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 |
---|---|---|---|---|---|---|---|---|
460 | hello friends in this session we are going to discuss another lead code problem lfu cache least frequently used cache which is different from lru cache least recently used cache it is good to understand lru cache implementation before understanding lfu cache i have given lru cache video link in the description please watch it if you are interested our cache comes with limited capacity we must provide cache capacity as part of the cache initialization we must implement two functions get and put get function takes key as input and returns the value if it exists it returns -1 if the value does not exist returns -1 if the value does not exist returns -1 if the value does not exist the put function takes both key and value as input it updates the value of the key if it is present otherwise it inserts the key value pair into the cache in case if the cache reaches its capacity limits then it should every least frequently used key before inserting a new item in case there are multiple keys with same usage frequency then remove least recently used key out of them the expectation is we should implement get and put functions at constant average time complexity let's directly jump into the solution since the solution is expected with constant time complexity hash map is the best suited data structure here we will store key value pair into this hash map insertion and retrieval of data takes constant time with hash maps let's assume that this hash map is our cache comes with limited capacity as per the problem statement let's assume that our cache capacity is 2. it can store maximum of 2 key value pays only any time when you try to insert new key value pair when it is at its maximum capacity it must evict one of its key value page to create a room for the new insertion the eviction policy is least frequently used we must identify which key is used least frequently and then delete it before inserting a new key so we must track each key usage count we will use this hash map we have named it frequency map in this hash map the key represents count and the value represents list of cachet keys why list of caches because it is very common that multiple keys usage count can be same so we are using list of keys as a value in this hash map now when the least frequently used keys are more than one in this list how to choose which key to be deleted as per the problem statement we need to identify least recently used keys out of this list so rather using list as a value here we will use doubly linked list as a value so that we can control node order based on usage i suggest to watch lru cache implementation to understand better why we need doubly linked list here in general registering raw value into this hash map as it is we can store linked list node as a value in this hash map so we can keep track of each key's usage count within the node itself then we can easily identify in which linked list this node is part of we can easily relate these two hash maps i mean here we have count as a key and linked list as a value there will be multiples of key value page if we know the count then only we can identify respective nodes linked list in this hash map in our case node will be holding the key usage count if we know the count then we can directly relate to the linked list in this hash map in general if we want to reduce code or if we want to use language provided linked list as it is we don't need to maintain node objects we can simply store raw values into this hash map as it is in such cases how can we maintain key usage count this is why we need this hash map to maintain key usage count here in this hash map key will be cache a key and value will be usage count if we know the key then we will get its usage count from this map and then we can identify which linked list it is part of now how do we know least usage count at any given point of time we need to keep track of it this variable min usage count will hold least frequently usage count at any given point of time let's apply these actions and understand the logic better initially the cache is empty we are making a put call here key is one and the value also one we will be inserting this key value pair into the cache in general we will check that the key already exists or not in the map before insertion we will consider put call also as part of usage count let's track the count so our key is 1 and its usage count is 1. now in the frequency map we will add count as 1 and we will maintain a linked list in the list we will add our key here we will maintain key usage order in this linked list we'll update minimum usage count value as 1 here by default we will update this value with 1 during any new insertions let's go to the second action again it is put call since the cache size is 1 and the key 2 does not exist in the cache just insert it we will update usage count also the key is 2 and its count is 1. since its usage count is 1 we will add this key under this linked list itself now look at the insertion order the tail is always carries the most recently used case and the head always carries the least recently used case so it is always easy to identify which is least recently used key from this list the next action is get call the key one is exist in the cache simply return its value before returning the value we must update our usage counts increment key 1 value to 2. since the count became 2 we need to maintain a separate list for count 2 here and then move key one from here to here the next action is put call if you notice here the cache is already at its maximum capacity too there is no room for new element so we must evict one of the element before adding another element based on our minimum usage count variable the least frequently used count is 1. based on this 2 is the key supposed to be evicted remove two from here delete this entry also delete this entry now add new entry into the cache also update its count key is 3 count is 1 and here we will add key 3. the next action is get call since key 2 does not exist in the caching simply written -1 written -1 written -1 the next action is again get called key 3 exists in the cache return the value before returning the value update counts as well increment key 3 count as 2 here and move 3 from here to here since count 1 linked list is empty we need to update minimum usage count value from 1 to 2. the next action is put call since the cache is at its maximum capacity we must evict one of the element before inserting another element least frequently used key count is to here but there are two keys in this usage count so we must find least recently used key from this list as discussed linked list head carries the least recently used key here key 1 is part of linked list head so remove this delete this entry here delete this entry also and then insert new element 4 update its usage count four the count is one and the key four will be here now update least frequently accessed counter to one the next action is get call since key 1 does not exist return -1 since key 1 does not exist return -1 since key 1 does not exist return -1 the next action is again get call since key 3 is exists return its value before returning its value let's update its count increment its count to 3 and here since count 3 does not have a list create one before moving from here to here and the next action is again put call since key 3 already exists just update its value with 8. update the counters it is 4 since 4 count 4 does not have a list create a list and move key 3 from here to here so this is how lfu cache least frequently used cache will be functioning hope you understood let's write code now i have already copied method signatures from lead code as it is let's declare a hash map to hold key value page let's declare another hash map to hold key counts now declare a hash map to hold key frequency usage count we will be using linked hash set as a value here declare a variable to hold cache capacity declare a variable to hold least frequently used key count at any given point of time we have initialized its value with -1 we have initialized its value with -1 we have initialized its value with -1 let's fill the constructor we will fill frequency map for count 1 with empty linked list now let's fill get function as a first step let's validate does the key exist in the cache or not written minus 1 if it does not exist if it exists update counts before returning value get the key usage count from counts map increment the count value by 1. since we have incremented the count remove the key from the counter linked list from the frequency map when the current minimum count linked list is empty then it should be pointing to next count as a minimum value if frequency map does not have linked list for the given count add it now add the key into the respective count linked list finally return the value from cache now let's update put function simply return back if capacity value is less than zero check does the key exist or not in the cache if it exists then update its value update counts by simply calling git function we will be reusing code here get function increments the key usage count whenever required and return back in case the key does not exist then check the cache current capacity in case if it is at its max capacity limits then we need to evict one of the key value path so identify the head element in the linked list as per our earlier discussion now remove the key from all possible places all possible hash maps now insert the new key value pair into the caching update its count with one make sure to update least frequently used count as one as it is a new insert also update frequency map with key we are done with coding let's test our code i have already written main method to save some time here we are making sequence of put and get calls let's run here is the output which is as expected so this is about lfu cache hope you like the video thanks for watching please do like the video and do subscribe to the channel thank you | LFU Cache | lfu-cache | Design and implement a data structure for a [Least Frequently Used (LFU)](https://en.wikipedia.org/wiki/Least_frequently_used) cache.
Implement the `LFUCache` class:
* `LFUCache(int capacity)` Initializes the object with the `capacity` of the data structure.
* `int get(int key)` Gets the value of the `key` if the `key` exists in the cache. Otherwise, returns `-1`.
* `void put(int key, int value)` Update the value of the `key` if present, or inserts the `key` if not already present. When the cache reaches its `capacity`, it should invalidate and remove the **least frequently used** key before inserting a new item. For this problem, when there is a **tie** (i.e., two or more keys with the same frequency), the **least recently used** `key` would be invalidated.
To determine the least frequently used key, a **use counter** is maintained for each key in the cache. The key with the smallest **use counter** is the least frequently used key.
When a key is first inserted into the cache, its **use counter** is set to `1` (due to the `put` operation). The **use counter** for a key in the cache is incremented either a `get` or `put` operation is called on it.
The functions `get` and `put` must each run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "LFUCache ", "put ", "put ", "get ", "put ", "get ", "get ", "put ", "get ", "get ", "get "\]
\[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[3\], \[4, 4\], \[1\], \[3\], \[4\]\]
**Output**
\[null, null, null, 1, null, -1, 3, null, -1, 3, 4\]
**Explanation**
// cnt(x) = the use counter for key x
// cache=\[\] will show the last used order for tiebreakers (leftmost element is most recent)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1); // cache=\[1,\_\], cnt(1)=1
lfu.put(2, 2); // cache=\[2,1\], cnt(2)=1, cnt(1)=1
lfu.get(1); // return 1
// cache=\[1,2\], cnt(2)=1, cnt(1)=2
lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
// cache=\[3,1\], cnt(3)=1, cnt(1)=2
lfu.get(2); // return -1 (not found)
lfu.get(3); // return 3
// cache=\[3,1\], cnt(3)=2, cnt(1)=2
lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
// cache=\[4,3\], cnt(4)=1, cnt(3)=2
lfu.get(1); // return -1 (not found)
lfu.get(3); // return 3
// cache=\[3,4\], cnt(4)=1, cnt(3)=3
lfu.get(4); // return 4
// cache=\[4,3\], cnt(4)=2, cnt(3)=3
**Constraints:**
* `1 <= capacity <= 104`
* `0 <= key <= 105`
* `0 <= value <= 109`
* At most `2 * 105` calls will be made to `get` and `put`. | null | Hash Table,Linked List,Design,Doubly-Linked List | Hard | 146,588 |
1,287 | hey everybody this is Larry this is day 11 of the good day challenge hit the like button hit the Subscribe button Jo the Discord let me know what you think about today's bar I'm in uh Ali Shan here um watching the sun rise the sun has already risen but hopefully so will your the code skills let's do this one yeah I hope you like the intro uh yeah let's do day 11 I'm here in where my chai right now uh much uh the internet should be faster so hopefully I should be getting you know I don't know whatever fast internet things anyway to F is 1287 element appearing more than 25% in sorted away appearing more than 25% in sorted away appearing more than 25% in sorted away all right there's exactly one okay uh yeah I mean if it's sorted then that means that uh that number of things in a row will um well will be the same number right so my first thought is to do a scan and then you know like for index I you do I plus um n/4 or something like this do I plus um n/4 or something like this do I plus um n/4 or something like this right and of course that's still linear time so that doesn't help enough I'm curious whether you can do it in all of one I believe you should be right I don't know about one but at least log in because from the pitchon hole principle if yeah if there one if it exists in more than 25% then it has to be one of the like if 25% then it has to be one of the like if 25% then it has to be one of the like if you divide it into uh you know you divide and uh can't English right now if you divid in the way of length n into four Eco components or roughly EO um then um at the border it should be that one of them should be uh one of those numbers right uh and so we should be able to only need to check those cuz it has right okay well let me step back for second I know that this is easy there other ways to do it that's easier but I'm trying to like you know uh upsolve this a little bit let's say a number appears in more than half the away and it's sorted right if that's the case then you know that the middle number uh has to be um the element right just because there's no way to put it so I think by the same logic by the pigeon ho um one of those elements should be it right so here then now we can do something like um yeah like you have one of those three numbers which is at n by 4 uh or n no it's uh n no yeah n by 4 this may be very pointed off by one that's why I'm a little bit worried about it but uh and then right CU those are the if you divide them into four equal parts those are the integers that could be like I said possibly off by one so it has to be one of these numbers and the way that you can I mean and there's a easy thing right if that if one of these three numbers is true then you can just binary search um the beginning and you can binary search the end and then you can figure it out and that's all of log n right but can I do better probably not I guess because that could be just any uh it could appear like you know within the one quarter it could be any of those places right so you can't just like be oh this is the beginning let's add one let's do it that way then right so let's say candidates uh is uh and I'm not going to lie you know I'm experimenting so as a result this may be wrong and it may be wrong not for any like math reasons just uh possibly all five ones uh and I'm too late and you could like I guess add one to these so then now you're checking six candidates or something like this so you really want add n minus one or something like this so it would be like nine candidates I don't know something like that if you want to play around with it but yeah um H right so then now going do a BC left right of or just find like or just account of uh X right and then that'll just be bisc bicec left of X just assumes that this is in the array which it should be because we're only getting it from here right so that's is the first index and then the last index is going to be BCT right minus one of course so then now uh might as well plus one right so then now uh yeah for X in candidates if count of X is greater than equal to n/ 4 or maybe just times four equal to n/ 4 or maybe just times four equal to n/ 4 or maybe just times four for you know return X and then now assert for so it's not possible again I probably made it way trickier and funner more fun than it needs to be let go submit maybe there's yeah like H like I said they all possibly uh off by on why is this I mean it's probably just the way I said candidates like I said uh okay uh so candidate is two three and three should be good right okay so why is this no good why are you no breno H oh more than oh okay this is an actually unrelated bug then uh this I did uh 25% not okay actually that did uh 25% not okay actually that did uh 25% not okay actually that worked in theory that would have worked the first time if I didn't have that Eco thing what did I do last time did I do the same thing oh know I did some lazy thing and still got it wrong twiice it's kind of that but uh you know even I am growing as an engineer but yeah as you can see this is um two binary search and you but you only do it three times so it's going to be log in and yeah that's what I have for this one let me know what you think let me know if this makes sense and yeah oh my head ler stay good stay healthy do go mental health I'll see yall later and take care byebye | 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 |
501 | hello and welcome to another video in this video we're going to be working on find mode in a binary search tree and so in this problem you have the root of a binary search tree without duplicates and you want to return the mode I.E the and you want to return the mode I.E the and you want to return the mode I.E the most frequently occurring element in it if the tree has more than one mode return them in any order assume BST is defined as follows the left sub tree of a node contains only nodes with keys less than or equal the nodes key and the right sub tree contains only nodes with keys greater than or equal to nod key both left and right sub trees must also be binary search trees and so what's weird about this problem is usually for almost every problem with the BST has unique values but in this one you can have weird stuff like this where you have repeating values so here our mode would be two and you might think like well I can just somehow figure out a way to track like may maybe all my nodes with the same values would be right next to each other right so I'll have like one two and then maybe I'll have like a four over here and then like this might have another four and so on but the problem is this isn't necessarily true so you can't just like keep track of two nodes next to each other and that's what I actually originally tried to do and I actually made a problem where I would just like check you know do I have the same node and if I do let's increase my count and so on and so the other example is for this one with a node with just zero you want to return zero so here is the case that I got you that was weird and so here it is right here so let's think about this one so like I said before you can't really just like check for nodes that are right next to each other because here there's a six here and this does still maintain the property of like a BST where yeah every node here is bigger than two and every node here is less than or equal to six but they're not necessarily unique so the question is like how do I keep track of this six and how do I keep track of this two and this two right like I can't just like see what values returned or something right like I can't just like return up here cuz then like how do I maintain the six value and maintain all these other values that seems kind of hard and so the property we're going to use is no matter even if a BST is like that now obviously uh so really quick and really easy solution is just either have a hashmap or like do some kind of traversal and get an array of all the values and then from there get the frequencies like that's like an easy problem right like you just Traverse every node get a hash map and then you know check out which key has like the biggest value so I'm not going to go over that one but for a BST even like this where you do have duplicate values there is still a property that an inorder traversal will still give you increasing value so let's actually run an inorder traversal of this and see what we get and then this will give us like intuition of what to do so remember in order traversal is left root right so we're going to run this traversal so we're going to start here so obviously left which means we go left as far as possible so we will go here now there's nothing here so now we're going to so we try to go left here we can't right there's a null node so then we will get the root so we will put in zero into the array now we will recurse so this node is or actually we're going to do right but there is no node here so now we will recurse up back to the two now we went left now we're going to get the root now we are going to go right now remember we go left before getting the root so we go left there is nothing left here so now we're going to get this value so two and then right and there's nothing here so now we will recurse up here to the four we already went left so now let's get the root let's recurse right now we'll go down here there is no left now let's get that root let's go right nothing there so now we're done here recurse back up to the four we're done with a four recurse back up to the two we're done with two recurse back up here and now we did the left so now we'll do the root then we will go right so we go left first go left nothing root 7 right nothing recurse back up then here we get the root then we go right so left is nothing root is nine and then go right and we actually oh we wrote down the value but anyway yeah then we go right and then we recurse uh so we're done with this node so we recurse up we're done with this node and now we are done with this node so if you actually take a look even with duplicate values no matter where they are for a BST and we're a traversal all of our values like all of the values that we care about are right next to each other right so all the twos are next to each other all the sixes are next to each other every number is next to each other so we're going to get some increasing array where all the duplicates are right next to each other so how do we use that to our advantage like how do we get the modes in place not counting for their recursive stack space so they are saying like yes their recursion of a tree will be oven but not counting that how do we actually get the mode without actually storing the in veral Array or hashmap and so that part we're going to use four variables and it's going to be really straightforward so we're going to have four variables so one variable is we're going to have our result right that we're actually going to be returning we'll call this like modes maybe or whatever we want to call it right let's say then we have a modes count and this variable will represent uh actually let's call this like I don't want it to be uh just do this or something okay so it's going to be one variable but I just want it to have like the spell check thing so essentially this is going to represent the count of every single mode in here and so for this problem if there are multiple nodes that have the biggest value they're all going to have the same value right so all of these modes in here will have the same frequency so modes count will just represent like the frequency of all of these modes then we need two more variables we need a Curr variable so let's write it down here and Cur is going to represent let's call it current so it doesn't uh give us an error so current will be the current number we're on so we can initialize that To None to start off and then we have a current count which is like the count of the number that we are on and we'll iniz this to zero okay so now we can basically so I'm not going to show this DFS again but this is going to be the way that the things are returned right so we're going to return this then this and this then this right like if we just return the uh or not even return we can just like when we like we go left then when we do this root part uh that's when these values will be checked right so essentially what we can do is whenever we are at these we can actually uh get the values so actually I will kind of show traversal one more time I guess U maybe I think what I could do is I can actually take this picture and I can just copy it and then I can delete all of this there we go perfect now I can paste it so we can kind of show what this traversal will look like one more time with these things so essentially we start here and we go left then we go left here and we have nothing so then what we're going to have here is we are going to take this value now right this will be the current value and we'll say okay well if this value is different than the current value then let's update the current value so the current is currently none so it is different so this current oops this current will now be zero and the current count will be one right that's like the node we're on then we'll obviously do this and we'll recurse back up here and so that's kind of how the recursion will work now I'll just work with these values like their recursion is going to be the same way and this value just means like we are currently at this value so we did the zero now let's look at the two so for the two what's going to happen is we're going to say okay oh by the way I forgot one step so once we do get this current value we're going to check is the current count greater than the nodes count or modes count and if it is that means that this node is now the biggest occurrent node right so this zero occurs more than every mode so mode should be deleted and we should have a new mode of what we have so we're going to have mode zero with a count of one now let's actually move this over here so we don't actually need this like tree but we will just go through the node so we did this one now we're going to go to this node so we went so and this would just mean like you go down here then you Rec curse so this node means like you were just at the node right it's left root right so this is this root part so for this two we're going to say okay what's the current node is it two no it's not it's zero so then we need to replace zero with two and that means if since we have a new current node it's going to have count one now we're going to check what's the mod's count it's one and our note is also count one that means that this node should be added to the modes right because it has the same count as the biggest node in there so if the node if the current count is equal to the modes count then we're just going to want to add that node in there so we add it in the node then we go to this node and we say okay what's our current node it's still two so now we have to increment the count then we're going to check is our count greater than nodes count or modes count yes it is so then modes count gets updated to two and because our current count is greater than all of these that means that these need to all get replaced so I think I should be able to just delete now yeah so these just all need to get replaced by this uh two oh I can't I there you go cuz essentially like if we have a bunch of numbers with frequency one and then we get a number with frequency two that means that number is bigger than all of them so then that's our new mode but if it's the same as the other ones then we'll just depend okay so now we go to the four and we're going to say okay well four is not two so that means our count should be one now and since the count is less than modes count we don't need to do anything right this can't this isn't one of the modes so we go to the next number so we go to six so we replace the four with six and our count is one and since it's less than two we don't need to do anything then here we will have six and our current count will be two so it's the same so we need to actually add it to our modes and then for seven it'll be count one which will won't do anything for eight it'll be count one right eight count one and for nine it'll be count one so that's kind of like the algorithm of getting the most frequent number if you know all the duplicates are in order you just keep track of like how many of the number do I have and if it's greater than what I had before I will replace that number and I'll delete this whole array of modes because now this is my most occurring element and if it's the same then I'll just add it to the array because if I have a bunch of numbers with the same large count then I want to just keep adding to the array so that's kind of the algorithm and it's pretty straightforward so we can write this as well so if current count is greater than modes count then we want to replace array with Cur and update count if they are equal just add Cur to modes and the nice thing is that even if we add a number like let's say we add this six the nice thing is if there are more then we'll just get a greater count and we'll just replace it later so it's okay to add right away like it's not going to cause an error and that's pretty much it for like the algorithm like you basically have to realize that in a in an uh inward traversal even with this tree with duplicates I know it's kind of rare to have duplicates but even with this problem with duplicates you're still going to have all of your same number right next to each other and then you can just keep track of like how many are there and by doing this by just checking the number one at a time and just only keeping track of the last number and these four variables we keep like the minimum information we need to update our modes without actually storing this whole array right so this modes is going to be the result which we have to have obviously but then for the modes count and current count these are all just variables so this is just like three variables we're not actually storing the array so this is like a much better uh time complexity like I said also be the same but if you assume that the traversal is zero and you're not counting your result then this would be an o one space solution okay and so now we can code it up okay so instead of mode I'm going to call this result and I'm going to have a result count and a cur count and we're going to have a Traverse function which if there's not a node we can just return I'm not going to check for like nodes existing I'm just going to recurse to them and then we will go left and now we have to do our Logic for actually uh actually like getting the get filling out these values so essentially because we made these outside of the function we don't have we can't modify them inside the function unless we use non-local so we're going to nonlocal non-local so we're going to nonlocal non-local so we're going to nonlocal them which basically tells python like hey we have these variables we can use them we can modify them otherwise you can use a dictionary with these keys or you can make these like class uh variables like self Cur and so on other one on all of those work so now we can do our logic so if node. Val equals Cur that means that this value is the same as the last one so we just increment C count otherwise CER equals no. Val right we have a new value so if we have a new value the count is one and the new value is this now we have to check if the Cur count is greater than the result count if it is that means that the count of this is greater than all of other modes so all those other modes should be deleted and our result should just now be Cur and result count equals curve count now other or there's one more case right where the Cur count equals the result count and if this is the case so if the Cur count equals the result count that means that this node should just be added into the modes so it's going to be res. append L and we can then Traverse to the right side right it's left root right for inorder traversal so Traverse no right and finally we call this function with the root and we return result see what happens and looks like it's fine and it's pretty efficient so for the time and space basically um if you do count the stack of traversing it would be o of n because worst case scenario your tree is entirely right sided right where every node only has a right child um but if you don't count the stack it would be of one because this is just the result so that we have to have this and then these are all just uh local variables and for the space actually so this was the space yeah this is the space um for the time we do have to Traverse every single node in the tree so that is okay uh and yeah so that's going to be all for this problem hopefully this is helpful definitely think the uh the follow-up section where you have to do follow-up section where you have to do follow-up section where you have to do it in constant um space is definitely like not an easy problem but just like a normal hash map or something would be an easy problem so hopefully you enjoyed this one 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 | 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 |
10 | hey everyone welcome back now let's write some more neat code today so today let's solve a pretty hard problem regular expression matching so we are given an input string s and a pattern or a regular expression p and we want to implement regular expression matching and these are the two special characters that we're gonna have to worry about a period and a star so the stars or so the period will match to any particular character and the star basically means that any character that comes before it can be repeated zero times or it can be repeated infinite times right so it can be repeated as many times as it needs to be and the match or the pattern has to cover the entire input string so it has to match the full input string so one example is let's say so these are the special characters we worry about right the period and the star if we don't have either of them then it's basically string matching right so we see in this example we have two a's right that's one input string and a single a so basically do these strings match each other they don't match each other so we have to return false meaning that the input string s does not match this regular expression and remember it's only going to be a regular expression which possibly has the star or possibly has the period now imagine instead if our pattern was a period so in that case we would compare it to the string double a and we would see that yes they do match because remember the period can be any character so we could say okay we'll given this pattern this could be double a so it would match this input string what if we were checking does it match this input string a b in that case it would also match because this period could then turn into a b so it would be a b and these two match each other but of course if we had a period checking if it matches double a it doesn't because they're not even the same length this has three this has two there's no way we could put any characters for these two periods that would match double a and what about this second example let's say the input string is double a and the pattern is a star so what this star means is a star so a star basically means that the element that comes before this a could be repeated multiple times or zero times so the possible strings that this pattern could match to could be an empty string because this character could be repeated zero times right so empty string this character could be repeated once so a single a this character could be repeated twice so double a this character could be repeated three times so aaa and so on right we could repeat this a infinite number of times but if you take a look at our input string we're only checking does it match double a of course it does right we just repeat the a twice so in this case we return true a third example so let's say our input string is a b and we're checking does it match the pattern dot star so basically what this dot star means is we could have a string that's empty right repeating the dot zero time so empty string uh we could repeat the dot once so dot we could repeat it twice double dot right and so on and so let's say this right double dot is what we're looking for we're checking does this match a b well one of the dots could be a and one of the dots could be b so that matches double dot so this would return true so as you can see that there's probably going to be a few edge cases we have to deal with right the complexity really mainly comes from the star the dot isn't so difficult right but the star makes things interesting so let's just try to brute force this let's look at one example this example let's say this is our string s and this is our pattern a star so as you know the star is really where the complexity comes from so let's make a decision tree let's brute force this so this is the string we're trying to match to this is our pattern a star we know so we're first gonna look at the first a and then we're gonna look at the first character of this now this isn't just an ordinary character there's a star that comes after it so this could be repeated zero times or more times right so let's brute force this we know we have a choice are we gonna repeat the a at least once or are we gonna repeat it zero times if we repeat it zero times then we end up with an empty string right if we repeat it once we end up with a single a now clearly we want the single a because it matches this right and if we decided to have an empty string meaning we want this star to or and this character a to repeat zero times then we would have to move to this position right and there clearly isn't any character here maybe there would be a b maybe there would be an a but there's clearly nothing there so this is this decision is going to stop right we cannot go any farther all we can do here is an empty string but it's okay because we ended up matching with this a when we were on this path right so now the character we're looking to match in the input string is this single a so now again we have a choice are we gonna repeat the star like in this spot we repeated the star and this we didn't repeat the star now again we have that choice are we going to repeat the star or are we not going to repeat the star if we don't repeat the star we're going to end up with a single a and then we're gonna have to be shifted over to this position meaning we cannot use the star anymore so we're gonna stop right this is going to be our string a single a but you can see in our input string was a double a so really our other decision where we do repeat the star at least one more time is gonna lead us to double a and that's good because now we have the second a meaning we matched this second a right so now in reality we have matched the input string but just to show you in theory we could keep going we could decide not to use the star anymore right we would be shifted to that position and in which case our ending string would just be double a or we could use the star one more time meaning we'd get triple a but then of course you can see we're even bigger than the input string that we wanted to match so we stop but we see that we did end up finding the results since we found the result right we found the input string that means that these do match right so we would return true because the input string matches the regular expression but as you can see we're doing a decision tree this is not exactly going to be super efficient right how many decisions are we going to have well any time we get to a star we're going to have two different decisions how many times can we repeat that decision it's going to be n where n is the input string s so clearly you can tell this is not super efficient but in case you haven't noticed this is a dynamic programming problem and if we take this and we implement a cache then we can get this time complexity down to n squared or in other words really we're getting it down to n times m where n is the length of the input string and m is the length of the pattern and this is if we do the top down memoization with a cache we can also do the actual bottom up dynamic programming solution so the bottom up dynamic programming solution and both of these actually have the same time complexity so i'm going to show you the top down coding solution but once you know the top down solution getting the bottom up full dynamic program solution is not usually impossible but before that let's look at one more example so the index i'm going to use so let's say this is our input string s and this is our pattern p so i'm going to use two variables to keep track of where we are in each of the strings i'm going to use i to tell us where we're at in the input string i'm going to use j to tell us where we're at in the pattern so remember whenever we reach a character that has a star that comes after we have two choices so i'm going gonna draw our decision tree we have a choice to use the star or we have a choice to not use the star so in this case if we use the star meaning we use the character at least once we're gonna get a c right we're gonna repeat the c just once if we don't do that we're gonna get an empty string so i'll just draw this dash for empty string now you can see we have a c but the first character of our input string is a so really what we want to do is not use this c any times meaning we do not want to use the star we don't want to repeat c even a single time so the decision we want is not this decision but this is the path that's going to lead us to the correct answer so what am i going to do with this j pointer i'm going to shift j so i'm going to shift j over here right so notice what we just did in this path where we do not use the star right we didn't use the star what did we do we ended up shifting j by two so we took j and then added two to it that's very important because any time we choose not to use the star we're gonna take our pointer where it's at and then shift it twice because we're shifting one to get to the next character but also look at the star we don't want to land on the star we want to land at the next character and what about pointer i are we going to shift that well since we didn't use the star that means we weren't able to match with the character a right so actually i is going to stay exactly where it is so in this decision what we did is we left i the exact same and then we took j and added 2 to it and this is very important because this is exactly what i'm going to do in the code so i remains the same j plus 2. okay so now we're still at this a but our j is over here so notice how j right after j is a star that means this character a can be repeated zero times or it can be repeated one or more times so again we have a decision to make so one decision is we use the star at least once the other decision is we do not use the star at all so if we use the star once we'll get a string of a if we don't use the star again we'll end up with an empty list or an empty string so remember when we used the star over here we got a c that didn't match the a but now we actually have an a that exactly matches the character over here right but what about this path right now we have an empty string is this path gonna lead us to the correct answer well the only way to find out would be to continue on this decision tree right making decisions and stuff but i'm not going to show that because it's going to get pretty messy and you can tell by looking at the string since we chose this path we would have to leave i as it is and we'd have to add 2 to j so i would stay here j would be moved over here and then you see the pattern left at this point is just b does that match the input string s it definitely does not right so clearly this decision is not going to lead us to the correct answer but let's look at this is promising let's continue on this path so if we end up using the star as we did right now how are we going to update our pointers well take a look at i we matched a exactly what we wanted to do right so what are we going to do with i well we're allowed to shift it by 1 now so we're going to take i and move it over here right we already matched this character we don't really need to match it again but we do need to match the remaining string of s a and b what about j well j can stay the same because we use the star once we repeated this a once now we can continue to repeat it or we can repeat it zero times and we can make that decision by rem by leaving j exactly where it is so when we go down this path when we actually use the star what we're going to do is add one to i but leave j exactly as it is and this is important too these two things are important because this is exactly what i'm going to do when i write the code so since we're still at j and there's still is a star that comes after it we again have two choices so we can choose again to repeat this a or we can choose to not repeat the a so if we repeat the a then we're gonna get the string double a right and if we choose not to repeat a then we're gonna have a single a and then meaning we're not gonna use this anymore and then we're gonna have a b that comes after right and you can tell a b by itself does not match the entire input string right so clearly this is not going to be the solution but you can see that the new character we just added the single a it matches exactly what we were looking for another a right so that means we can repeat what we just did up here we can take this i and shift it by one and we can leave j exactly where it is so now i is at the last character in s and i was shifted by one and j remained the same okay i'm starting to run out of space but let's see if we can finish this again we're at this position where star comes after right j is over there so we have two choices we can use the star or we can not use the star if we use the star we're going to get triple a right and see the third a it does not match the character that we're currently at b so clearly this is not going to be the decision we go down if we don't match the a then we're going to end up with a double a right exactly what we had before right but in this case as we usually do when we don't use the star what we're going to end up doing is taking i leaving it where it is because we know we didn't match this character right now but we're going to take j and add 2 to it and since we add 2 to j that means we have to shift it by two so now j is going to be at the last character in p at the b and notice how j now the character after there's no star that comes after right so we actually don't have a choice right now we are only checking does the character at j this b does it match the character at i this other b we don't have a choice because there's no star we're not allowed to repeat this b zero times or one time or three times we have to use it only a single time right we must use it we're required to use this b but lucky for us we have a b right here right so we don't have a choice right now we're just checking do they match and they do so what we're going to do now is see that our string that we created with our regular expression is now a and b right and that matches what we wanted to in the input string but it's important to note when we do not have a star we're strictly checking do the characters equal we're checking does s of i equal p of j and if they do equal what we're gonna do how are we gonna update our pointers i and j we're gonna take i add one to it and take j add one to it we're going to do this in the code so now when you see if we take our i and then shift it over here so i'm just going to make a barrier between these two and if we take our j and shift it by one you see both of these are out of bounds right i is out of bounds and j is out of bounds that's how you know we have perfectly matched so really when we say that i is greater than or equal to the length of s meaning it's out of bounds and j is greater than or equal to the length of p that's how you know they have matched exactly perfectly but my question is what if i wasn't was i was still in bounds but what if j was out of bounds what if j was greater than or equal to the length of p so an example would be this let's say our input string was a right that's our input string our pattern is a is just a single a right let's say our index of i was here let's say our index of j was over here right clearly this does not match this is our string s this is our pattern p this does not match this right so basically if only j is out of bounds then they do not match because we still have some string in the input that hasn't been matched but what if the opposite was true what if i was out of bounds right i is out of bounds so i is greater than the length of s but j was still in bounds what does that look like an example would be this let's say we had an input of a and let's say our pattern was a star and b star so let's say our index of i was shifted by one so our i is over here and we took our j starting over here we matched the a single time then we shifted our j to be at this b character so basically i'm asking so with our i over here and our j over here do these two strings match each other technically yes right because this b could be repeated zero times and still match the input a so just because i is out of bounds doesn't mean we have to return false but as i just showed a second ago if the j happens to be out of bounds so if the j is out of bounds then we must return false i know this is probably a little confusing with these edge cases but i hope the examples make it clearer and i hope the code that i'm about to show you makes it even more clear so again i'm going to do the top down memoization dynamic programming solution not the bottom up i think the top down is easier to understand when you're first starting this problem just doing the bottom up solution is more confusing in my opinion but we are going to do this recursively so i'm going to do a nested function depth first search inside of our uh is match function i guess you could call this backtracking or you could call it uh whatever else you wanted i'm just going to call it dfs and we're passing in i and j which are going to tell us what position we're at in the input string s for i and j is going to tell us where we're at in the input string p so as always with recursive functions let's start with the base case i just showed you that if i is out of bounds and j is out of bounds that means we have found our solution that means we were able to match the pattern to the string so we can return true but as i showed you if i is not out of bounds but j is out of bounds we have some string in s that we haven't matched and there's no way we're going to be able to match it so we have to return false so these are our two base cases notice that given these two cases it's still possible that i could be out of bounds right i technically could be out of bounds and neither of these return statements would execute right because this needs i and j to be out of bounds so we would pass this and i could still be out of bounds but i'm going to show you how i'm going to handle that right now so the first thing we want to check is there a match between the first character so is there a match between s of i and p of j and the other thing we could check technically right p of j could have a period in that position meaning the period matches to any character right so we have to check this or check this and since we know i could technically be out of bounds before we even check this we have to confirm that i is inbound so i is less than the length of s so strictly less than not less than equal so if these conditions are satisfied that means the first character of each string matches exactly the reason i'm putting this in a variable is we're gonna have to repeat it a couple times in the following code so the first thing i want to check is does the following character in uh the pattern string so p of j plus one does it match the star is it a star and the reason i'm checking this first is because the star has the highest precedence and i'm checking j plus one because we know the pattern the first character in the pattern string is never going to be a star and since i'm checking p of j plus one i have to first check that j plus one is inbound so i have to check that it's less than the length of p so if this is true that means we're gonna have to take care of this star right and we remember when we encounter a star we have two choices so i'm going to do a recursive call right that first search the first choice we have is don't use the star right if we don't use the star we leave i as it is and we take j and add two to it right that's one now we know we have two choices if either of them evaluates to true then we can return true right we're brute forcing this right now so the other decision we have is use the star right so if we use the star that means we can take i and add one to it and we can leave j where it is but remember we can only use the star if there's a match between the first character right the first two characters right because we only want to use the star if there happens to be a match so really here we're checking if there's a match and this whole thing about this recursive call evaluates to true right so i'm going to wrap this in parentheses so basically what i'm saying is these are our two choices this is one recursive call and this is another recursive call if either of these evaluates to true then we can return true and that's what i'm doing basically by putting these on the same line so i don't know the best way to format this maybe this is somewhat readable so if either of these is true we're going to end up returning true if neither of them is true we're going to return false so this by itself this these three lines of code handles that star for us now if this isn't true meaning we don't have a star character then we're looking just for a simple match right so we can just check if match if the two characters match then what are we gonna do well remember we can then increment i by one and we can increment j by one and return the result of that now if there's not a star and the characters don't match in that case it's simple right then we can just return false meaning that this string will never match the pattern so then we return false and this is the brute force solution it's actually as simple as that so let's return it and let me show you how inefficient it is right now so we can call our debt for search starting at zero in both of the strings oops i had a syntax error so we had double equal over here we have to put double equal over here oops and one last thing when you have multi-line stuff in python when you have multi-line stuff in python when you have multi-line stuff in python you have to wrap it all in parentheses so i'm just going to wrap this entire thing in parentheses hopefully it's still readable and a third bug so i don't know why i checked if j is out of bounds of string s when j refers to the index of string p so sorry about these bugs but okay so this time it finally worked you can see it's not super efficient right it took about i think this is 1.3 seconds think this is 1.3 seconds think this is 1.3 seconds and it was 11 so we did the top we did the brute force solution but look i forgot to do the memoization right so let's actually do the caching now and make this efficient so i'm going to create a cache it's going to be a hash map so before we do anything whenever we call this function we're first going to check if i if the pair i j has already been added to our cache if it has then we can return it right so this is going to basically not have to is basically going to take care of repeated work for us if we execute this we're not going to have to do all the repeated work but now we actually have to use this cache so instead of returning this right away you can see down here i'm going to actually take this and add it to the cache so at index ij i'm going to put the value that this returns to and after that after we add it to the cache then i'm going to return it and i'm going to do the exact same thing down here so adding this to the cache and then we can take this and return it so we're all we're doing right now is caching the work that we do so we don't have to repeat it lastly down here we can say in the cache add false and then return false so basically by just adding what like four or five lines of code we've added the caching element to this function it was pretty easy so taking the brute force to the optimal solution was actually pretty easy and look at the result look how much faster this is 44 milliseconds 81 so we actually didn't even need to do the bottom up dynamic programming solution right and this i will be honest with you is not the prettiest way to write this code i've seen solutions that are a lot better than this but i really hope that you at least were able to understand what we're doing right the meat of the work is done in this call right basically these two lines of code are the work that we're doing right this is where we're handling the star case and you can see it's actually not that difficult right all we're doing is i stays the same j added two or i plus one j stays the same right and you understand why we're doing it like that from the picture that i drew but i encourage you to do the dynamic programming solution i'll probably link the code for that in the description and i hope this was helpful if you enjoyed please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon | Regular Expression Matching | regular-expression-matching | Given an input string `s` and a pattern `p`, implement regular expression matching with support for `'.'` and `'*'` where:
* `'.'` Matches any single character.
* `'*'` Matches zero or more of the preceding element.
The matching should cover the **entire** input string (not partial).
**Example 1:**
**Input:** s = "aa ", p = "a "
**Output:** false
**Explanation:** "a " does not match the entire string "aa ".
**Example 2:**
**Input:** s = "aa ", p = "a\* "
**Output:** true
**Explanation:** '\*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa ".
**Example 3:**
**Input:** s = "ab ", p = ".\* "
**Output:** true
**Explanation:** ".\* " means "zero or more (\*) of any character (.) ".
**Constraints:**
* `1 <= s.length <= 20`
* `1 <= p.length <= 20`
* `s` contains only lowercase English letters.
* `p` contains only lowercase English letters, `'.'`, and `'*'`.
* It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match. | null | String,Dynamic Programming,Recursion | Hard | 44 |
204 | hey everybody this is larry this is day 10 of the may legal daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's problem uh let's actually scroll down you should say that but one thing i wanted to point out was that you may notice my on the bottom uh there's this key stroke uh it's just so you could see it people sometimes ask me what i type uh usually you see most of it because it's on the web browser but just so you know anyway today's problem is count primes and as usual i do softies live so if it's a little bit slow you know skip ahead watch on 2x do whatever you need to do okay so counting number prime numbers less than a non-negative number less than a non-negative number less than a non-negative number well they're eight hints what is going on here um i'll say this one it's a little bit weird because it goes to five to ten to six so the ideal way to do it is just to do it once and then use the same code pre-cached answer in all your code pre-cached answer in all your code pre-cached answer in all your tests but maybe some i'm just not always easy um and because of this and the running time on the code and stuff like that is a little bit awkward but do i was it five times ten to six was that five million wow that's actually kind of hard um that's a lot of things to store in memory uh usually i would say yeah i mean but the standard way of doing this is just gonna be prime stiff uh i always i don't ever start do this i'm probably saying it incorrectly but that's just a safe um let's see try to think why is this end so large i might actually run out of time even if i do the sieve most of the time i'm gonna take a look at some hints just to see what they're because i mean could why i say that is that because i actually know i mean some of it is that this is just a little bit of a mind reading i don't think this test case is gonna be that complete but the test cases they give you it's a little bit of a guessing game of how because you can imagine that if i do something that goes to five times ten to the six but you know um if there are 100 cases on that it's going to time out no matter what so that's basically what i'm saying and i'm going to take a small hint and knowing that okay this is just this is not a small hand this is the sif and this is what i was talking about with okay fine i mean i know how to do it so i'm not gonna look at it that much i just thought that there'll be a smaller hint to be honest but uh but yeah that's implemented the dumb way and then we'll see if we can or we have to implement it there's uh a smaller way so yeah let's just say primes is equal to force times was it n plus one for n inclusive yeah not negative numbers n right less than okay yeah less than so we can just do n and then prime you know it's just four uh okay oh actually technically this is all true whoops uh we said primes of zero is equal to the primes of one is equal to fours and then now we start by just for x and range sub and i guess oh n plus one well it doesn't really matter i guess but uh if prime sub x i guess this actually doesn't matter because this is not inclusive for some reason if this is a prime then you go out and you keep on doing it until it is not right so i is equal to x while i is less than n um now whoops i'm gonna do it a little bit i mean so there's a technically you start with two times x but you can do some proofs to yourself that this is good and technically you're supposed to do this but i think you can also just do this oops um for reasons that you can maybe do the math one um because every other pro number is gonna be multiplied by two but i'm just gonna keep it simple for now uh yeah and then now just return uh i'll do it forget how to do uh whatever yeah let's just do a follow-up whatever yeah let's just do a follow-up whatever yeah let's just do a follow-up oh i guess i could just check it here as well count zero and let's start this at 2 by the way what are the test cases it's 10 0 1 and what is it five two three four five seven oh whoops oh okay obviously this is true but um yeah if and return zero i think that's the only case where that's whoa maybe not now that looks good um i'm going to just check one case just make sure that it's less than strictly which is if you give it a prime because i think that was a little bit un unclear in this problem uh so okay so it is good because it's two three five so let's give it a submit there may be micro optimizations here but we'll see how fast that goes okay so this is accepted like i said uh the problem with leak code is that they don't tell you how many test cases they give you so and but the tle is based off the sum of those test cases right so it's a little bit clearer that by this constraint is sufficient that it's gonna be fast enough but turns out that the sip is fast enough um you want to read up on it i guess look at uh yeah hint eight which is a little bit too much of a hint but i guess it's in eight i was just too lazy yeah so look up say if this is going to be of n space and o of n log and time um the proof is there i'm not gonna go over too much um you can you know do summation and this is uh for competitive this is definitely important and well known and something that you should know um but for interviews i don't i can't imagine number theory comes up that much so i wouldn't worry about it that much uh but it's hard to say but you know i'm just saying that if you have other things to prioritize then prioritize other things but otherwise yeah uh that's all i have for this problem let me know what you think about the typing thingy bye anyway uh yes so yeah have a great rest of the week it's monday hit the like button hit the subscribe button join me on discord and stay good stay healthy and i'll see you tomorrow bye | Count Primes | count-primes | Given an integer `n`, return _the number of prime numbers that are strictly less than_ `n`.
**Example 1:**
**Input:** n = 10
**Output:** 4
**Explanation:** There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
**Example 2:**
**Input:** n = 0
**Output:** 0
**Example 3:**
**Input:** n = 1
**Output:** 0
**Constraints:**
* `0 <= n <= 5 * 106` | Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less than n. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up to n would be O(n2). Could we do better? As we know the number must not be divisible by any number > n / 2, we can immediately cut the total iterations half by dividing only up to n / 2. Could we still do better? Let's write down all of 12's factors:
2 × 6 = 12
3 × 4 = 12
4 × 3 = 12
6 × 2 = 12
As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, if n is divisible by some number p, then n = p × q and since p ≤ q, we could derive that p ≤ √n.
Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?
public int countPrimes(int n) {
int count = 0;
for (int i = 1; i < n; i++) {
if (isPrime(i)) count++;
}
return count;
}
private boolean isPrime(int num) {
if (num <= 1) return false;
// Loop's ending condition is i * i <= num instead of i <= sqrt(num)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
} The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up to n. But don't let that name scare you, I promise that the concept is surprisingly simple.
Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" by SKopp is licensed under CC BY 2.0.
We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well? 4 is not a prime because it is divisible by 2, which means all multiples of 4 must also be divisible by 2 and were already marked off. So we can skip 4 immediately and go to the next number, 5. Now, all multiples of 5 such as 5 × 2 = 10, 5 × 3 = 15, 5 × 4 = 20, 5 × 5 = 25, ... can be marked off. There is a slight optimization here, we do not need to start from 5 × 2 = 10. Where should we start marking off? In fact, we can mark off multiples of 5 starting at 5 × 5 = 25, because 5 × 2 = 10 was already marked off by multiple of 2, similarly 5 × 3 = 15 was already marked off by multiple of 3. Therefore, if the current number is p, we can always mark off multiples of p starting at p2, then in increments of p: p2 + p, p2 + 2p, ... Now what should be the terminating loop condition? It is easy to say that the terminating loop condition is p < n, which is certainly correct but not efficient. Do you still remember Hint #3? Yes, the terminating loop condition can be p < √n, as all non-primes ≥ √n must have already been marked off. When the loop terminates, all the numbers in the table that are non-marked are prime.
The Sieve of Eratosthenes uses an extra O(n) memory and its runtime complexity is O(n log log n). For the more mathematically inclined readers, you can read more about its algorithm complexity on Wikipedia.
public int countPrimes(int n) {
boolean[] isPrime = new boolean[n];
for (int i = 2; i < n; i++) {
isPrime[i] = true;
}
// Loop's ending condition is i * i < n instead of i < sqrt(n)
// to avoid repeatedly calling an expensive function sqrt().
for (int i = 2; i * i < n; i++) {
if (!isPrime[i]) continue;
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) count++;
}
return count;
} | Array,Math,Enumeration,Number Theory | Medium | 263,264,279 |
331 | hey everybody this is larry this is day 26 of the august lego daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's farm my internet's been kind of bad so this video may be a little bit weird because i am recording it live so if it does get bad just fast forward or watch it on the fastest speed anyway okay so what if i pre-order so what if i pre-order so what if i pre-order is to pre-order traversal you is to pre-order traversal you is to pre-order traversal you uh you record the notes value otherwise we call it a sentinel okay for example return true if it is a correct pre-ordered stress of a binary tree pre-ordered stress of a binary tree pre-ordered stress of a binary tree is guaranteed that okay so you're given this pre-order e thing oh you're not allowed to reconstruct the tree that's a little bit awkward um well why what would be a force situation okay so basically you just have to consume everything okay um yeah i mean i think this is pretty okay you just have to do the recursion and do it that way and the thing with pre-order is that pre-order is that pre-order is that it just means that for every node there's two corresponding um children but it's a little bit awkward the way that i have to figure out how to because the way that i usually do this or thinking about it is to use side effects but maybe there's a better way to handle this um yeah but basically you can just have like an index is equal to zero and is equal to the length of the pre-order pre-order pre-order and then now we just have a pre-order and then now we just have a pre-order and then now we just have a pre-order uh okay let's just convert this to the tree maybe so then because i like my function name being pre-order makes more sense but being pre-order makes more sense but being pre-order makes more sense but yeah but given a node so okay wait what no just giving what do i want to return here well what is an input maybe that's a little bit awkward but okay but oh yeah um no this is wrong obviously actually so let's just call it this tree naming things are solid for me but we'll just ignore the fact that's the case and uh and do this for now um yeah i think that's okay so basically the value don't doesn't even matter because it doesn't have to be a binary search tree anything just a regular binary tree so in that case i don't even have to care about the contents uh just uh we care about the content long enough to know that it is a dollar sign of hashtag or whatever or not so okay so if index is bigger than and then this is no good right return so now we have some good is either true maybe i'm not sold on this quite yet this is way ad hoc and whatever but yeah but if tree of index is equal to uh then we just kind of return because then that means that this number is good um maybe on um i'm trying to think whether it makes sense to increment the index here or afterwards because i guess here doesn't really make sense either so i guess we'll just do it here so then we go to the next character else it's just a number then we go pre-order it's just a number then we go pre-order it's just a number then we go pre-order pre-order kind of and then return pre-order kind of and then return pre-order kind of and then return um something like that but we have to figure out how to do the index so then we consume the index so we index first as the pre-order and then we do the net as the pre-order and then we do the net as the pre-order and then we do the net the left and then the right yeah i think this should be good maybe so now we do a pre-order and then we so now we do a pre-order and then we so now we do a pre-order and then we return good um we have to do some non-local index here as well i think non-local index here as well i think non-local index here as well i think this should be good but i am not as confident as i am usually so let's give it some testing give it some love oh i am wrong on this by the way this case for example i think i'm wrong and again now i seem to be running into some internet tech difficulties it's been bad internet all day um okay so i know that i usually say i don't cut away but there's actually not well i guess actually i could improve the code because i know that this is wrong but i might uh cut out for a second because this is really stupid uh what year do i live in living in new york city okay uh oh yeah so i think we just have to return good and index is equal to and because if index is not equal to n that means yeah if index is not equal to n then that means that we're either short which is in this case um or i guess if it's going over it good is already false so yes i think this should be uh definitely more accurate a little bit more confident again i am having difficult uh internet connections i logged in i had um it was good for about five minutes of the last like two three hours so just long enough for me to start this video but not long enough for me to submit okay so i'm i mean you could stay i'm gonna this is one of the rare times i will edit away because you can see that literally my internet is having technical difficulties so yeah hey welcome back and i'm back i guess if i didn't do much but okay so now i'm able to run the code so it looks okay here um i probably am okay let's actually write a few more test cases like an empty one uh do and maybe do one two three no whatever okay and let's give it another spin oh i hope this internet stays up long enough for me to submit so this looks good i'm confident or i don't know if i'm confident my internet is having issues so let me just give this except okay so it is an except yay um yeah so we look at each character slash node if you want to call it that at most one so this is going to be linear time in terms of space this is going to be uh of h space where h is the height of the proposed tree because that's just the cost of the stack even if with no parameters there you do create some or you do use some stack space so yeah so linear time of h space um yeah i don't like the side effect to be honest of but i think that's how i generally do it maybe i have to do some learning about um learning about how to write this in a cleaner way so yeah so even you know just because you get it accepted doesn't mean you can't improve the code and in fact for me sometimes that i even do i aim to do that afterwards because it helps me to you know already have a base of what is you know what like i know what works so then i can work to iterate on that um sometimes especially now that i know what i want to express but yeah um that's what i have for this one let me know what you think apologies for the internet and weird cuts i'll talk to you later stay good stay healthy to good mental health i'll see you later bye | Verify Preorder Serialization of a Binary Tree | verify-preorder-serialization-of-a-binary-tree | One way to serialize a binary tree is to use **preorder traversal**. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as `'#'`.
For example, the above binary tree can be serialized to the string `"9,3,4,#,#,1,#,#,2,#,6,#,# "`, where `'#'` represents a null node.
Given a string of comma-separated values `preorder`, return `true` if it is a correct preorder traversal serialization of a binary tree.
It is **guaranteed** that each comma-separated value in the string must be either an integer or a character `'#'` representing null pointer.
You may assume that the input format is always valid.
* For example, it could never contain two consecutive commas, such as `"1,,3 "`.
**Note:** You are not allowed to reconstruct the tree.
**Example 1:**
**Input:** preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
**Output:** true
**Example 2:**
**Input:** preorder = "1,#"
**Output:** false
**Example 3:**
**Input:** preorder = "9,#,#,1"
**Output:** false
**Constraints:**
* `1 <= preorder.length <= 104`
* `preorder` consist of integers in the range `[0, 100]` and `'#'` separated by commas `','`. | null | String,Stack,Tree,Binary Tree | Medium | null |
154 | hi hello today we will talk another binary search question find minimum in rotated sorted array 2. let's see what this question is all about all right so this question provide us a rotated sorted array and we had to find a min element from it with an extra condition that it hasn't it can have duplicates i have write few examples here in this case you can see it is rotated and six is repeated in this case one is repeated and here one is repeated in more it can be other elements too it's not only one or one element that can have multiple elements which can be repeated so how we will solve this question the first thing we will look at it is look at these two points the first that it is a sorted array and we have to find main element considering these two conditions for sure we will try to look at bunny search but in this bunny search again we will use advanced by search because we will make some change and then we can solve this question easily considering these three examples here we can see what happened we will take the left pointer here we will take right here and in the middle now when we will see that we will then we will try to find as i discussed in the previous example uh the part one where we are mostly interested in this area which is the rotation point where actually it start rotating because there we can find this mean element in all examples here so in the first example if we will look at so what it's saying when we find mid we will ask this question this is mid is greater than this end if it is then me then this dropping point and this rotation point is in between some place of mid and end then we will do the binary search accordingly and in the second example if you will see we will take the left pointer we take the right pointer and then we take the mid in this case uh when we ask this question that is this mid is greater than and so it is not then we will ask that does mid is less than end just to confirm where we are right now is sorted if it is sorted in that case we will either look here so when we are looking when we are saying mid is less than end then we are saying start looking here in the last example which is little trickier we will be left here we'll take right pointer here the midpointer will be at some place here now we will ask the question that does mid is greater than end mid is greater than and no is made less than end yes we will move here in that case it this will become four five one two three again we'll take left pointer right pointer will come here because we start looking into this side of that side because mid was less so we start looking into this area and mid will go somewhere here now that now in that case this mid is becoming greater than and then we start looking here because this condition starts satisfying so we say mid is greater than and then yes it is then we start looking in this area so in this area for sure then our example will become like 4 five one two three and we will move the pointer we'll save it goes here and will remain on its place mid will come here now in this condition you can see mid and end this become equal and once they are equal so what we will do we will say okay the end point you should come one step back so we will keep start here and we will ask and you should come one step back so we will do e minus one and so that we can come out of this duplication area step by step one by one because when we are in some uh duplication area it's not telling us some direction that either we have to look here or we have to look here in which direction so we go one step to come out of this situation so in this case when we will use a binary search we can find our we can find the main let's see in the code how we can solve this welcome back so as we already know that we have to use binary search to solve this question i will do we'll call binary search function we will say here we are that's the first index will be on zero the last index will be on at the end and we can write this method here f b s left pointer is here right will be an end and we are expecting it will return as min so what will how we can solve this first we will simply ask we will say if left is greater than equal to right if it is we are in the base condition and we can return nums at left otherwise if it is not we can do actual the binary search here so we will save wall mid will be left plus right minus left divided by two when you find the mid we will say if nums at now we are asking the question that is the right side is sorted or no so we will say if nums at mid is greater than nums at and sorry right so in that case we were asked we are saying the number at the middle is greater than the number on the right so the rotation point is in between mid and right so we will start looking into mid and right so we'll say mid because mid is already greater than nums right so for sure that won't be uh our minimum number so we will go min plus mid plus one and we will go with the right else if it is not the case so we will say else if nums at mid is less than so if it is not greater than so we will ask is it less than right so if you'll say yes it is less than right so here in some sorted array where mid is less than the right then for sure we will try to look into the other side which is uh binary search from the start to you know i'll say restart it's left to mid now in the else part when we never find so for sure that nums at mid is equal to numbers that right if all these two conditions don't satisfy so in that case we were in some area where mid and right or duplicates so we can go with the binaural and here we can say left and we will go right minus one now that's it we keep on doing that and with this by search we'll find our minimum number let's run the code and it works thanks | Find Minimum in Rotated Sorted Array II | find-minimum-in-rotated-sorted-array-ii | Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,4,4,5,6,7]` might become:
* `[4,5,6,7,0,1,4]` if it was rotated `4` times.
* `[0,1,4,4,5,6,7]` if it was rotated `7` times.
Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`.
Given the sorted rotated array `nums` that may contain **duplicates**, return _the minimum element of this array_.
You must decrease the overall operation steps as much as possible.
**Example 1:**
**Input:** nums = \[1,3,5\]
**Output:** 1
**Example 2:**
**Input:** nums = \[2,2,2,0,1\]
**Output:** 0
**Constraints:**
* `n == nums.length`
* `1 <= n <= 5000`
* `-5000 <= nums[i] <= 5000`
* `nums` is sorted and rotated between `1` and `n` times.
**Follow up:** This problem is similar to [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/), but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why? | null | Array,Binary Search | Hard | 153 |
495 | Jhaal Hello Hi Guys Welcome To Questions Today's Question Attacking In Speed This Question Attacking In Speed This Question Attacking In Speed This Question That Bihar Invoice Jaaye Zero Point Teams Undertaking Can Make This MSG Been Present Condition Not Given Date Attacking In This Question Teams On Standing Time Series Two Words Essay And Deposit Time Tuition That you need to put a total time till acidity point condition zoom that teams takes it very beginning of this specific time point and make such bean present condition immediately let's understand this are timely active voice and devotion of deposit nine teams giving back To cash withdrawal lineage giving trucks and again to represent the time duration in which will win in which will be in this printing off subscribe pimples that now young man youth floor and devotion 9 times from amazon time at which will give a good practice representative one And for it means the taste one should stop vande giving the acid staff or the giving acid keep and duration represents effect illegal drug women sc dot in the giving its difficult one unit improve effective deslast 30 deslast 365 days hello hi madam are to make things Made Things Better But This Happening At Unit Now I 'm Telling That I'm Explaining 'm Telling That I'm Explaining 'm Telling That I'm Explaining Using Debit Hindi Solution Can Not Go Into From Any Are Available In Your Letter How Does The Self Work Swayam Using React Reaction Fenugreek Clear Tube Narao Which Represents A Timed Sure Detergent Unit Sunao Tips For Death Was Given To Add First Unit Distance From 0215 Was Not Arg 2009 Truck 20000 Representatives Not Present In Every Person Does Not Present At The And Sunao Hindi Are Vacancy 80 For Students Were Giving Effect To Share So And When Will Ra Mental two units dentist third unit som words will see is deep active one second only one and only som one that at one wear giving back to such supreme one two 20 for a point nine from 2323 why this factor of women from pintu unit certificate unit and This Deep Treatment Depend Trimming Will Be Till Unit Soft 123 Sports And Now 13816 Handsfree Unit Vacancy Date From Which Government Hospitals And Saw Three Unit Not Giving Any Other Drugs If Such Person Minute Fourth Unit Certificate Such Will Not Present At That Now Something To Forensibly Not present hai dekho chief represented 10940 giving acid talk and laugh tuition 209 front four to five faces of devotion in the equipment poles and now not afraid at all song devotion and you should not do any one unit operation authority at so such a possible deposit a 900 Vacancies after becoming a great fortune it is deposited present poisoning effect continues till security question and 2000s that total time in which she was present for physical to front of all given in this regards for this that no one has Madan Singh died when not wanted to family Hey Hindi Solution By Time For Making Things More Clear I Am Using Key Address Format Will Tell You This Solution Later And Please Avoid To Understand No In This Question Answers Come To 4 For The Time Roshan's Method To Increase Such Daily Point Knowledge Loaded Input To but what is this fennel represents one and to it means festivals and tagged one second first unit android urination and excretion of drug inspector August 2018 201 unit 099908 is not considered this government one unit show from and emotions to show the factors now last from one Two Three One Two Three Do It But Were Considered Only And Raw One Second Supreme One Two 50% Now Two 50% Now Under the top two drops 1518 for students and mid doing only from devotion duration of two three under the influence of tourists in this world but not be considered effective work with that show come to three only 10 days poles and spirit will not option 250 from 212 Come to toe three things under the influence of two years but will consider only day prince of conduct software beans 1234 answer one so 98 third second david vinod deficit which gives what is over thirty effects which give a little over 2600 subscribe 2012 1000 minutes second Unit And Effective Treatment For Sweet Dish Times Beneficial Than Three To Four Seats Under The Influence Of A Cylinder Day Prince Of Wales Is Conduct Show Any Special Soft Hanging Is Drug Ko Hai Sonth Ek Cheez Ban Now That Modi Factor Under Which Was Given A To Will And Asked For That Bigg Boss Season Audition Is To Only For 10 To Be Are Answer Bhi Kam 2008 With The Message That Total Time At Which Schedule Call Day That Is Equal To Three Seconds Sudhir Choudhary And Tire Examples Of This Code On Let's Look At What Were Formed During 20 Times Bsc In The Night Increase Drug Ki Beni Drugs Event IS Index New Delhi Rajdhani Rectangle Index - Drugs - New Delhi Rajdhani Rectangle Index - Drugs - New Delhi Rajdhani Rectangle Index - Drugs - Time Admission Graph - One Who Has Given When Any Time Admission Graph - One Who Has Given When Any Time Admission Graph - One Who Has Given When Any Differences With Celebration At This For - 12323 Liberation And What Will Happen For - 12323 Liberation And What Will Happen For - 12323 Liberation And What Will Happen With Lord Vishnu But I - Banat Second With Lord Vishnu But I - Banat Second With Lord Vishnu But I - Banat Second Day Which Given Youth Second Will Have Its Effect On Forest Date Means Minister Was Given That When It Was Given At One Second Saini Binti Effective Dashrath Blast Same Flat Settle Two New Delhi Only Taken from one to three labs under the influence of only destructive one does she will repeat my flight mode settings from c timestamp of ias - 575 minus one is better than edition ias - 575 minus one is better than edition ias - 575 minus one is better than edition dated 4th - 3 and united nation dated 4th - 3 and united nation dated 4th - 3 and united nation in the scripters which was given and unique id - Once in next bill it is its effects to the - Once in next bill it is its effects to the - Once in next bill it is its effects to the fullest that Reddy Bandhu at one second will it will be only in saffron speed will only in flats such bindi third second third unit in the third desert festival only under the influence of this trek and others Drugs given in this time period according to countryman's Swarna IA Times - Yuvan Ras Timestamp is greater than or - Yuvan Ras Timestamp is greater than or - Yuvan Ras Timestamp is greater than or equal duration Know what is chief Timestamp - CIMS Word Timestamp - CIMS Word Timestamp - CIMS Word Timestamp is not to be reduced to 100 Jai Hind is Presidency Overlapping is Happening Show overlapping is happening sudhir then a particular interval acid under the influence of two all models in this case in 2223 edison electronic under the influence of two and mode rakh will consider only one day difference of two different white times - york times timestamp lets times - york times timestamp lets times - york times timestamp lets 110cc condition Hair Oil - Hair Oil Minus 110cc condition Hair Oil - Hair Oil Minus 110cc condition Hair Oil - Hair Oil Minus One is great benefit devotion of drug day well a day in the RMM drugs and you will have its effect on the police and will depend on a legitimate agent I donation will give and celebration of decide twitter account that and when This Is Not The Kid 0505 - One Is that and when This Is Not The Kid 0505 - One Is that and when This Is Not The Kid 0505 - One Is Not Greater Than Two Years Back In This Case Some Will Happen How To Weiler Friend Show Installed App I - Hair Oil - 110 012 Seconds X2 Settings - Hair Oil - 110 012 Seconds X2 Settings - Hair Oil - 110 012 Seconds X2 Settings Off Key New Dress But From One To Second COD Effective Only wonder ladies duct is so English's will our will and share - so English's will our will and share - so English's will our will and share - share - one so this point and then approach this question share - one so this point and then approach this question share - one so this point and then approach this question 9 Lucrative Codification Sunao Avoid Andar Code Already Know Electronic Code Line By Line For Cheap Ask This Banner Times Are This Style Se 0.5 West or the time for which she will remain Style Se 0.5 West or the time for which she will remain Style Se 0.5 West or the time for which she will remain in the point to the time series will start alarm equal to one Szechuan equal to one day disposal years back to sea warehouse youth is all value and note Sudhir will come from abroad in icon 212 234 time series i - times of - 1st 234 time series i - times of - 1st 234 time series i - times of - 1st edition addition in this is what will happen or account classification means a date and time only i is - time saif a date and time only i is - time saif a date and time only i is - time saif first world immigration it means the 20.18 first world immigration it means the 20.18 first world immigration it means the 20.18 dish valued at this time saif - 1the dish valued at this time saif - 1the dish valued at this time saif - 1the effect of effect pause until maximized A dentist in this kc banner drug 181 and against 40 minutes for the first don't have already completed in time duration sudhir for in this case will adaptive account plus equal to a nation will add 2.2 reaction to account mails valentines i - 2.2 reaction to account mails valentines i - 2.2 reaction to account mails valentines i - - verb - One is not regret at the - verb - One is not regret at the - verb - One is not regret at the invitation like this how to minus one so divine will be lit will be hair oil - Yuvan Big Boss hair oil - Yuvan Big Boss hair oil - Yuvan Big Boss Which set up due point which gives wealth will remain in only till debt point one second charges not given Date Is Only For One To Three Second Minute It's Women Only Words Related To Women In Fact One And After That She Controls Given So Second Rottweiler Bar First Time Sudhir Will Add Value Of Controversy Over Time Series After - Times After - One To India And Follow Up What Will Happen - Times After - One To India And Follow Up What Will Happen - Times After - One To India And Follow Up What Will Happen Account Bestows Liberation Of The Ko Bhi Roshan Admit Char Aisi Is Important Mode But See That This Vansh Lecture Detail Loot Value In Account Divya Account Will Be Only For -1.2 Only Account Divya Account Will Be Only For -1.2 Only Account Divya Account Will Be Only For -1.2 Only E Hai But Gilas Dravid Timestamp Admission Last Date Was Given His Neighbor Come Into Power Shoaib Will Develop Depression Again For The Last Timestamp Account Blood Circulation Exam Bigg Boss 100 Deal-Points 210 In 2001 Bigg Boss 100 Deal-Points 210 In 2001 Bigg Boss 100 Deal-Points 210 In 2001 Last Date Which Was Guilty Last Time Stamp Which Gave There Last Time Stand Will Have Its Effect On The Fullest Sudhir and gyan up and celebration in account siddhi indian vitamin e count and walnut time decode a e weighted setting accepted commission ne district is the video thank you a | Teemo Attacking | teemo-attacking | Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly `duration` seconds. More formally, an attack at second `t` will mean Ashe is poisoned during the **inclusive** time interval `[t, t + duration - 1]`. If Teemo attacks again **before** the poison effect ends, the timer for it is **reset**, and the poison effect will end `duration` seconds after the new attack.
You are given a **non-decreasing** integer array `timeSeries`, where `timeSeries[i]` denotes that Teemo attacks Ashe at second `timeSeries[i]`, and an integer `duration`.
Return _the **total** number of seconds that Ashe is poisoned_.
**Example 1:**
**Input:** timeSeries = \[1,4\], duration = 2
**Output:** 4
**Explanation:** Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.
**Example 2:**
**Input:** timeSeries = \[1,2\], duration = 2
**Output:** 3
**Explanation:** Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 2 however, Teemo attacks again and resets the poison timer. Ashe is poisoned for seconds 2 and 3.
Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in total.
**Constraints:**
* `1 <= timeSeries.length <= 104`
* `0 <= timeSeries[i], duration <= 107`
* `timeSeries` is sorted in **non-decreasing** order. | null | Array,Simulation | Easy | 56,605,649 |
1,523 | uh hey everybody this is larry this is q1 of the recent only contest you'll see me try to do it live and i gotta mess it up a little bit but that but for this problem you're trying to figure out the count of odd numbers between low and high inclusive uh and the user's way to do that is just by um case enumeration i think but so low and high could only be odds and events uh just you know do the math and make sure you get it right uh i think that's kind of the idea behind it basically if high is a odd number um then that there's high or plus one over two numbers that are smaller than an odd number and then you just want to subtract from uh the same thing from the lower case uh yeah and now you can watch me cyber live during the contest where i fumbled around a bit hmm uh-oh my website's having an issue let's see oh inclusive this is trickier than i thought you | Count Odd Numbers in an Interval Range | capital-gainloss | Given two non-negative integers `low` and `high`. Return the _count of odd numbers between_ `low` _and_ `high` _(inclusive)_.
**Example 1:**
**Input:** low = 3, high = 7
**Output:** 3
**Explanation:** The odd numbers between 3 and 7 are \[3,5,7\].
**Example 2:**
**Input:** low = 8, high = 10
**Output:** 1
**Explanation:** The odd numbers between 8 and 10 are \[9\].
**Constraints:**
* `0 <= low <= high <= 10^9` | null | Database | Medium | null |
1,013 | hey guys I'm in this video we show see another problem partition array into three parts with equal sum so given array of integers return to if you can partition AR into three non empty Parts with equal sums so question say says the given an array of integers and we should check that if we are able to partition the array with into three partitions such that the sums are equal in each partition so each partition mean some of the numbers integers in the each partition should be equal to some of the numbers in other partitions as well that is what we need to check here and one more thing is they not told like exactly three it can there can be more than three partition with equal um number but minimum three is must so let's see this example okay if we take the first example 0 + 2 + 1 that will give you sum example 0 + 2 + 1 that will give you sum example 0 + 2 + 1 that will give you sum up to 3 - 6 + + + 6 will be 0 - 7 + 9 + up to 3 - 6 + + + 6 will be 0 - 7 + 9 + up to 3 - 6 + + + 6 will be 0 - 7 + 9 + 1 again it will be 8 - 7 uh 9 10 - 7 3 1 again it will be 8 - 7 uh 9 10 - 7 3 1 again it will be 8 - 7 uh 9 10 - 7 3 yeah 2 + 0 + 1 last three elements three yeah 2 + 0 + 1 last three elements three yeah 2 + 0 + 1 last three elements three so uh here we are performing the partition of the array we are not taking subsequence from the array right you're not taking two one then Zero from here no you are partitioning the array into three parts here so either this partion can be this also 0 2 1 - 6 and - 7 9 1 can be this also 0 2 1 - 6 and - 7 9 1 can be this also 0 2 1 - 6 and - 7 9 1 21 or 0 2 1 - 66 - 7 91201 so you're 21 or 0 2 1 - 66 - 7 91201 so you're 21 or 0 2 1 - 66 - 7 91201 so you're partitioning the array into three parts and we not performing the subsequence in the sense we are picking out some elements in the r order no we not finding that so we are just partitioning the AR into equal parts minimum three equal parts such that the sum of the numbers in each partition should be equal so how do we solve the problem so one thing is they have told we have to partition the array into three equal parts and some of the numbers in equal each part should be equal that means if we find the sum of the entire array if you find the sum of the entire AR then that sum divided by three if it is divisible by three only then we can partition the array into three parts that is for sure right so what we'll do is at first if they given an array let's say with the given array first what we'll find is we'll find the total sum so in this case total sum will be 0 + 2 + 1 3 - 6 + 6 will be 0 - will be 0 + 2 + 1 3 - 6 + 6 will be 0 - will be 0 + 2 + 1 3 - 6 + 6 will be 0 - 7 3 - 1 - 7 3 - 1 - 7 3 - 1 - 4 + 9 so 9 - 4 it will be so 5 + 1 6 7 8 4 + 9 so 9 - 4 it will be so 5 + 1 6 7 8 4 + 9 so 9 - 4 it will be so 5 + 1 6 7 8 9 so total sum what we get here is 9 so is this 9 is divisible by 3 9 by 3 is it equal to Z is the remainder is z if the remainder is z yes that means if it is divisible by then only we can confirm that we can do the partition in the array to three equal parts otherwise we cannot perform so if you take the next example uh let's say this example okay here same thing 0 - - 7 - - 7 - - 7 9 1 2 0 1 so if we do the addition of the elements in this case so 3 6 + will the elements in this case so 3 6 + will the elements in this case so 3 6 + will get cancel 3 7 + 3 10 19 - 1 18 19 get cancel 3 7 + 3 10 19 - 1 18 19 get cancel 3 7 + 3 10 19 - 1 18 19 20 so we get the sum of 21 so 21 by 3 means it's divisible by 3 but the question says is we have to addition the into three parts initially I had told minimum three or more than that also but more than three when it happens I'll tell that case at the end now we assume that we have to partition AR to three that more than three comes in what if the element the array is 0 comma 0 Comm 0 so in this case you can partition these two this right so if the total sum becomes zero and count can be greater than equal to three yes in that case we can say this is partition but in the second example if we see it is divisible by 3 7 21 by 3 we get seven partitions are possible with three elements in that but can you divide it into three partiti no that is not possible that is why we written false here so I said in the beginning like there can be more than three partitions also that will be this case explicit case where total sum is zero so if we have -1 -1 in this case total if we have -1 -1 in this case total if we have -1 -1 in this case total sum is zero but if you see the number of partitions only two we form so in this case you return false which is not greater than equal to three so but here if you see total sum is zero and count can be greater than equal to three also because this one partition possible or these two this three partition possible so in this case count will be greater than 3 uh here you find 0 tot time equal to 0 here again you find 0 matching so four partitions you get which is greater than three so in this case you return two but if you have non zero total sum then in such case only three par should be able to do it not more than that so in this case you return false similarly uh last example also so first you find a toal sum that is 9 div by 3 yes it is there are if 9 is divisible by 3 yes we can do it and if 21 is also divisible by three there are chance we can get the partition of three but that depends on the elements in the if there are consecutive zeros like let's say we have 2 1 okay then 0 again 2 one here 0 2 one so in such case we will get the answer so depends if it is div yes there is a chance of getting the partition uh it need not be like 21 by 3 will be question we get the 7 seven partition no there are chances we get the partition of uh three partitions of equal sum so it depends on the elements in the so for that we have to check once you get that your is divisible first we need to check so in this case total sum is 9 so next Target sum will be nothing but 9 by 3 that is 3 this is the target which we are looking because we are dividing into three partitions so if we have 21 by 3 = 7 so we are 3 = 7 so we are 3 = 7 so we are looking three partitions with 7 as the sum in the second example so if you get 7 as a su by partitioning the array into three parts then yeah there can be chance in the first example 3 which you are looking so total sum by three whatever is that will be the target sum so let's keep a variable called current sum initialized to Z we start iterating so what is the current sum now current sum is 0 + 0 will be 0 again 0 + 2 sum is 0 + 0 will be 0 again 0 + 2 sum is 0 + 0 will be 0 again 0 + 2 will be two updated to two then 0 + uh will be two updated to two then 0 + uh will be two updated to two then 0 + uh okay 1 + 2 will be 3 so now you can see okay 1 + 2 will be 3 so now you can see okay 1 + 2 will be 3 so now you can see current sum is equal to Target sum hence one partition we have obtained here okay since we're partitioning the aray we need not to check for the random elements in the it will be the continuous element continuous elements so once you found one partition current sumal let's have a variable called count increment the count value by one and current Su will initialized to zero so next element start again - 6 so current next element start again - 6 so current next element start again - 6 so current Su will be - 6 because 0 + - 6 will be - Su will be - 6 because 0 + - 6 will be - Su will be - 6 because 0 + - 6 will be - 6 again - 6 + 6 will be 0 again now it's 6 again - 6 + 6 will be 0 again now it's 6 again - 6 + 6 will be 0 again now it's not equal to 3 then you get - 7 so this not equal to 3 then you get - 7 so this not equal to 3 then you get - 7 so this willed to - 7 then you get 9 so - 7 + 9 willed to - 7 then you get 9 so - 7 + 9 willed to - 7 then you get 9 so - 7 + 9 will be 2 which is not equal to Target sum again you move hard so + 1 will be 3 sum again you move hard so + 1 will be 3 sum again you move hard so + 1 will be 3 now current sum equal to Target sum yes another one partition you can do so count will be to and current re initialized to zero again you find here to up current sum to two it's not equal to Target sum zero it to remain as such one upate current sum by three so 3 equal to 3 yes one more partition we have so Total 1 2 three partitions count being three current will Beal to Z yes we are at the end of the hence we have found that we have found three partitions of equal sum which what is the sum here three here but if you uh take the next example same thing next example let's try out with this also so if you take this example now so in this case some was 21 so 21 by 3 will be 7 Target sum was 7 here so let's say current Su initialized to zero and count also initialize to Z you should get count equal to three here so you start here Z will be Z only two you found increment to two again you found one so 3 in 3 + 1 then - 6 means 3 found one so 3 in 3 + 1 then - 6 means 3 found one so 3 in 3 + 1 then - 6 means 3 - 6 will be - 3 - 6 will be - 3 - 6 will be - 3 + 6 you do so - 3 + 6 will be 3 again 3 + 6 you do so - 3 + 6 will be 3 again 3 + 6 you do so - 3 + 6 will be 3 again which is not equal to Target some yet plus 7 you get so this will be get incremented to 7 uh 7 + 3 10 this is more than Target 7 uh 7 + 3 10 this is more than Target 7 uh 7 + 3 10 this is more than Target some form then you found 9 here that will be 19 - one will be 19 - one will be 19 - one will be 18 then - + 2 will be 21 uh sorry minus 18 then - + 2 will be 21 uh sorry minus 18 then - + 2 will be 21 uh sorry minus okay 18 right 18 + 2 20 then you last 21 okay 18 right 18 + 2 20 then you last 21 okay 18 right 18 + 2 20 then you last 21 so nowhere you're getting it equal to Target some here you can find one partition but there only one partion the remaining elements whichever there previous prev will not be equal to seven right so that is why if you find a partition you start from beginning one partition another partition so in the continuous manual you will be getting because you're dividing the into partitions you're not picking up some elements and finding the sum here you're not picking this two this one and this zero no you're not doing that elements which that means you're partitioning the array into three parts here it is not SP because nowh you're getting current Target count is zero here it's not equal to three so return false so this is the logic so let's define the variable first okay total sum initialize it to zero so for each number in the array so total sum that's equals to number okay if first you have to check whether total sum modulus 3 is equal to Z only then you can do the partition if it is not equal to Z means you cannot partition the ARR into three partition that the sums are equal no so in this case you directly return false you not to check only if it is if the mod is equal to Z that are case there is a possibility that you can partition the array to three partitions of equal size equal some so if that is the case so again in the array before to that we have to initialize variable current sum and let's have a variable count so first what we need to do is current sum plus equals to num so if in case current sum and we have to find write the target sum also that will be nothing but total sum by three it will be see only if the remainder is zero then only you divide it by three otherwise you won't so if current sum equal to Target sum that means count should be incremented and whatever current sum you have the initialized to zero so at the end you have to return if count is equal to 3 or uh there is a possibility total sum equal Z count can be greater than equal to 3 in that case so say count equal toal 3 or total sumal toal to0 and count greater than equal to 3 because when you have the elements with 0 right target total sum will be zero so total sum means Target sum will also be 0 by 3 will be 0 again when you find the current sum here you find Z which is equal Target sum count will be one for this again equal to Target count will be two again equal to Target count will be four if count greater than equal to 3 so this let it be inside one more bracket yeah so we can run this and check total yeah yes so same logic applies to Java also directly can give greater it will not create a problem yeah so we should submit this also yes successfully submitted if you understood the concept please do like the subscribe to the channel we'll come up with another video in the next session until then keep learning thank you | Partition Array Into Three Parts With Equal Sum | fibonacci-number | Given an array of integers `arr`, return `true` if we can partition the array into three **non-empty** parts with equal sums.
Formally, we can partition the array if we can find indexes `i + 1 < j` with `(arr[0] + arr[1] + ... + arr[i] == arr[i + 1] + arr[i + 2] + ... + arr[j - 1] == arr[j] + arr[j + 1] + ... + arr[arr.length - 1])`
**Example 1:**
**Input:** arr = \[0,2,1,-6,6,-7,9,1,2,0,1\]
**Output:** true
**Explanation:** 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
**Example 2:**
**Input:** arr = \[0,2,1,-6,6,7,9,-1,2,0,1\]
**Output:** false
**Example 3:**
**Input:** arr = \[3,3,6,5,-2,2,5,1,-9,4\]
**Output:** true
**Explanation:** 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
**Constraints:**
* `3 <= arr.length <= 5 * 104`
* `-104 <= arr[i] <= 104` | null | Math,Dynamic Programming,Recursion,Memoization | Easy | 70,872,905,1236 |
1,438 | all right long as continuous are both absolute difference let's make a limit so let's say i have this array of numbers here and i have a limit of 50. and let's just look at this sub array here so this is actually the longest sub array where the difference between any two of the elements so if i like look at any two elements that the difference between those will be less than or equal to the limit and the way you can check very quickly is you just look at what's the maximum element so the maximum element here is 55 let's write that down and the minimum element is 20. why is my facing off all the time okay minimum 20 okay and if we just look at the difference between 55 and 20 or if we look at the difference between the maximum the minimum as long as that difference is also equal to the limit well then all the other numbers uh will have a difference that is the center equal to the limit as well so uh let's pretend that i was able to like find the sub array by looping from let's get rid of this let me just actually i'll leave that there so let's say i was i started at the beginning right and i was just like traversing like increasing my window size and i got to this point right and i was like okay cool we're good so far but then where things get interesting is when i try to add the zero in so let's say i try to add the zero in what i'm going to do first is i'm going to update my minimum to zero and i'm gonna say okay is this zero uh is the difference between this zero my minimum is it less than equal to my limit and it is because your zero minus zero is zero and zero is less than fifty okay but now is this zero minus my maximum is it less than or equal to my limit of fifty and no because the difference between zero and fifty-five is 55 between zero and fifty-five is 55 between zero and fifty-five is 55 so 55 is greater than the limit so we need to exclude this 55 we don't want it and everything to the left of it we don't want it so we need to do is move our window size one past it and you think we're good so far we you'd think this would be fine right but we're not because if you notice there's another number in here that's 52 if we take the diff so if we our new maximum would actually be 52 and 52 uh minus zero is 52 and that is greater than our limit of 50. so we would actually want to move one past this 52 as well and this would be our new window size uh if we include the zero here and so notice what i had to do there for a second let's actually go like wind that back a little bit so i had to find so i had to compare zero to my maximum and then if it broke my limit i had to go one past the maximum i didn't move my one to one past it and then i have to compare it i have to compare the zero to the next maximum element which would be this 52 and when i say next maximum it's whatever the maximum element is past this 55. so this 55 was my current maximum now it needs to be whatever my next maximum is whatever is to the right of the 55 and that would up to this point so this would be the 52 here so uh and then i would because that breaks our property 52 minus zero would break our limit then we need to move one past it as well okay and i'm going to explain how to find the next maximums and all that in a second but let me just keep going so now we're going to try to include the 10. and actually let me real quick let me update our maximum to 40. okay so uh we're going to try to include this 10 here and we can because our minimum right now is zero if we just we take we look at this 10 and we compare to our minimum well the difference between 10 and 0 is 10 that's less than our limit and the difference between 10 and 40 is 30 so that 30 is less than our limit too or less or equal to the limit so we're good there but uh now when we try to include 57 so we're going to update our maximum and we're going to say okay it's 57 is the difference between 57 and 0 is that less than or equal to our limit and it's not because 57 minus 0 is 57 is greater than 50. so uh we need to move one past the minimum now so we're going to update our bracket and move one past this minimum and then we would compare 57 so our new middle would be 10 now we compare 57 to 10 and that's 47 so we're good there because 47 is also equal to 50. all right so what we need to do is we need to have an efficient way of finding our maximum and minimum values and then we need to be able to find our next maximum and our next minimum values so that we can keep updating our the left side of our window so how are we going to do this so what we're going to do is we're going to use a monotonic stack so and you could use i'm sure you could use a monotonic here too um i'm not as like well-versed with monotonic cues but i'm well-versed with monotonic cues but i'm well-versed with monotonic cues but i'm pretty sure they just achieved the same thing so but if you want to go that route you can't but i just used excellent that's what i'm comfortable with so uh let's go over let's use a decreasing stack to find our next maximum elements so let's write that down so a decreasing stack will it finds the next max element and then an increasing stack will find then the next minimum element okay so uh we're gonna just do a decreasing stack so and we're gonna use both in our algorithm but for now let's just go over what a decreasing stack is and all that so we're going to push this 30 into our stack let's do that here i'm going to push i'm going to try to push this 55 but i can't because if i push 55 this is increasing this needs to be decreasing so what i need to do first then i need to pop 30 and then push 55 and then i can push the 20 and notice this is decreasing right well what's the relationship uh between this 20 and this 55 well if you notice whatever's on the bottom of our stack is actually our maximum element up to this point so like if we look at so right now we just did we tried to we pushed 30 55 and 20 to our stack and the maximum element with it up to this point is 55 and notice that it's at the bottom of our stack so one property you should notice is that the just keep that in mind is that the bottom of the stack is our maximum element in a decreasing stack and then the element on top of me is actually the next maximum element to the right of me so like whatever element is on top of me so 20 is on top of 55 that is the next maximum element to the right of me in the array so or sorry so it'd be just this would just be this so far okay and now when we add the 52 uh we actually have to pop the 20 because this is that wouldn't be decreasing anymore and then we could just push the 52 and now up to this point or we could highlight the whole thing so up to this point 55 is my maximum element in the array because 55 is still on the bottom of the stack so notice 55 is still the maximum element and notice the next maximum element up to this point so like let's just ignore this so the next maximum element after the 55 so between 2052 is this would be the next maximum and notice that is directly on top of the 55 here in our stack so now let's bring this back and now we're going to add we're going to try pushing 40 into our stack and because 40 was on top of the 52 that is 40 is the next maximum element to the right of 52 which is right after 52 in the actual array now we can push 0 and 0 would be the maximum element that comes after 40. like the to the right of it okay and let's go ahead and finish this up so 10 let's push the 10 in well we have to pop the zero because we want to be increasing or sorry decreasing and we're going to push to 10. and now notice that 10 is the next maximum element of 40 on its right side so that's and 10 is directly above the 40 in our stack okay and then when we do this 57 well we actually have to pop all of these because uh 57 is greater than all of these so we want to be decreasing so we're going to pop all of them push 57 and because 57 is on the bottom of our stack that means that 57 is actually the greatest element up to this point okay um so that's how you find your next maximums is you need to well let's look at that so you would need to actually take things from the bottom of the stack this would be our maximum this would be the next maximum and then this would be the next maximum amount of 52 and this would be the next maximum after 40. so uh we and we need to also be able to do this for the minimums um but it's exactly the same thing you just use an increasing stack i don't really want to go through the whole example but just trust that uh if a decreasing stack finds the next maximum and i showed you how to do it just now then if we use an increasing stack so let's just do it really quick like i'm not going to go through the whole thing but an increasing stacking i'd push the 30 i'd push the 55 and this is notice that 55 this so this is our minimum so far 30 and because 55 is on top this is our next minimum element if we were to like delete the 30 and then when we pushed the those one up to 20 next to get rid of both of these let's pop both push 20 then push the 52 and if we want to push the 40 we'd have to pop the 52 push the 40 and notice that 40 is the next minimum element after 20. so like if we were to get rid of uh everything on the left side here then 40 would be the next minimum element uh now when i say next minimum it's just like if this was if 20 is the minimum if we were to delete the 20 then the first minimum if we just look to the right side of 20 up to this point then 40 is the next would be the next minimum element assuming that we deleted everything out here okay let's code this out so i'm gonna create a couple link lists to represent the stacks and i'm using linked lists and not actual stacks because um we want to be able to remove from the bottom of the stack because remember the bottom of the stacks have our next maximum minimum elements so we'll start with the decreasing stack equals new linked list and this would hold because it's decreasing our max element is on the bottom we'll just say max element on bottom and this so this finds the next max element okay and then this is the same thing for the minimum so we want to do the increasing stack and now because it's increasing the minimum element is on the bottom and this finds the next minimum element okay and now we want to what we want okay we need to create a variable to keep track of our longest sub array that we've encountered so far this is just like a mac a global max variable and we're going to return longest at some point okay and then we're going to loop through our uh our nums array so i is also noun.length noun.length noun.length plus i and then we're going to uh we want to add the number that we're currently at so we want to add numbers i we want it let's just do the decreasing stack first so eventually we wanted to be able to say decreasing stack dot add last and the last element is going to represent the top of my stack okay so i'm going to try to push this onto my stack but before i push it i need to make sure that i'm not breaking the decreasing property in this decreasing stack so i'm going to do what i'm going to do is i'm going to say if while the stack isn't empty this actually needs to be decreasing stack so while decreasing stack is not empty and decreasing stack dot oh and actually oh sorry one last thing i don't actually want to push the values i want to uh push the indexes and i can always grab the values from the indexes right because i can always when i pop out the index i'll just index into the nums array okay and that's generally just more useful than pushing in the actual values but anyway uh so while the decreasing stack is not empty and decreasing stack dot get last so this is the top of the stack this is the index of the top of the stack we're going to say nums okay is okay so this is decreasing so five four three and let's say i want to push in uh i don't know a seven well i can't push a seven because if this needs to be decreasing so uh we're going to check is this value here so is nums of to get last so if it's less than or equal to this value then we want to so even if it was a duplicate we could just get rid of the duplicate and just put in our three in there it's a it doesn't matter but uh so if nums educational stack get last if it's less than or equal to um our nums at i yeah then so essentially this breaks our decreasing stock property then we want to say decreasing stack dot remove last so this is the this would be the pop okay and then finally after we remove all the elements that break our property then we're going to add the element into our stack okay so now what we want to do is keep is compare this nums i uh to the maximum element in our decreasing stack so and we actually have to make a while do this in a while loop because um remember we have to keep comparing it to the next maximum and the next maximum to see if like if that keeps breaking our limit when we take the difference of it so we're looking for the difference so all math.abs of nums i math.abs of nums i math.abs of nums i minus the decreasing stack dot uh get burst so remember so get first is the bottom of the stack and that holds our maximum element so if the difference between our current value and the maximum value if this is greater than the limit then we want to pop or we want to remove that element and we want to move our window size one past that so let me do decreasing stack dot remove first and we're gonna say int let's keep track of our window size or sorry our start or window start and we can actually put that we should put this outside so the start of our window is just going to we're going to start at the very beginning so windows start at zero and this needs to be window start equals decreasing stack remove first so this will be the index of that maximum element oh and i actually need to do sorry i forget so this is an index right of the maximum element so i need to do nums here okay so if the difference between our current value and the maximum value is greater than the limit then remove that maximum value and then we got to move one past our we got to move our windows the start of our window one past this is going to be uh remove first plus one okay so now i think we are almost done so uh and now we need to update uh longest so into longest equals one plus um the window start or we need to do i minus the window sorry cool so i is our current is where our current like if we let me just type out some numbers here okay let's do that um so if let's say we're on the seven here then i would currently be here and let's say my window start is i don't know right let's say it's here at the very beginning so this is index zero well if i is index two so i equals two in this case then uh two minus zero would be two but i need to add one because we actually have three elements here right in this little array so that's why i add one here um okay so uh and i'm saying that my window start would be zero in this case okay so um now so we did the maximums we didn't do the minimums but the code is literally going to be exactly the same so what i'm going to do the only thing that changes like when we do our increasing stack the only thing that's going to change is this guy right here this little condition because instead of uh less than or equal it'll be greater equal running for an increasing stack so um what i'm going to do is i'm just gonna literally copy and paste this into a helper method and uh yeah so let's actually create that really quick so private um int and we'll call this get window get windows start i think that's good and we're going to pass in our stack and we're going to pass in on the nums array we'll pass in the index that we're so this i we're gonna pass this in it's because we're trying to add it push into our stack and we'll pass in what else should i pass in oh the limit yeah we need the limit too okay so let's just literally copy and paste all this and okay so like how are we actually going to handle like changing this condition based on whether it's like a decreasing factor or increasing stack well what we're going to do is we're going to create a by function which is just like a callback function and these two integers here that's just going to be these two integers here and i need to pass in the thing that we're returning or we're turning a bullion right because when we're just going to do this little check and then we're going to return a boolean and we're going to it puts on another line it's getting long so we're going to call this let's call it compare all right and then what we'll do is we'll do compare dot apply uh these two values here okay and i'm going to go ahead and so i'm going to rename this to just stack and since it's no longer just a d this could represent the decrease in stack or the increasing stack all right so let me see what else we have to do so okay so now we just got to call this so get windows start let's copy paste that pass in our decreasing stack and for the just remove all the types and then for the compare part we just have to do um i'll just type it right here so a comma b it's for decreasing stack it was less than or equal so a less than or equal to b and then we'll pass in the limit at the end okay so now we're going to say windows start equals the maximum of where we currently are and whatever we uh if so if this forced us to move past anything then um this maximum will uh will give us that value right so uh get windows start uh windows start okay cool and then we would do the same thing for the increasing stacks we could just copy paste that okay and i actually need to return windows start down here oh this is my spacing's all off when i copied and pasted it okay so inch oh my god window start equals zero and so windows start gets over in right here and then we'll just return windows start okay uh i think we are good let's just run this what's wrong with this to find oh what am i doing longest needs to equal math.max of longest because this might math.max of longest because this might math.max of longest because this might not be our longest sub array anymore after we update the window sorry okay oh i didn't update the condition right here so this all that changes that this needs to be greater or equal now okay cool so let's submit it all right so uh that's how you do this problem this is of n time i know it looks like it's o of n squared because of like these inside while loops but you just have to think of what's actually happening um we only push every element in the stat every element in nums gets pushed to both stacks one time and every element only gets popped at most once from those stacks so that's why it ends up just being o of n and the space would be o event as well alright cool bye | Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit | find-the-team-size | Given an array of integers `nums` and an integer `limit`, return the size of the longest **non-empty** subarray such that the absolute difference between any two elements of this subarray is less than or equal to `limit`_._
**Example 1:**
**Input:** nums = \[8,2,4,7\], limit = 4
**Output:** 2
**Explanation:** All subarrays are:
\[8\] with maximum absolute diff |8-8| = 0 <= 4.
\[8,2\] with maximum absolute diff |8-2| = 6 > 4.
\[8,2,4\] with maximum absolute diff |8-2| = 6 > 4.
\[8,2,4,7\] with maximum absolute diff |8-2| = 6 > 4.
\[2\] with maximum absolute diff |2-2| = 0 <= 4.
\[2,4\] with maximum absolute diff |2-4| = 2 <= 4.
\[2,4,7\] with maximum absolute diff |2-7| = 5 > 4.
\[4\] with maximum absolute diff |4-4| = 0 <= 4.
\[4,7\] with maximum absolute diff |4-7| = 3 <= 4.
\[7\] with maximum absolute diff |7-7| = 0 <= 4.
Therefore, the size of the longest subarray is 2.
**Example 2:**
**Input:** nums = \[10,1,2,4,7,2\], limit = 5
**Output:** 4
**Explanation:** The subarray \[2,4,7,2\] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.
**Example 3:**
**Input:** nums = \[4,2,2,2,4,4,2,2\], limit = 0
**Output:** 3
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 109`
* `0 <= limit <= 109` | null | Database | Easy | null |
1,032 | Hello hello everybody welcome to my channel it's all the problem in freedom of characters to implement his team chapter class carlos slim check kar witch gets relief but switzerland constructor in data structure will give words and various methoded witch will get neither patient nor notification glass virgin oldest In the letter and spirit of the world in the giver is the example will be constructed and will be the chief and will get the correct video actor will be id porn tell anything our history like constructive said happy check is it content character id know it content Do But No Return Soon After Midnight Subscribe 2009 Half Ninth ABCD Noobs Straight Note Straight Reserve Which Seamed To Return With Boys And Subscribe Button To 2017 English Letters Video Please Ujjain Who So How Will Solve Problem Solve And Subscribe In Your Mind Will To All the World in One of the Tarzan One Time Which She Will To All the Like Problems Directly Taboo Report Subscribe Directly So Let's After Getting His Will Power Come Set and Notes How Will Generate All the Worlds First Step All Will Start From the end of the builder on which explanation ladies vs super villain is the noble deeds in sydney for this does not mean that straight to Thursday civil war or with whip will do the words from correct and implementation of solution is Airtel Distributor for Keeping the Places of the World in the Sense of More to the Meaning of the Word From - 120 subscribe this video give Person Shamil Virvar on the Places of the World Can We Make Sure That War Subscribe That the Solution for the Two Get accepted 100 servi pattern first automatically half minute and subscribe to the amazing problem is that straight turn off nk l sorry third Indians after getting no isi builder normal bhed from cd deluxe starting of the self made this year will have to search the World from the world's oldest universe but last subscribe thank you for creating the tribes from normal life and they will drop it from r soul will look like this ki and will create denotes from which will address vijay disbursed dip node and will have seen node in This World Will Have This Year So Let's Meet Dance Makeup Person Video Similarly After World Must Subscribe Channel Main To Sari It's Not Be Arriving In Reverse Sidwell For First And Young That Choudhary Is Special Person Word From Quote SVR Reverse Verses Try Not For searching straight pattern egg bcd lead key and little abcd crops search so what will oo will check for this others are in the video then subscribe to the amazing learn from this video all will return from books from evil check is there is no issues will Return is straight forward century of forms proven try will work to so let's implement this I have implemented with abe security map data structure and boys subscribe this video please subscribe and up the stop this is the best way to make the thing subscribe Thursday try thing Not elected call route nobody will release references in mostly new history builder who alarm in the morning route is new 's creatures not so after nationalization be 's creatures not so after nationalization be 's creatures not so after nationalization be happy and all the words in incomplete word in words and withdraw into subscribe for the first of all they will strive to search The World Will Start From A Ki Prai Lord Which Related Not Vanish From Drought And Will Defend Itself From Depend Of Acid - Awal From Depend Of Acid - Awal From Depend Of Acid - Awal Ki And This Is Great Daily 120 Phase Notification Aa Ki Rajputs Notice Not Equal To Na And Decree I Want Every Time You Will Go through it and will dhanodo will we will do subscribe to yes brother so will check in our tribes have any next day of character 220 will check this God notice note channel and evolve with oo a return from a great salute nickel swift otherwise will continue Clipping Looking Into All Characters Also Processes And Subscribe To 200 Where Is The Okay Isht We Aap Ko Maaf Badu * Condition [ __ ] Condition Aap Ko Maaf Badu * Condition [ __ ] Condition Aap Ko Maaf Badu * Condition [ __ ] Condition President C August Alarm Set Compiled And Were Wait Submit Scored A I Connect Is Characters 120 MLAs Solution That The Like Button Subscribe to my channel press bell icon to get notification thanks for watching the | 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 |
350 | written an array of the intersection so what the question says is that given two arrays and we just need to return the intersection of elements of both the eyes and the condition given is each element in the result must appear as many as times if chosen both the arrays and you may return the result in any order that means see in this example you could say 1 2 1 and 2 and we could say that two element is occurring in the in both arrays and this Two element is occurring twice in both directions so the output must contain as previous times are an element appeared in both the arrays and you may return the result in any order so if you go to the second example 495 it is rfuc false the lines present yeah four is present so since the 9 and 4 are present in the array one only once we return 94 from direct to also only once because it's an intersection of two arrays and Phi is not acting and are array two so you don't output that and we order at which you return the output like you can either return for both will be accepted that's what they have told so what is the approach to solve this problem is we will take the example first and for this array it would be 4 comma 4 then a comma 9 comma a so once you start the array now we have to since we have to written an array right into section of two arrays let's define a new array called Ras and the length of the RAS will be equal to minimum of uh length of two arrays so that resulted length might be the minimum of array of two array settings it can be three the resultant rlm can be in this case it can be three or two or one also so any of this so the max will want to be in that case the minimum of length of two areas that is one we write here so I have to handle these conditions we will see later next coming to um let's say if uh to handle this condition means what let's say the array 1 has 4 and 4 comma 5. right so in this case Okay other has four five and nine right in here you could say you need not to have the fourth Market in the existing array I can explain the case so in this example four nine five four eight nine four is present in second another yeah it is an intersection then 5 is not present then coming to nine yeah nine is four command n must be the output ER nine comma four anything is acceptable if you like if you see the length of this resulting array now it is 2. but fear initially assigned the length of the resultant error equal to minimum of length of both the arrays that is three so but the resultant data has length two so the resultant array will be either 4 comma n comma zero or nine comma four comma zero because it has only two elements which we inserted so the third element would be uh MP that is zero it will be represented as zero to handle this function what we do is we will have a count of this number of elements in the resultant array so till while development only we will declare a new Oracle result so the result array will have the length the number of counts of the Elements which we interconnected to the horizontal array that will be let's see k so the New Order initial S and we run the while loop for the result and add the corresponding values to the resultant we uh we run the fall for the RAS array and add the corresponding elements to the result of it till the count which we have in this case it is two so that is how we handle this case so we're going to do this now we have sorted the arrays right now let's say I is pointing here and J is pointing here so if I is equal to J We Run The Y Loop until the either available Okay so in this case we check whether I is equal to J if I is equal to G we just need to add this that will be nothing but res of K let's say case initially equal to 0 so rules of K plus this we can write because once you assign a value to the gate position then the next element you come to the K plus position so that's why we use right R is of K plus this will perform nothing but at first will be initial as RDS of K and then it will increment K plus so that operation is done in this I and now if both are equal then you increment both I and J now so increment both I and G for the next iteration so once you increment both I and J now we check whether this element is equal to this element this Phi is equal to 4 no so if they still want point that you have to implement so get to know that you could see here the iron unit of second is 4 and the other unit of 5 is uh first are S5 so if You observe five is lesser than uh greater than four that means 4 is lesser than 5 so this is scope to get the file number in the secondary because it might be the next element also right after the five appears after four so that's why we have to check the condition if the other element doesn't match if nums of I is not equal functions here then you check if nums of J whatever is present here 4 that is lesser than answer five if that is the case as I said after 4 you need to get 5 right there is a scope to get it so in that case you just import J plus foreign you have here so and J question eight you have Phi and a see now is the way possible to cut Phi in the secondary mode because 8 is already greater than 5 and we are sorted that so that is about things you need not to check this connection in this case the L is part will contained that is nothing but I plus in this case the first thing we will have a scope to get a to the first step right so if uh secondary element is smaller than the possible unit then there will be a scope to get the first other element in the second array element so we increment the pointer J Plus if the faster element is smaller than the secondary element in this case 5 is lesser than a then this 8 might appear somewhere next to Phi in the first that is a possible in that case the increment I so we do I plus are equal so you add them to the res of K plus will be equal to nums of I so once this is done again you increment I plus and J plus s now at this time you could see foreign similarly arrays or sort of nulls to so once you solve the both the arrays now we okay after all these cases as I said you have four comma 9 as a resultant but the resultant array areas not resulting researl length is three actually so the last element would be zero in such case friends to avoid this condition we have K value pointing together k equal to 1 right because we do K plus here so K was 0 initially when you added for K will become one thank you so next you add again 90 will become two so you run the while a for Loop k equal to 0 sorry or yeah some other element M or l for or for I units positive sorry I'm just okay so for I equal to 0 and I lesser than K because I will be 2 this time so either 0 and comma one position that will have four comma so that should be added to the one more called resulting result so this result array length will be Okay so the results position we add four comma right so while I equals 0 I lesser than K and I plus result of I is equal to r e s of K oh not okay yeah that's it because usually we are going to initialize res equal to length was three but we obtained res only two elements as four common area intersection we didn't include five we couldn't get 5 right this 5 was not included in the intersection array so that's why there is a length reduced to one so in this case uh the output array was like four comma 9 comma zero which she will get it we need only four commonly for that we declare one more array result and tilde State position we run the follow and we add this elements to the result array and to escape in this case not the mean of 2 r s so now we'll declare array called Ras equal to U in of the sorry the entirely is equal to new int off so now why we select length is dot mean of length of Tourism is one dot length common comes to the left right so now in k equal to 0 to keep track of the elements in the resn that is resulted so now print I equal to 0 comma J is also equal to 0.2 I is pointed to one running and J is 0.2 I is pointed to one running and J is 0.2 I is pointed to one running and J is going to another so why less than nums coin dot length and J lesser than nums 2 Dot N so when you have this you check if nums of I is equal to nums 2 of J is one of I sorry very sorry if they are equal then you add that to the resultant that is res of K plus this is equal to sums 1 of I it can be comes to of J also so r s of K plus what will do it will initialize the RCs of K vary first then implement the K value by 1. so after this edge condition oh okay after this we Implement I and J both so I plus and J plus because we have found the result matching eliminating both that so else conditions will be in the else part we need to check now this temperature array one length is smaller or array two like this smaller if nums 2 of J is smaller than nums 1 of I in that case increment J plus s because there is a possibility to get so that is one case home foreign so at last after all these cases now uh declare a new array so in result equal to new end of K this time the length will be equal to K because as I said see we have the Define the minimum length equal to and the two others right so in the system won't contain the minimum length of industry or two arrests so it might be lesser than that for this case we declare a new array so for and I equal to 0 I lesser than K and I plus result of I equal to r e s of I that's it so at last written the music is there any mistake okay I knew this m should be Capital math yeah um and this should be numbers too 5.0 is lesser than k okay variable I is already defined in method intersection oh yeah that's why we will use the other something else then this should be changed is it successfully submitted if you haven't readers please drop it in the comment section we'll come up with another video next session and please subscribe for more such videos and keep learning thank you | Intersection of Two Arrays II | intersection-of-two-arrays-ii | Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2,2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[4,9\]
**Explanation:** \[9,4\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
**Follow up:**
* What if the given array is already sorted? How would you optimize your algorithm?
* What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better?
* What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? | null | Array,Hash Table,Two Pointers,Binary Search,Sorting | Easy | 349,1044,1392,2282 |
334 | all right so let's talk about the increasing triple sub sequence so you are giving integer real numbers you have to return true if you can fulfill the constraint and this question is pretty straightforward you can use in a brutal force but i don't recommend that brutal force is pretty straightforward ijk right and then you check every single index all the possible combination and then you starting moving your k first and then if you cannot find out the increasing subsequence then you move your j and starting the same idea right and then if you cannot find it then you move again right then you cannot find again then you will move your eye right so this is pretty much it right the problem is why you need to find out if there is the all the fun time complexity and then all of one for the space and in this one this is into a tube right it traverse every single one of the possible possibilities and then to find out the increasing triple subsequence so this is not good so how do you actually get the most efficient way so i'm going to just give you my solution and this solution is pretty it's pretty good and it's insane like i don't think about it and someone i know so i will have a meanwhile that means you set to the max by default value and then i will have a pointer for my norms and then i will have to check if my num is less than equal to mean one if this is true i'm going to update my mean one to num this is first if statement and then if this is true i update if this is false i point to my lc statement for the nouns it's actually less than equal to mean two if this is true i update my min two to know right so uh in this idea right you probably know this you find out the inclusion two element only two right now and if you want to find out the third one then you are just using an else and then you will say return true right here this is because what you check your first one the first if statement and the number is less than equal to mean one right and then you don't execute this if statement then you go on the next if statement numbs two i mean sorry nums is less than equal to mean two so you cannot find it right so you don't execute right then you know this is the third biggest the third smallest i mean the third smallest value inside an amplitude so your return should so this is a pretty much idea but i have to just walk through this algorithm with you so i will say mean 1 equal to max min 2 equal to max and here's my num alright my number's pointer so again if norms is less angle to mean one i update my max up in my mean one all right if this is true update i mean one two right so there's a reason why you use uh why you're using uh lesson info i mean be more accurate why you use equal this is because if you have one they are not actually uh increasing subsequence they are actually on the same level so you want to use an equal sign to keep updating your current smallness right so like the same integer is not allowed right and then uh you're going to go on your next pointer follow numbs and then you see the first if statement mean one number is the mean one then update to one right again move your pointer to five and then you see okay this time mean one is what it's less than num right so you don't update but the number is one less than mean two so you update five then move your pointer to zero right now this is get updated now you change another pointer four right and this is four then the last one six so you check your first if statement all right noms that's angle to mean one is this true or no this is six this is zero this is false right so you go on the next one is numbs less than equal to mean two no this is six this is four right so you go on the third one which is else now you return true right so you find out the increasing order based on the comparison right and this is not called uh this is not coincident the if you find out if you change the number for zero you are still going to return to why one two six i mean one four six sorry one four six this is older and even though like uh i mean even though the logic look pretty complicated but it's just correct so in mean equal to integer dot max value comma integer net stock right traversal number and then using the comparison if num let's go to mean one i update my main one to third uh third smallest i think and then i have to recompose at the end so this is why you have to keep track of the current smallest the second smallest and then the third smallest right so let me run it right so uh this is a solution so full of time this is time all of them right for the space this is space i mean constant sorry so constant followers space all of them for the time and this is the solution and i will see you next time bye | Increasing Triplet Subsequence | increasing-triplet-subsequence | Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** true
**Explanation:** Any triplet where i < j < k is valid.
**Example 2:**
**Input:** nums = \[5,4,3,2,1\]
**Output:** false
**Explanation:** No triplet exists.
**Example 3:**
**Input:** nums = \[2,1,5,0,4,6\]
**Output:** true
**Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6.
**Constraints:**
* `1 <= nums.length <= 5 * 105`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity? | null | Array,Greedy | Medium | 300,2122,2280 |
198 | That show, Hello friends, Tech's new video and 175, today is a very special day because we have to steal, not actually, etc., through this question, this is the not actually, etc., through this question, this is the not actually, etc., through this question, this is the house road and this is Google's question and Google has made such a good question that it is fun to see this question. Come, I mean, I will teach you the basic of diner programming. Okay, so we have that problem. What else has to be done is that you have to steal from the houses. Now we can steal as much as we can from the houses as per our convenience. Do it, if you have decided then message me that means we all are getting ₹ 1 then message me that means we all are getting ₹ 1 then message me that means we all are getting ₹ 1 for ₹ 2. This is the issue, otherwise you for ₹ 2. This is the issue, otherwise you for ₹ 2. This is the issue, otherwise you could have stolen all the groups but did not give the condition that Edison should be hot and should not be adjacent to him. If you steal this 1 inch from here then friends you can't do it, if you can't do it with two cars, you can't do it with three or you can't do it with one, okay, there should not be Edison people, so you have to maximize the stolen goods, okay, then as much money as you can. The more it is, the better it is, like here I steal Vansh Bhanwari, this can also be done, steal the vehicles that come to it and steal the vehicles that do it, but that is less, meaning it should not happen that no matter how much you You can go far, take care of this, then we will try a lot, let's get to that, let's go, then it should be here, just pay attention to this, if we start, then anyone, if you have caught the forest, then after we all From side to side, you can also go towards side, these lines are fine as per your wish, if you move from side to side, then there can be no problem, then when water option comes, then we go to the same option, then we see that from side to side Which is bigger, three comes from here, it is complete from here, so why I, this has become our answer, one thing we understand is that if we catch something from here, if we catch one, then two will not go after that. Those who will be caught, it's okay if we only look at you, then you are in front of us, whichever maximum suits you, when people look at us and off, then what are we doing here, who should do this, tell us about this relationship, okay. If it is, then it will be the maximum, one of each will be closed, but the rest of Bachchan's is fine, that is, whoever we are, we will stop his height plus, from whose two till the end, we will be on the position that this is zero, this is the thing, so you We will see from A to N, all the positions are there, okay, either I name these two, it will be our maximum that we can rob from Le Ban and even watchers, see the difference, there is no problem, okay either. We have seen this completely, we have seen this and this, do not remove the middle one, then further reduce our relationship in this way, this relationship will work. Okay, so this thing has to be kept in mind in DP, if we can tell you this in a good way. I have understood from this that our logic is that if it is 1231, then okay, now I can message you, create this problem and then after that, we go from behind and ask the question. Okay, if there are living beings here to see before the front to understand. So suppose that I am here, we are right at the starting point here, so I have one option, so choose one, I have written it right there, okay now I have also made this wall, you have accepted that I have come to the wall, now let me tell you one thing among these two. If I have the option to choose one then I will talk from the side. I will talk for Rs. 2. Okay, you find the discussion on Churna Two Three interesting because now we have reached Three, so we have two types of questions here. Force. One has to carry out Vanshree Light is the point to create so what will we do if someone uses it because we will feel the difference of forgery and if it reaches our own then we will have to see that we cannot take the exempted one, we can take the free one. After that, which of these two is the two, then the tubeless 180 is free, isn't it free, or we use one of them, then we use two, then after being young and tied, neither will I have Gafoor by sucking caption2 So definitely you will do something else, then ultimately after going there, I understand one thing that there is so much trouble that we are having trouble seeing everyone, when we came here, we had this from the plate, then the tea here is like Kishore. If we look at the previous two value, then we just have to keep in mind that the previous two value has to be caught and our answer will be Nimesh Maxima. It is okay that ultimately the results that come are coming by special judges and if you want to see the makers paste then We know that it is better than doing one plus two, let us do something else, okay, so this is our simple method, its code is also similar, so now we have understood what we will do, we accept it if we need the previous values. That Robber Near Auto is what it is 0 If we find anti in it then we will stitch our stomach and believe something like this that R1 is r2 and this is their value so for any norms I have handed over our temporary patience to here. We are doing this because we are moving forward with one value, we will take the temperature evening, we will take the maximum, and it is theirs, we should leave the rally between R1 and America and do not want to catch the adjustment, so those who will take it to the maximum, and ours since 2010. Tubelight was born in this country, that police station was Jaisalmer and the copy was told that you keep it away, it is 4 crores by adding these three, otherwise whatever will go ultimately will go to our tempo, and while doing this, our potato will be the same in the list when it is finalized. Will return our answer idiot, how simple it is to be explained, if logic should come then enter then always convince him and in Bloody Mary, you are giving with me, it was a good problem, it is such dynamic, lots of contacts will come, so like the video, why not Do n't forget to subscribe the channel, how are you watching in the tagged with family video. | House Robber | house-robber | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 2:**
**Input:** nums = \[2,7,9,3,1\]
**Output:** 12
**Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 400` | null | Array,Dynamic Programming | Medium | 152,213,256,276,337,600,656,740,2262 |
917 | welcome to september's leeco challenge today's problem is reverse only letters given a string s reverse the string according to the following rules all the characters that are not english letters remain in the same position all the english letters lowercase or uppercase should be reversed normally when we reverse a string we have a two pointer solution we have one pointing to the left and one point to the right and what we'll do is swap the two and then increment the left pointer one and then decrement the right pointer one but here we only want to reverse letters so all we need to do is put some sort of condition to either increment our left pointer all the way up until we see a letter or decrement our right pointer all the way up until we see a letter and we have to make sure that the left and right pointers don't cross so let's initialize first our left and right pointers to be zero and length of s next i'm going to convert our string to a list to make swapping easy and normally when we do a reverse algorithm we say while l is less than r let's swap our letters s of l sr equals s of r s of l and then we increment our left pointer and decrement our right pointer right but we're gonna have to have an extra condition here we'll say while uh s of l we're going to use the is alpha function we're going to say while it's not an alphabet letter we are going to increment this left pointer but we also need to make sure the left and right pointers don't cross so we'll do this and all we have to do now is the same thing for the right side but we'll be decrementing instead finally we turn the s lit uh string we'll do a string join and that should be it so let's make sure this works okay it didn't work okay i have to do a minus one for the right pointer okay so that looks like it's working and accept it so time complexity is of n and space complexity would be the same because we have we're creating this into a list yep that's it i don't think there's anything i'd love to say so thanks for watching my channel remember do not trust me i know nothing | Reverse Only Letters | boats-to-save-people | Given a string `s`, reverse the string according to the following rules:
* All the characters that are not English letters remain in the same position.
* All the English letters (lowercase or uppercase) should be reversed.
Return `s` _after reversing it_.
**Example 1:**
**Input:** s = "ab-cd"
**Output:** "dc-ba"
**Example 2:**
**Input:** s = "a-bC-dEf-ghIj"
**Output:** "j-Ih-gfE-dCba"
**Example 3:**
**Input:** s = "Test1ng-Leet=code-Q!"
**Output:** "Qedo1ct-eeLg=ntse-T!"
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists of characters with ASCII values in the range `[33, 122]`.
* `s` does not contain `'\ "'` or `'\\'`. | null | Array,Two Pointers,Greedy,Sorting | Medium | null |
84 | Hello friends, welcome to the new video, question number 84 is the list of DS rectangle in histogram, Arya's question is tax question, other category is your DP energy question, you guys will get the interview with us on Google Facebook Amazon, let's start. The question is that you have been given an interior, basically the height has been known, you have to make a histogram using that height and from the histogram you have to find the largest rectangle, which is the largest rectangle being formed and finally you have to find the area of that rectangle. finally you have to find the area of that rectangle. finally you have to find the area of that rectangle. So you will see this program, you have created this interior using one, you are looking at the diagram in front and which of these is the largest rectangle being formed, many rectangles are being formed, you will see that the largest rectangle is being formed, if you consider the two pillars. Take and two units below the width, then it is 5.22 because units below the width, then it is 5.22 because units below the width, then it is 5.22 because 2 blogs and five units, if we consider the height of both, then we can consider the area of this rectangle as 10 units, consider the height of both, then we can consider the area of this rectangle as 10 units, consider the height of both, then we can consider the area of this rectangle as 10 units, so first of all we make this program, we took out the largest rectangle in it and we used it. After returning the area, let's understand it in a little detail. Let's start with the large rectangle in histogram. In the question, we are given an integer of height. And that leg is given to you to create a histogram using the interior height and that program. If we want to tell the area of the largest rectangle, tell the area of the largest rectangle, tell the area of the largest rectangle, then do not get confused now let us see how we can make a histogram by using this height increase a are, so first let's make a histogram. Okay, so you will see that first the height is two, then a histogram. Let's make height two, okay, then height one, okay, then height five, then height six, then height two, and then our height is three, so you will see these tears, we have given the height, we have made a histogram of height, now what to extract now. In this program, you have to tell where the largest rectangle is being formed and return its area, so basically you will see that many rectangles are being formed and we will also see some examples and then we will see which one is being formed the largest and tell its area. First let's look at some small rectangles, what can we get in it, I can see a rectangle, what is the height of this rectangle, the height is looking at it is two, what is its method, it is a single block, so its is with one and its area is What will be the height, if it is two with one, then what will be the area, so into one, okay, and what will we keep in it, I live in Adams and you guys will know what are rectangles, so this time, let's make a slightly bigger rectangle, you will see a rectangle like this. It is also being made, okay, what is the height in this rectangle, all these features have one height and you will see that the height is one and what is its width, you will see that it has a height from 6 blocks, so 6 breads. So whatever is your area is going to be into six, your area will be six, okay and any rectangle can be formed, let's try a rectangle, this is also being formed, what is the height in it, these two which are plus, the height in both is 5common, okay and these two are plus. So you will see that if there are two blocks then its west will be our two so its area is ours basically you will see that 512 two is our area tan and apart from me this is the largest rectangle being formed in our example and its area tan returns us. If you have to do this and you will fry some more, then I do not think that a bigger rectangle can be made than this. Okay, so in this question, we have to find the area and you must have seen that we have been given the height, where is the problem coming, the problem is with you. It is coming in and we have to find the area. Okay, we have to find the area and the height has been given to you, so if we work a little hard to find the width, then we can do this question. So now whatever concept we understand, basically our focus will be that we have to find the width. Okay, so let's start and see how we can find out the width. Let's take some examples and in this I am sitting in my block with a height of one and that one and I am seeing how far I can stretch to the right. And there can be deadly tightness in the chapter and basically you see my position, I am with my height one, which is my index, the second induction which is ours, we are sitting on it and we will see to what extent we can test it on the right and left. We got every position to see how far the wid could go We sucked our height one and saw how far this stretch could go So we got the idea that these could be classic and move on Okay now this time we We are sitting at our height five and at height five, if we go to the left then basically our French is not working. If we go to the right, there is an A of six length, then it will stretch to the right, then we will know that our width is two and where we are sitting. We are sitting at our height five, so from there you can see where we can go left and how far we can go right and let's see the example, where are you sitting this time, what are you sitting on the second last index app room? His height is also two, okay and he is on the left, your three positions are left, tractor thief and on the right, you have access to one more question, so basically if you look at each position, what can you find out, at each position, if you look at the left. I have the touch and the right boundary and the left ventricle is the left ventricle, so you will get the height and height. You know the height is your two. Basically we have taken out the with, so how will we calculate. Let's start with the. We have to calculate with, let's take an example. Index five, let's take the index and we have our value feedback and this is our index two, so from here we will see that on the left there is no stretch happening anywhere else on the right, we track one position forward, okay and once we write the index These are some of our indexes, so what we have to do is we have to see left ventricle and right ventricle. How to get a good sweater. You have to see that the five can stretch to the left till the point where something greater than 585 is found on the left and the five on the right. To what extent can this be true, if the fiber is found bigger than the fiber on the right, it is fine and if it is found smaller, it cannot be stretched, then what do we have to do, you see, whichever is found smaller first on the left, take it as the left boundary and whatever is found first on the right, If you find it small, take it Rawdi, then the left ventricle is small on the left, I can see it on index one and if I go to the right, this is six feet two, then on the right, it is small on index four, so if I see the left and right boundary, then I can see The right boundary is the expomore where the smaller one is found first and the smaller one is on the left, index one, so my five can be stretched in between, I have taken these left and right boundaries, so now using the laptop by right boundaries, I have divided it. Find out that if you do - then you will see your free that if you do - then you will see your free that if you do - then you will see your free coming but we have seen that I was left and right boundary so to balance we will have to do a little minus one, then exactly we will get our two blocks because you have caught the left boundary and If you have caught the right boundary, then to find the middle length, you have to do minus one once, then you will get its exact width. Okay, so in this way we can find the width and you have come to know that you can find it at every position. So now let's start and see at each position how we will calculate the with. Let's take the first position and at the first position we are going to do the same. We will calculate separately how we can stretch on the left and how far we will reach on the right and They will calculate separately and cannot be calculated together and then we will calculate our total and if you go to the court, then you know we will combine it for example, it is not difficult, it becomes very easy to implement and I will explain it in detail in the court. I will explain but right now we are just focusing on where is the stretch on the left side and the ear shape on the right side and do not want to get into technical terms like state etc. If we understand the details in the chord then let's just see how far the stretch is on the left side. And let's see, the thief can come to the right and we will find all our boxes in the middle and we will take out our belt, so first let's calculate the left, it cannot be calculated simultaneously, okay the left will stretch till there. Left we will get small but now if we go to the left, if you are sitting 0n extra then there is nothing on the left otherwise you can consider it small. Hey, if you go out then basically we will go before zero, then there is a minus one index, so you will get a small one. If you don't find it then you will select the left boundary right there on the hair, we have to select something left behind, where we are sitting, we cannot consider it as love there right boundary, so even if that is the first position, then left front is you. We have to accept that minus one is fine and we are not taking out the right boundary right now. Now let's move ahead. The next number is one. What is its left laundry, meaning where are you getting the small one in the left, till then it can be our actual. If you go to the left then it is 282. Ours is not small and if you go before two, then if you go out of the key, then we will have to consider minus one as the left boundary. Okay, let's come to the next number. The next number is the electronic of five. How far can 572 be smaller than 5 in the left? Where is it, where you will get small, from there it will stop being straight, that loop will be laundry, so before 5 you will go, there is one and that is small and one is our index at one, so we have written one here and we are doing this inductively. Basically we have to save the index or right-left index, save the index or right-left index, save the index or right-left index, then you will also get problem with it. Okay, don't get confused in this. We are doing inductive. Let's move ahead. The number is our six. Six is Lu. our six. Six is Lu. our six. Six is Lu. How far can we reach, if in the left. If you get something smaller then it will stop being straight, that will be our lace for entry on the left, you will go five, if it is small, then the left grinder for heights is our two, index two heights, go up, go forward, height up, height in Dual app. How far will the test go, you have to see, small one will go to the left, it is not small and you will go to the left, five is not small and you will go to the left, one is our small one, so our left boundary is the index 54, which is our two to have a. We have found out where. There can be a stretch in the loop till the end, okay and right now we are not seeing the stretch on the right, let's move ahead number 3 is free to the left, till what is possible, if something small is found on the left, it will stop being straight, on the left we have To is getting, you are small, to is on the index for, so for our free height, the left boundary of which is where we can consider this tree, okay, now let's look at the right truth, okay and start from the first number is yours. Two is okay, how to, they are in the right angle, you will see, take this one in the chord, we play it a little in reverse, but for the sake of understanding, I am starting from the first position, now we see which one is smaller on the right, so we have the biggest one. Let's start from the last position, but here I am doing an interest first, so where we get Chota on the right, our straight will stop, so if there is one to the right of Two, then Two cannot be stretched further, its index of in and one. If it is made, then write it here, okay, now the next number is one is right, how far can it be true, one will go to the right, five has stretch, and you will go to the right, this can be stretched, and you will go to the right, this too There can be a big stretch and you will go to the right for three. There can be a stretch here too and you will go to the right. If you go out of Anti Zara, then we have not found any small one. Our height one can be tight till the end right. So Right boundary, what will we write? Nothing small was found, Minty, that you came out earlier. On the left, you wrote your minus one. Here, if you come out, you have to write six because your integer index is up to five, so now you will come out and You will write six because we got height one, ours kept getting stretched, nothing small was found. Let's come to the next number. The next number is five. How far can it be true in fibroid? You will go fibroid, there can be a stretch in six and you will go right, two is small here. If search is not possible then two candidates are for then write for on the next number that six how far can it be true the next number two cannot be small at this stage index of two write for f4 come on the next number now the height of our two is this The height can be a mistake because it is the right method and if we find any small jar, we will close it there but the right method is it can be stretched and in the right you have the interior. If you go out, then our height can reach till the end of 21 cm, then come out. If you go to the right boundary, we will have to take six because we have to take some left and right dongri. Okay, the last number three is free. How far can we stretch? From three, we will go to the right and we will go out. Hey interior applicants, we will write six because of our hearts. It became a bit tricky left and right and I had told you how to calculate the width for every position. You know the height. Which height can be tested to what extent in the left and right. It is a simple formula. Apply it and you will easily remove the fast. We have calculated the height, we have given the entries about it and we can easily calculate the area, so we just have to focus on how we will calculate the width. Now let's come to the cord and tax implement it. We will understand in details and we will also do the final calculations in the court. So we will start the area and come to the court, we will check the court. We will do the same in the court as we saw in the diagrams by finding out the main focuses or with and then a line or two. By writing the code of , we will finally find a line or two. By writing the code of , we will finally find a line or two. By writing the code of , we will finally find out the area. The giver in the question has given the interior height and we have seen every height till which height is the fatal stretch on the left and we can say thief on the right, so a rectangle was being formed at that point. We used to go to the height and see what rectangles are being formed. We will find out the area of all the rectangles are being formed. We will find out the area of all the rectangles are being formed. We will find out the area of all the rectangles, which will be the largest area, we will return the biggest rectangle to the Lokayukta, but the main focus will be on how the width has been calculated. Finding the area will be of one or two lines. The code is ok, so what did you see in the diagram, you did not draw the left boundary and made the right boundary. Okay, so let's do the same in the court. I will draw the left boundary and make the right boundary. Okay, let's copy it quickly. And let's make the right one. Okay, okay. And you saw that the left and right boundary was drawn and using it you had calculated our fast at every point. So let's make the height of one person also. Okay. For left and right dongri is coming out and by calculating the width you will fail about the interior. Okay, then we will get the height and width, so we can get the single line code by multiplying all our rectangles, patience, okay and I said. We will use the technique of giving left and right boundaries and folding it, so basically if you do not use check then it will become very complicated and if you use step then the simplest way is what is starch? So let us make this pack and in detail. We will understand how these are failing due to tagged, we will get help from the track, okay, and in the left, very basically, did we mince the boundary, did we index left induct, where did we reach the intersection, right index - what did we do by index - what did we do by index - what did we do by removing the boundary. If we take it, we will also do some indexing in the tag, so first let us understand, then we will start, let's take an example, this is our example, okay, so this is our example, what do we have to do, we have to create left and right boundaries using this pack. We have to fill, okay, let's make the top and first make the foil, which one will be on the right then okay, so this left interior will be our fill and we will use the step in this, we will do this, am I making an extra one, why not write in the court? I am making it because I want to do it, I don't want to install it, I will show it to you with numbers so that you do n't get confused, and also I am making the index by taking 2 inches, I will put the number also, I will put it in one, so as you want to understand it so that you don't get confused. No, it's okay and we will do it. What should we do basically? We have to frill the left boundary of ours and then hit the ride entry to feel it and go out with it, then to remove the weight, we will have to walk, we will talk about the complete entries. You will have to run the loot, okay so first let's write this and at every position you have to see the left boundary and the right boundary. Okay, so this distance is being calculated but basically it should be that I remove this for the left. First I will take this leader of the left, okay and after that I will copy this, I will say this for the right, okay and we will feel the track from the stand, it will take a little help, how will the scalp be placed in it, that Arthur, you will paint the first position above, you know. If the left boundary is on your left, then it is 200 index, so ours is on zero index. Okay, so there is something small in the two to the left. We have to see what is small in the two to the left, there basically a will stop, so tuition is in the left. If it is not small, then the left boundary will be our interior. If we go out, then the left boundary will be our minus one as we saw in the diagram. Okay, so the left front will be ours. So, in the beginning, we say that if your step is in the camp. You can support it in such a way that if you eat the stock then you can close the left boundary, okay, there is no problem in this and as soon as you process it, now this number will not be in tech. Do n't put the number, you have to put it intact. I am also showing you by putting the number. We will put ascended in the pot. There is no need to put so much double. So whatever is its index key. Okay, now we will move ahead. Now we will come. Our next number is How far is the stretch going from one to the left? If there is a bigger number on the left then this will continue to be true because you will see that it can be made inside the toe also. Then it is possible that if there is a bigger number on the left then one would be your stretch. It will keep happening, it will keep happening, okay, so we have to find the left boundary and the current data of the boundary will not maintain our step. So if I tell you that the SP of one is half, then it is okay if it is small as long as it is small. That left mustache will continue to grow, it will grow like Gulf country, if you are removed, then it will continue to be your space. Okay, so as long as yours is small, that means two, this one is yours, as long as it is small, that loop will match, then two. How will you do the account? If your account is broken then you will compare it with the tax. Okay, you will write tag dot pick because no number was given in this test. This tag is our index. So here you will take out the contact from stat at peak and our one. If we compare one with two, then we compared one with two. If yours is small then keep sketching because one will be your feel. It is okay in the rectangle. Keep stretching and okay then keep emptying the step. If it is small then Clear this track, Josh is getting so stretched, clear the step because the letter P will hold the boundary of the left, where will the laundry of the left go and stop, okay check, maintain the data and keep doing it, so we got the left key. Boundary will be found in actual, okay and if this entire track gets empty then you know that - it will be made in actual, know that - it will be made in actual, know that - it will be made in actual, here if it gets completely empty then we will close again - but if it is close again - but if it is close again - but if it is not empty then the pack but actual This index would have been 082 and our one stretch by chance would not have been finished, we would have caught from the stag that we had entered this club, if one was not vacant then we would have written the balance, you would have picked up the left boundary, we would have picked up from this tax, you would have picked up whatever stock is in the future. There is an index in the peak, okay, this is the index and this number was not there, so I used the index to find this number and you have an index here, if it is jhali - if it is not happening, then - if it is not happening, then - if it is not happening, then whatever is left is the index on its left. That one will be on your leg boundary. Okay, and he doesn't understand the concept. If you look back a little, we will keep doing it in this manner and then what we are going to do is like we will be facing forward, this is our well which was already empty so we will add our number. We will do this in the take. We have discussed that the way we do movies, now we have five main points, so we have added the index and whatever number is in the set, so in the last here you also have to do this before starting the process. All we have missed is to add in this. Next number is our five and decide that maintains the data. Okay, so basically what you will do now you will come here in your loop, you will see that five is your small then left mustache will be there. The stock is empty, we are not feeling it. The track is not even empty, it is not feeling crisp. Now you will see that if you put the pick of the step, then the number in the pick of this track is one and the index of this number is Now we will put the spider in some tags before becoming the moong and put its index two in the strat. Okay and we will come to six and we will learn, we will see that ours will be small so left. Mustache kind of thing, but our six is small or not, urban our six is small or not, urban our six is small or not, urban bodies, if the first condition fails then only the step is done - you had put one, but the pick of the week, only the step is done - you had put one, but the pick of the week, only the step is done - you had put one, but the pick of the week, put it in the back of the stock, your how to induction number five and October. Total two, come and move ahead, I told you before moving ahead, let's do statement TV. Okay, that was the last step. Let's put it in the track. Let's do the number. Let's put it in the set. Now we have moved ahead. But you have to watch it. You are half. If the phone is smaller than 6 then vacate this track. If your phone is smaller than 5, vacate this track. The phone is ok. We had seen this. Keep emptying it from so that you can catch the left boundaries of yours. You are not small, this is better than one. We have come to one. Geet behind back, if you are not half small, then toe cannot be touched till the back, okay, so we have made this first empty, now come down, it was empty, by August, it would have been completely empty, then we would have put minus one, but in the tag. If there is anything left, then whatever index is there in the pick of this track, put it here. If there is one in the pick of the stock, then we will put one here that before proceeding further, we make an entry, put our number in the track and this index Let's put it in the track, this is our four, okay now we see that ours is smaller than the number behind, not the number behind, the number in the stock, but the smaller one is not ours, so I will not empty this strat and The stock is not empty either, otherwise let's put minus one. Now put whatever induction in the pick of this track. Basically the index in the take care pick is our four, so you will come to your left boundary and put it here. In this way, on your left. Create a boundary and you can also create a right boundary using this. If you copy this code and use the same concept, you can also create a bride entry and I think you can understand by yourself what to do with this minor change. Let me tell you that you have to run it a little in reverse. Okay, you will run the loop in reverse and do it in this. Will we run it in this way and will do I - - we run it in this way and will do I - - we run it in this way and will do I - - and will see from the last position. If there is a step at the last position, then this time we will not - This time we took six obstacles, meaning not - This time we took six obstacles, meaning not - This time we took six obstacles, meaning we had gone to the right about our interior. In the last, we had our ant going up to index five, so we will feel like the diagram we saw and the rest of the code will not change, the code is yours. The SIM will remain, you just have to write it and ride it and you write it in this way, we, I, you, and there are minor conditions in it and I would like to change, whenever you check in the tech, before that you One more condition was to be seen whether your tech is empty or not. In MP state we never check, so it was to be seen that this condition should run till our note MTO. If these tags are never checked, then one more condition was imposed. And when you have used the first one, then clear the text because we need friends' take for Rawdi, so friends' take for Rawdi, so friends' take for Rawdi, so clear this track also and you can remove the right and left boundaries using the same logic. Now what to do? You have found out the area. Okay, how will you find out the area? So next we have found the boundary for the area. So to find out the with, let's run the loot once more. Okay, there is not much else, we will hit a little shortcut in the court. Now there will be more in the lap of two lines. If they finish then how will they go through every point? What did I tell you? What did we do to go through every point? We did it from right to left. Okay, we went through every point and I said - do one more. So that in order to have a little balance, said - do one more. So that in order to have a little balance, said - do one more. So that in order to have a little balance, our right and left sides were stretched, so to balance, we had to do minus one, only then we will know exactly how many blocks we have. Okay, now find out the area, how will the egg come out at every point or else? Along with this, I also put the maximum that whatever area you will calculate, keep calculating it here and whatever is the maximum, it will start, then how will you calculate the area, what should not be done to calculate the area basically, we need to know the height of each of our points. At that height you have to multiply it with this simple and mix and whatever is the maximum it will start because we have run the function of because we have run the function of because we have run the function of and finally return the area. I think the work will be done. Let's return the area. I should compile this, I think the code is done, so I think last, this will work directly for us, we will have to pick it quickly, and this will become our zero, this will be I plus, let's see this once. We will have to remove the racket from here and let's cut it. Let's quickly compile it, submit it and see that it is being looted. We will have to make a change in the cord. We have written this loop in big letters. This will be a viral loop for you. You have to pop till it stretches on the left and you have to pause here till it stretches and on the right we will see that if this type of thing continues then basically there are while loops because there is no single condition where it will happen. Till then, if we have to do it then we cannot write it in this loop and now let us compile it once and submit it and check that it is getting set. After submitting, let us see that our code is also being successfully submitted. You can subscribe to my channel. You can go to about section and mix Google set, you can see in the shape which video of interview questions I have made, which list question type video should I make, category, you can do voice search, channel related news, which video is going to come next, all You will get updates in this video. Thank you very much for watching this video. Jai ho kar do ajay ko do. | Largest Rectangle in Histogram | largest-rectangle-in-histogram | Given an array of integers `heights` representing the histogram's bar height where the width of each bar is `1`, return _the area of the largest rectangle in the histogram_.
**Example 1:**
**Input:** heights = \[2,1,5,6,2,3\]
**Output:** 10
**Explanation:** The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
**Example 2:**
**Input:** heights = \[2,4\]
**Output:** 4
**Constraints:**
* `1 <= heights.length <= 105`
* `0 <= heights[i] <= 104` | null | Array,Stack,Monotonic Stack | Hard | 85,1918 |
303 | guys hope you're doing 3r today's question is range some query immutable it's an easy question on gate code and involves an emic programming as one of the possible solutions and I thought it would be a good one to have on the list so the question says given an integer array nums find the sum of the elements between indices I and J I less than equal to J inclusive okay so I and G would be inclusive when it says that find the sum of elements between I and J right for example given is this array and the sum range 0 comma 2 so it means that 0 1 & 2 range 0 comma 2 so it means that 0 1 & 2 range 0 comma 2 so it means that 0 1 & 2 so the sum of these elements 3 0 and minus 2 which is 1 is the expected output and similarly the other values so you may assume that the array does not change there are many calls to some rate function so it means that this will be called again and again on this array right the important thing to understand here is just this that there will be more frequent calls and at the first look it looks like a very simple problem because whenever you get this you can just run a for loop from that particular index to the J index from I to J just some of the elements and return the answer but it would take U of n complexity for each some range all right so um let's just have a look at the various methods because this is an unsorted array so whatever approaches we can use to solve questions on unsorted array and think about an approach where you can improve the solution from just doing an oh F n for each some range one so please pause the video have a look and come back so I think here it's quite clear that we need to think about how we can do it dynamically right because finding the sum between any two indices is basically more about you know a problem which we can divide into subproblems and have our handy results right such that we can just use those results without traversing the area again and be able to find the answer so we'll be using dynamic programming here and what I think we should do as a part of the solution is to four so basically for each index in the area right what we need to do is that we need to find the sum of all the elements in the array before that index right so for example in this array 4-2 there are no elements in this array 4-2 there are no elements in this array 4-2 there are no elements before it so it would be zero four zero there is minus two so it would be minus 2 4 3 so I've just written that down here yeah so 4 minus 2 it would be zero four zero it's minus 2 4 3 it's sum of these two so again minus 2 4 minus 5 it is sum of all these three elements so 1 4 2 it's the sum of the elements before and so on right so now here as you can see that since the output that we are trying to create needs to have one element extra you would need to use a dynamic programming array of one size bigger right and why we need to do that is because the question states that we need to find the sum of the elements between the indices inclusive now if you don't do this basically when we if we store so whenever you have to find for example some range 0 comma 2 right we would know that @dp of three we have we would know that @dp of three we have we would know that @dp of three we have a value which is the sum of all elements before three that is 0 to 2 right and at zero we would know that it has the value of all the elements sum of elements before zero which is of course nothing zero so we will just subtract that so for example if you see here if the question says 0 comma 2 we will go for DP of 3 which will have 1 - this will DP of 3 which will have 1 - this will DP of 3 which will have 1 - this will give us the and someone if you see 2 comma 5 so 4 5 will have to go 5 plus 1 6 so minus 3 minus 2 right - so which is 6 so minus 3 minus 2 right - so which is 6 so minus 3 minus 2 right - so which is minus 2 so minus 3 minus 2 which will give us minus 1 right so that's how we will be able to derive our results in row of one complexity we would have to do this process just once prepare the dynamic programming area because our area will not change and then you can just use it to get these values like that so let's just get started with the solution and it will become much more clear okay so as I said that we need to have an extra element in the DP array right I'll just create so now here in problems like these when you have two functions right and one of them is being called again and again you need to declare your collection or array whatever you are using outside of both the functions so that they are accessible in both of them so what we will do is that we just do this for the time being because we don't know the size of nums so that's why we cannot like initialize it we can only declare it effect and then here we will initialize it and plus one okay and since we will always know that DP of zero would be zero because there are no elements before zero so we just do that okay now let's start the for loop so we start from one okay I less than equal to n because we have n plus 1 elements in DPW populate right and then I plus okay so now DP of I okay so the value of DP of I should be what so you need to think of it as a sub problem because if I am at 3 right and I want to if I am populating DP of 3 I want to populate it with the sum of elements of 0 comma 2 and I know that D P of 0 1 right which is here that contains the sum of elements before 0 right so it contains minus 2 so if I want to get this sum I'll just add 0 plus DP of this index and that would go into this index right so the DP of I minus 1 plus nums of I minus 1 right so DP of I minus 1 contains the sum of all the elements before I minus 1 and we add nums of I minus 1 to it which gives us the sum of all the elements before I write so we just have to do this okay now if I minus 1 right you just have to do this and yeah that's what that's also here and then in some range what we need to do is that to return now you've been given GI and as I'm saying that the next BP element right so J if J is the index DP of J plus 1 will have the sum of all elements before J so what we do is that DP of we'll take J plus 1 right because this is the value of all the elements summed up before J plus 1 right so it includes G as well now and we subtract TP of I from it right so yeah this should work let's see okay let's submit it fine so as you can see that we were able to do it with just so you can mention that to the interviewer that nuns of early vote yes definitely take oh of n time complexity but the some the method that from where we want to find the son that will take off one each time and this complexity would be O of n as well because we are using a DP array of the same size so I hope you guys find this video helpful if you do please like share and subscribe keep coding and take you guys | Range Sum Query - Immutable | range-sum-query-immutable | Given an integer array `nums`, handle multiple queries of the following type:
1. Calculate the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** where `left <= right`.
Implement the `NumArray` class:
* `NumArray(int[] nums)` Initializes the object with the integer array `nums`.
* `int sumRange(int left, int right)` Returns the **sum** of the elements of `nums` between indices `left` and `right` **inclusive** (i.e. `nums[left] + nums[left + 1] + ... + nums[right]`).
**Example 1:**
**Input**
\[ "NumArray ", "sumRange ", "sumRange ", "sumRange "\]
\[\[\[-2, 0, 3, -5, 2, -1\]\], \[0, 2\], \[2, 5\], \[0, 5\]\]
**Output**
\[null, 1, -1, -3\]
**Explanation**
NumArray numArray = new NumArray(\[-2, 0, 3, -5, 2, -1\]);
numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
**Constraints:**
* `1 <= nums.length <= 104`
* `-105 <= nums[i] <= 105`
* `0 <= left <= right < nums.length`
* At most `104` calls will be made to `sumRange`. | null | Array,Design,Prefix Sum | Easy | 304,307,325 |
1,461 | Hello Hi Friends Welcome Back Today We Are Going To Solve Tourist Co Problems A So Lets Start With The First Co Problem 1446 Which Coating Actor Now We Start Looking Into The Details Of The Problems And Their Solutions Is Meant To Mention Data My Channel Dedicated To Help People Work Preparing for Coding Interviews and Java Interview Samay Channel Has a Variety of Problems Which Should and Explained in Java Attempts of Different Varieties Light Dynamic Programming Languages Problems Programming Languages Problems Programming Languages Problems Binary Search Tree Is Graph Problems Deficiencies as Well as Spring Related Interview Questions and Law Too Frequently Last Telephonic Interview Questions Will Show A Few Of Preparations For Any Like Interviews Please subscribe this Channel Name 200 Lipstick Look Into This Problem The Power Of Spring Is The Maximum Length Of Not Entirely Something Which Contains Only One Unique Character During Its Return The Power Of String For example you have given its president senior character moral repeating this only one can give different characters and varied to senior leaders have to return to the power of the thing so let's move and share and we will discuss how they are going to solve this problem Solve will create one variable and twelve wealth and where seen switch on meeting character bank account will increase in cases pay not repeating character account will get 300 seats for example account variables non so British one side se hui aa the will start from the First Character Prayer Requests for This Character Venter Character Nine Character Account Will Be Sworn in the Beginning Should Start with CD Sanseri Is Not Will Always Be Sworn in with Previous Character It is Not Equal to a Shovel Dhundhala is the Account One is Always Busy in His Life in the Match Which Team Previous Character And Will Go To Subscribe Now To Receive Will Keep Track Of Maximum Subscribe To Go To The Character Is Not Equal To Basically Dare Not Give Will Really Dose Subscribe Will Go To The And Sunao Account Welcome To And Vigor To Country Key Control Vikram Free Life Due To Increment Account By Seeing Previous Character And When Doing Good Deeds Not Equal To Its Previous Character Seen So I Will Reach Initial Pure Account Deficit Which Occurs Loop Footwear Ka Test Match Vikas Maximum Value Have Seen So Hairy Low Na Hui Will Go To Duty Should E Capsule Keep In Preventing Account From One To Three Four Vs Payment Yudh Rich Food Additive Would You Have Found For Consecutive Days Back To Her Cont Isko And Max With Updated From Three To Four Wickets For You Have Singh Maximum Not FORGET SOMEONE WITH DIFFERENCE AND WHEN WILL VISIT CHARACTER THE DIFFERENT LIKE AND SHARE IF YOU WILL NOT WARY INITIAL DISCOUNT WORK PRO JUST RIGHT HERE ELECTION ACCOUNT IF SAMSUNG MAXIMUM ACCOUNT WHICH HAVE SCREENSHOT THIS FOR ELECTION KI ANY NOW A GO TO DESH TIGHT [MUSIC] [MUSIC] [MUSIC] 1234 Election Our Account Will Be Compiled For Five Minutes So Now With Five Years Account And Will Increment Our Maths 258 Developed 1520 We Will Put Forward Them A Current Affair We And After That Can We Go And Visit Duty Reddy Is Different Character Of The Day Subha jaanu good account s one hour maximum account assigned this five types and after death at jain urvi visit series different and jewelery and standardized wave with differences define this wiki previous lives in vikas vihar different size different than 200 will release account one so let you listen Soft The Maximum Account Dr To Front For Distic Special Song How To Return 501 Service Five 1,000 More Answers And Return 501 Service Five 1,000 More Answers And Return 501 Service Five 1,000 More Answers And You Can See There Fight With Answers For This Is The Back To Your Going To Solve This Problem So Latest Look Into The Implementation Any Problem This Problem Solve Back Create One Max and Account Variables Both Are One in the Beginning and Were Getting Through the Eyes Character of the Scream ACIT Switch Character Very Interesting and Wear Checking If-But Characters Matching Previous Character Checking If-But Characters Matching Previous Character Checking If-But Characters Matching Previous Character Will Start from Character 1512 Always See the Previous Character Fennel Matching Will Increase Your Account And Give Necessary Evil Updater Maximum Very Nice To Meet You Come Late Say Like 100 When Ever Visit See Right The Base Camp Till Character Meanwhile War Reinstalling Account One And Because Nau Appears In Another Character 123 Target This Account Family Tree 12123 And This Is Like This But They Are Doing Her And Death And Were Going To Return Max Website So Let's Take A Look At The Same Example Tattoo Respect Short Hair So Let's Get Started Now Swift Arrangement They Are During Sir Software Testing Correct Answers Let's Run and Test How is Set Behavior Friend Mix and That Oil Test Cases for Passing Nature Can See You Are Getting All Correct Answers Including 511 506 and Doing During Correct Answers Shoulders and Submit Our Solution A in Software Testing Hundred Percent Performance Hand Of 5 per cent in the memory of activities is very good and the time complexity of noise pollution is very attractive through the string all the character should be time complexity and decide who care for you to time complexity for this solution is more towards in and space complexity For the solution is order of one died because they are not using any candidate for data structure flight map link glycerin that you are using simple two variables too cute and sorry for the best complexities 5420 one problems later to you want to discuss and the regional problem Video Clip The Problem Let's Go Through The Description For Doing Good Example 100th Problem Is Loot Ko 2016 Kunwar String Contents All For Your Report Subscribe Knowledge - Settings And At Integral's Return Through Every Knowledge - Settings And At Integral's Return Through Every Knowledge - Settings And At Integral's Return Through Every Binary Code Of Length Quiz And Sub Screen Of S Otherwise Return Forms Type So let's take this example if hair oil can explain what is the problem in solar system insulated given to us and a pioneering spirit and have to find out if all the size two subscribe sure and size two minor this trick are there in this stringer subscribe to Means How Will Find Its Size Two Minor Stringers He 108 Rasikan 2013 Dates 104 3085 By Two Basically Force Wing Are Basis For Total Fostering That Former Minor String To Have To Make Her And All Of Distic President When Skin Tear Se Present hair act day man good 20 201 vision on this project roman reigns shiromani also present clear day 120 is president clear if subscribe and one is president senior vice president share so all these force wing are present in the given figure subscribe 100 aa basically approach to Where we are going to take to solve this problem is what we will do is merge greater heights and right hand side of things and will take from beginning will go and will get a string of five to the right fennel example I will maths science two streams from this Given String And So Will Go On And Hui I Pin Function Of Being Also This Is Dynasty Day I Will Put Into The Satanic Verses Will Put Into * Into The Satanic Verses Will Put Into * Into The Satanic Verses Will Put Into * Left After Great I Will Take Another Sub Screen Of Science Twelfth Science's Basically West Indies And Mothers 110 After Battling With To The Next To Link Most 2012 That And Again Will Dhanush Cuttle Tour Interesting By Handing Proper 1010 Wicked Tree And The Shadow Of The Rise Of Which State Is Equal To Three To Power To Right Character Power To Basically Lights And Rector Power Of Gift To Men Stud A True Power To Get A Gift To Give 124 Subah Surat That Is The Size Of Dresses For President Means The Best All The Tool Binary Code Or President Abs Hindi For This Is Not Going To Implement The Inquiry And Will Be Restaurant Tours That Today to a's basic and not a race to British tourist previous so ₹2 death in British tourist previous so ₹2 death in British tourist previous so ₹2 death in case of bakhari arrest to in s up to difficult tourist brajdham in combination with 1548 tourist husband jeth 100 likes basically a's so again election chotu race-2 mins For so again election chotu race-2 mins For so again election chotu race-2 mins For you will find in gift used to give free will find tourist through which get details for you will find to arrested for which aspect email light sweet crude let's take a look at the implementation based and created history of string year result and the created Descendent Linkup Spring And We're Going To Straight Through This Distic Right The Number All Characters Interesting But We're Going To Add Into The Sellout's Length Spring Tide A Grand Duke 200 Life Into You Will Create To Land Unite All Will Create Tour In String Shaadi Student Distic And They Will Keep Adding Friends * Set Taste You Can See You Year Adding Friends * Set Taste You Can See You Year Adding Friends * Set Taste You Can See You Year Creating A Year When Using Spring Function And Were Passing Noida Plus's Doing Great Souls In Captivity That Ever Hero Plus To Student Available 2014 Plus To Date Of And Plus To This Side Sites For The And We Are Going To Make Your Data Is Equal To Two Wheelers Maths Power Function Tourist's Right Tourist's Holiday Dinner For Example In This Is It Is Tourist To Ride Solar Geyser All The For Minor Sting 0080 President Arun Agarwal Powder Form Tight So Let's Go Ahead And The Late Say Reduce Example Force One Morning Shoot Proof Servi The Software Getting Through Right A I Today Late Chest Password Negative Specified Changes One Should Be False Because Now Will Not Have To Wander Springs Apps Team So You Can Listen Who Hair Also It's True Only Because They Are Too Defying All The Best Result 2016 That Sudheesh First To Letters Paris Hair And Destroy You Follow 0 Getting Hair 10112 Yaar Getting Air Balloon Yaar Getting Air Tight And 102 Yaar Getting Here Right 101 Software Getting Clear Intermediate Man 108 Questions Distinct Of Witch This Too Andher Is Not Recorded 105 So Let's Sexual Tuesday To You Want To Test Ride Specific Less Which Is Points Now How To Remove The Century Sorry And Listen Tips For Decades No 1210 Stream So Lets and Solution is Working Fine So Lets 51 Sector-12 of Test Has Cleared All Fine So Lets 51 Sector-12 of Test Has Cleared All Fine So Lets 51 Sector-12 of Test Has Cleared All Ise Examples Hai Ki Hai To Aam Kadi Clear Examples True for Ones Proven True False for Solar Coming Rate Fixed Through Modi System Software and Will Change its Form and Submit Dress Code 200 Good-Good Accepted by List Court 200 Good-Good Accepted by List Court 200 Good-Good Accepted by List Court 42% Only Performance and Fifty Seven Per Cent 42% Only Performance and Fifty Seven Per Cent 42% Only Performance and Fifty Seven Per Cent in the Memory Usage Which is Cent for This is the Way Can Solve or Check Per String Content of All the Records Size Problems Night With The Help Of Scent And Vision User Substring Method So They Can Get All The Sub Screenshots Size Of Basically From The Given String Tie And They Will Put Into The Set And You Want To Make Website Is Equal To Tourist Tower Basic Latest And Updated Do Logic To Solve This Problem Yes If You Have Told You Check My Channel Play List Code And Solutions Fixed Nine Letters And Emphasize them Java Problems Of Interviews In Big Companies Like Amazon Apple Google Facebook Yahoo And Microsoft And So Many Rate Companies And Whose Forehead With Problems App Consists Variety Of Problems Like Dynamic Programming Languages Related Problems Related Interview Questions Daily Graph Problems Binary Search Tree Problems Finally Search Related Problems Logical Base Problems As Well S Lord Of Telephone Recruitment Last Interview Questions Also Late So Please Request Check The Playlist On My channel like this video and if you find this video helpful please subscribe and liked your subscription is really important totke channel vikas that is the videos can go and reach to more people de can also watch these videos and get benefited wildest interview preparation for please subscribe The Channel thanks for watching this video | Check If a String Contains All Binary Codes of Size K | count-all-valid-pickup-and-delivery-options | Given a binary string `s` and an integer `k`, return `true` _if every binary code of length_ `k` _is a substring of_ `s`. Otherwise, return `false`.
**Example 1:**
**Input:** s = "00110110 ", k = 2
**Output:** true
**Explanation:** The binary codes of length 2 are "00 ", "01 ", "10 " and "11 ". They can be all found as substrings at indices 0, 1, 3 and 2 respectively.
**Example 2:**
**Input:** s = "0110 ", k = 1
**Output:** true
**Explanation:** The binary codes of length 1 are "0 " and "1 ", it is clear that both exist as a substring.
**Example 3:**
**Input:** s = "0110 ", k = 2
**Output:** false
**Explanation:** The binary code "00 " is of length 2 and does not exist in the array.
**Constraints:**
* `1 <= s.length <= 5 * 105`
* `s[i]` is either `'0'` or `'1'`.
* `1 <= k <= 20` | Use the permutation and combination theory to add one (P, D) pair each time until n pairs. | Math,Dynamic Programming,Combinatorics | Hard | null |
208 | hey everyone in this video let's take a look at question 208 Implement try only code this is part of our blind 75 list of questions so let's begin in this question a try or a prefix tree is a tree data structure used to efficiently store and retrieve keys in a data set of strings there are various applications of this data structure such as autocomplete and spell checker you want to implement the try class where try initializes the try object insert will take in a word and insert it into our data structure then search we'll go ahead and return true if this word is part of our try part of our data structure and starts with well again taking a prefix and return true if there is a previously inserted string word that has the prefix and false otherwise so what does this mean essentially so let's take a look maybe we have the following words so let's say we have the following words we have the word cats dog cat and then Dot try data structure might look something like this and if you kind of think about it we can represent this in terms of a tree and they actually want this to because it's a tree data structure and so maybe this over here this is like one node right maybe we can call this like a try node or something and so what do we notice well a try node has a value right you can see that all of these have values this value is a c this value is a d what else does it have well it has like children right it has like what it points to it has like its left child it has the right child but if you've got to think about it instead of just left and right we can have a maximum like 26 children right because there's 26 alphabets 26 letters in the alphabet so for example for cats over here you can see here we kind of have like a root which is like this node over here then we have C actually the root child which is a c here A C node and that has a child for a and then we go to a T and then we go to an S you can see similarly we also have catch right cat is just this and then c a t we also have dog and Dot notice that for dog and Dot after the O over here we actually have two children right we have one for the G and one for the T and so our insert function will essentially take in a word and insert it into our data structure here our search should somehow go through this tree and return true if we have a word right so maybe let's say I search for the word cat then I should actually return true here because cat is part of the word and then starts with it's basically just going to return true if there is a string that we can form in the try such that it matches the prefix so for example maybe I have just the prefix of D or maybe like d o you can see that we can form like a continuous string here and so we would return true in that case but for something like DOA well there's no a over here right there's no h out over here so we can't really form that so we'll return false there so there's many different ways to do this right there's one way in which like we actually create the individual nodes here so you would have like a actual class over here for the nodes and then the class would have like maybe something like um you know class like node and then the class would have like a value and like um you know like array of children so this is one away but this is actually not the way that I want to do this in Python it's actually it actually becomes very simple because if you think about it a node we can kind of represent this in terms of a dictionary right so what do I kind of mean by that well let's say over here like this initial root over here we can say root is just like an empty dictionary something like this right and let's say I want to insert the word cat okay so what would I do well this dictionary over here is going to essentially contain all of my children if you think of it that way so right now I have no children so right now I just have this one root here I have no children and then when I insert a c what am I going to have well when I insert a c then I can have something like this I can have that my dictionary becomes C and C in itself actually is its own dictionary so you can think of C in itself is something like this so maybe there's other Keys over here but C in itself is this entire thing here and so if you think about a c C Child is This one over here the a over here so really what this would kind of look like is if I go ahead and remove this it would kind of look something like this so we would have from the root we would have a child C and then C would also be a dictionary which has its own children here we have a children of a and then a is its own dictionary which has a child of T and then T is its own dictionary which has a child of s and then s actually doesn't have any children at all and so you can kind of think of it like this so we're doing the same thing but we're just representing it in terms of a dictionary we're not creating new nodes over here and so you can actually imagine here right so maybe instead of just the a you can see that the root here also has like a d right so here we would have like d also points to its own child over here and then D points like a o which points to a g and a t Etc so hopefully you're understanding the point here that I'm trying to make but essentially we can represent this in terms of a dictionary instead of a node and so doing that actually simplifies our approach quite a bit and so there's just two more questions to answer right how do I know whether I've whether I have like a word like I can search for a word and how do I know that I start with the word well let's start with the starts with first right so if I ask you like um you know do I have like maybe starts with c a well or maybe all I really need to do is like I just need to go through the string right and then I need to check okay does c exist Okay C does exist now I'm going to look for the a is there a inside the children of C yes there is so we can conclude that there this is a valid like prefix if there isn't if it was something like C and then D for example um or in this case like it wouldn't work right actually I realized I put D over here um so D should not be here so actually if I wish to kind of draw this entire thing again what it would kind of be like would C would point to a would point to T would point to S and all of these would have like their own children like this but in addition to this we would also have like d here and then D would point to O would point to G and then also point to T Etc so that's like another way this is the better way of representing it so basically if we're looking for something like c a i can check if like C A is a string and in this case I can see that it is so that answers that question the next question is and guess the final one is like how do we realize the search right like how do I know that a string exists inside of the search and I can't just follow the same approach here right because for example if you put like C A well C A definitely exists but the string doesn't end here right the string actually goes to cat and actually cats and so the way we want to do this is like we want one way to like figure out that you know this is like the end of a word right and really if you maybe think of it in terms of a node maybe we can have something like um end and then this would be like a Boolean right so this would either be like true and false indicating that at this node a string has completed and so we can actually do the same thing over here essentially what we could do is maybe every time a string completes we can add like end as true over here so end as true and so what this would kind of look like if you think about it is if we had this entire thing here so let's take a look if you have this entire thing here I'm going to skip over the D just look at the C and then just look at the A and then just look at the T So T will have its own children and then like you know there can be more things over here but as part of the children maybe we can have something like end and then we set it equal to true we know that the child will only be like one letter at a time right so we're completely allowed to add this but we can notice here that the cat over here if we have this scenario then this is a true case like this is um this is a case in which a word ends so let's take a look at how we can do this in the code to better understand and so it's actually completely very simple on how we do this especially in Python so let's take a look so the first thing we need is we need like our root right and I think I'll just call this children so I'll call these children and it needs to be a dictionary and I'm using self because I need to refer to it everywhere so first thing I can do for insert let's start off with insert I can do c is equal to self.children and then when I'm equal to self.children and then when I'm equal to self.children and then when I'm inserting what do I need to do with my word is something like bat for example then I need to go through each letter so for w in word then I need to essentially create like the nodes which in this case it's a dictionary right so I can actually check I can check that if W not in C then C at w is equal to an empty dictionary so all this is doing is that if like initially when we have an empty dictionary this one we can see that we don't have like a b here so we're going to create a child B and that will also have like its own children so what this is essentially doing is like from this node over here if you think about it from this node all it's doing is that it's creating like a b over here for the bat that's what it's doing and then what I'm doing so if this is not the case then what do I want to do well now I want to move forward right now I want to consider the a over here but in order for me to consider the a I need to essentially move like my C variable here into the B's children if you think about it right so I can do c is equal to C at w and so what this will essentially do is c will initially start off over here so this is like our pointer to the root and now my root pointer will be over here and so I can look inside of like these children to see if there's a A or whatever we can see in this case there's not going to be anything so this will continue to Loop and then at the very end what's going to happen at the very end we'll have our T and then C will be like T is child right so it would be something like this so have B and then we'll have an A over here and then we will have a t over here and now c will be on like these children which there are none right so c will be like this empty dictionary here so what I can do now is actually once it's complete I can do something like C at end is equal to true so all I'm doing here is I'm just saying that okay one of the children let me have the value here set to end and I'll just make it equal to true so that's all I'm doing over here okay so if you think of it in terms of that's all we really need to do here and then search becomes very easy because all you need to do in search is again we'll go through the children and so we'll go through the word itself and then if we can actually check this right so if we can check actually if W naught in C then automatically we can return first right because we know we're missing a letter but if it is then we're going to keep going till the end right and then what I want to do is I want to return end in c because if you think about it maybe I enter the word like ca right well C A definitely exists but you can see there isn't an end over here there isn't to end the end only exists as cat and cats and so that's why we have this scenario here and then the start to it is actually even easier than that all we have to do is again we'll look at the children and then again we'll go through the prefix and so I can actually again just check if W not in C then I know that this prefix is not valid right so then I can return false and then otherwise I will just Advance my pointer again and then in the end I can just return true right because I know that I haven't returned false so far so in the end I'm going to be on any one of the children I might be on the C I might be on the a I might be on the T or the S but I know that this is a valid prefix so this is all there is to this question and so if we go ahead and run it we can see that it works this is the O of n type algorithm where the insert and the read and the all of the operations are o of N and so you can think of this as like a very easy approach to solve this question thanks for watching | Implement Trie (Prefix Tree) | implement-trie-prefix-tree | A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
* `Trie()` Initializes the trie object.
* `void insert(String word)` Inserts the string `word` into the trie.
* `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise.
* `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise.
**Example 1:**
**Input**
\[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\]
\[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\]
**Output**
\[null, null, true, false, true, null, true\]
**Explanation**
Trie trie = new Trie();
trie.insert( "apple ");
trie.search( "apple "); // return True
trie.search( "app "); // return False
trie.startsWith( "app "); // return True
trie.insert( "app ");
trie.search( "app "); // return True
**Constraints:**
* `1 <= word.length, prefix.length <= 2000`
* `word` and `prefix` consist only of lowercase English letters.
* At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`. | null | Hash Table,String,Design,Trie | Medium | 211,642,648,676,1433,1949 |
397 | hello YouTube this is another Nikko problem for integer placement giving a positive integer starting from 1 to integer no max value you can the operation that follows if n is even replaced me in divided by 2 it is odd you can't replace n with either n plus 1 or M minus 1 so the max value of integer is odd if we add 1 there were both flow so we need to deal with that what is the minimum number of our placement and editor for and to become one okay for this problem when you see this kind of structure either or either these or either than you should think of TFS problem also you can use in dynamic programming either going to we just use DFS so here there is no kaneki need to tell me is because n is always positive so we just return the advice and here we run TSS so there is a logic if and encoding and we directly written the euro good for one it's the result also while there's no replacements needed if equal to 2 in this case agree written well we just the 2 divided by 2 that is 1 for others if in module 2 is 0 in this case we return 1 plus the SS in divide that you else we need to do is else easting else if n is odd number but if any in teacher taught max value in this case we could written just and we want the minimum number of replacements what do we need to do we could just either give it a manual and plasma either really or and just in / - or it's just really or and just in / - or it's just really or and just in / - or it's just an even number and no the maximum value and when we need to do it in one class math stopped me yes last a minus 1 y SS n plus 1 since that's it here this is the special Connell case we need to deal with because in his heart and in his a maximum value of integer if we ever there were just overflow so in that case we need to be there here you can just input DFS m minus 1 or n plus 1 this is a key and for the Loma odd number then we just my gfs in management EF at n plus 1 we just choose the minimal one so yeah miss Ronco suits me okay guys that worked you can also use dynamic programming that's basically mostly the same process let me know if you have a better solution thank you | Integer Replacement | integer-replacement | Given a positive integer `n`, you can apply one of the following operations:
1. If `n` is even, replace `n` with `n / 2`.
2. If `n` is odd, replace `n` with either `n + 1` or `n - 1`.
Return _the minimum number of operations needed for_ `n` _to become_ `1`.
**Example 1:**
**Input:** n = 8
**Output:** 3
**Explanation:** 8 -> 4 -> 2 -> 1
**Example 2:**
**Input:** n = 7
**Output:** 4
**Explanation:** 7 -> 8 -> 4 -> 2 -> 1
or 7 -> 6 -> 3 -> 2 -> 1
**Example 3:**
**Input:** n = 4
**Output:** 2
**Constraints:**
* `1 <= n <= 231 - 1` | null | Dynamic Programming,Greedy,Bit Manipulation,Memoization | Medium | null |
102 | okay hi guys today we are going to solve a very interesting problem from lead code it's a medium problem and the problem statement is binary tree level order traversal so let me go through the statement and then let's try to explain the problem to all of you so the problem statement is given the root of a binary tree written the level order traversal of its node value that is from left to right level by level so as all we know what is the level of the traversal but those guys who don't know about level order traversal let me explain the level of draw traversal is that we have to traverse the tree from the root by level and each level we have to print or give the output from left to right or in this case in level order 0 there is only one node so we give 3 then in level 2 there are two nodes 9 and 20 so we move left to right which is 1920 and again from level two there are two nodes 15 and 7 so we move from 15 and then seven so input is this and we have to give the output in a matrix and each row will correspond to each level so in this case the first row is 3 then second row is 9 20 third row is 15 7 okay so it's a very standard problem a very good problem so how to solve this problem so as we know we can do level of traversal on a tree using bfs what is bfs it is called breadth first search so one way to solve this problem is that we will start from root and we will use some data structure which is cube and we will put this node into our queue and then explore its children so it's children 9 and 20 then we will put it into the queue 1920 and we pop three and these in the order we push so this will work from left to right and we will put and this is the second first level right because 3 is level 0 so we will put into our matrix in another row and then we will check for children of 9 we will push and we will pop 9 from the queue and so forth and so on okay so let's try to also we have to keep track of the levels right yeah so that's why i'm popping all the node and we have to uh keep trace of the level which we are traversing or which we are exploring okay so let's try to solve this problem so let's say if the root is null right if this is the case then we will return nothing okay now we have to return a matrix so we will make a vector this is the output you can say also we required a queue it is of type tree node and let's call it nodes that we want to explore okay now nodes dot push will be the root so we are pushing our root into the queue and also we need another pointer let's call it front also we need another we have to track trace basically which level we are exploring so let's make a 1d vector and this is called level okay so what kind of variable and what kind of data structure needed we define and now let's try to solve this problem so we will like level i think uh why do we need a vector named level we need like for storing all the uh nodes in a particular level right yeah that's why okay so we will try to pop until the queue is empty right while exploring so we will say node dot empty now we will first try to what is the size of that node right okay now what is the typo size equals to the line 28 int size equals two nodes dot size in the line 28 yeah sorry yeah which is the size of the queue also we have to while we are pushing all the uh node we have to explore from backward right so let's say if i push 9920 so on the top of the queue this will be 20 but first while exploring the children of this level we have to explore nine so we have to reverse because uh in case of a queue we do first come first serve right yeah so we will pick that item the nine first now let's try to explore why are you doing this reverse uh because in this case let's say i push the children 1920 right so what is on our top 20 but when we are doing the bfs on the next level we have to explore the children of nine but it is on bottom right so we have to reverse that okay like uh you cannot pop from the front in c plus no uh so when i like uh suppose if i do it on java then i can like uh use the q data structure and i can pull the elements from the front actually we are going to use it so that's also same for c for what i am saying that so while exploring the children of theory right so which nine in twenty so first we push nine and then twenty so on the top yes which node is there it is twenty right and we stopped three in the beginning so now we have to explore the children of this level nodes so what are the nodes in this level it is nine and twenty so what we have to do from left to right so on the top is twenty so but we have to do to start from nine so we cannot access nine directly right so that's why i have to reverse the queue and that's the reason i mean yeah that's uh that's what i was saying like in java we can just uh take the element nine from the front okay i got your point okay so we here we pop the root right and now let's try to push back the value of its children into the vector right and therefore these are children in the left then we will also push into the queue and if there is a node in the right of the tree then we will also push into the queue so because we have to explore these nodes right so i think this is done also yeah we have to put the levels in our output yes yeah so this is all the notes in the given level and i'm just pushing into my vector of vector which is the matrix right and also i have to remove all the elements in the in that level now because i have to explore the another level and this will do all the job so what let me go uh do it through the code so it will first push three then q is not empty then this will define all these things it will reverse then it will push its children here into the queue and are in also into the level right because i have to okay so yes this will push 9 and 20 into the level and also into the queue because i have to now explore its children's level their children yes when it is done then i will push my level into the vector and then we will clear the level because now there is no need to three because we explore three then this will do for nine and this will do for twenty so there's no children of nine so this will do nothing here because here we are checking right and for 28 this will do and that will do the job well all the notes are explored because there is the empty condition in the end i will simply return my vector back to all the level let's try to in the line 41 semicolon uh let me try let me explore the code because this time i want to make it work | Binary Tree Level Order Traversal | binary-tree-level-order-traversal | Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[3\],\[9,20\],\[15,7\]\]
**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 | 103,107,111,314,637,764,1035 |
1,235 | hello guys welcome to algorithms made easy my name is richard and today we will be discussing the question maximum profit in job scheduling in this question we have n jobs where every job is scheduled to be done from start time to end time obtaining a profit now we are given the start and the end time and the profit in the arrays and we need to return the maximum profit that we can make such that no two job in the subset will overlap the time range now there is a condition given to us that if we choose a job that ends at time x we can start the another job that start at time so in the first example we can see that the first job ends at time three so we can start off the fourth job right at that point of time and so we are getting the maximum profit which is 120 and similarly in the rest of the examples so now let's see what the question is all about and what are the ways that we can use in order to solve this particular problem now this is the start and the profit arrays given to us in the first example and this is how the diagrammatically it will look like and as we know that the answer to this problem is we use these two particular jobs and we see that these two jobs do not overlap when the first job ends at three the next job starts at three the total profit in this case becomes 120 which is 50 plus 70. doing it manually is not a difficult task now we need to come up with an approach where we can solve this programmatically so let's see that we have two times given to us in this particular problem that is the start time and the end time and we can use either of the two in order to find out what will be the result so let's first discuss how we can solve this using the start time so suppose we have one job with us and then we have another job now these two jobs do not overlap and we can use both of these jobs in order to find out what will be the maximum profit so let's focus our attention only on the first job right now we can have two scenarios for any of the job present to us it can either be selected or it can either be rejected if the particular job is selected that means this job with the profit 50 is selected in that case the profit would become 50 plus the profit after or equals to the end time which is 3 in this case the rest of the profit after this end equals to 3 plus the current profit 50 would become the profit that we can get if we start at one and similarly if we do not select this particular job then the profit at this particular job would be equal to profit after one that means at least starting with time equals to 2 and that way we can find out the profit we will find out the maximum of all these profits for all the jobs and then we can return the maximum amount of these so if we write that down into a set of instructions we first sort the jobs with the start time because as we will be going sequentially from every job to the other job we would need the start time smallest to be processed earlier than the start time which is at the end of the job scheduling now for every job there are two scenarios either it is selected or it is rejected if it is selected the profit becomes profit of i plus next job after the end else the profit becomes next job after start plus one now the max of the two profits will become the profit starting with this particular job we can store that somewhere we will talk about how we can store it and everything and the third point is we find out the max of all the these jobs and return what will the maxim that we are getting so now let's turn our attention to how we can solve this using end time so in the case of end time we again have two jobs let's suppose that we have already computed the result for the first job and now we are on the second job this is just to make things easier and the second job in this case is either selected or not selected similar to what we did in the start time so if the job is selected then the profit becomes 40 plus the profit before or equals to 5 and if this job is not selected then the profit becomes profit before 10 because we are not selecting this job and any job ending at 9 can be used to compute the profit and if we write down into the statements it will still be the same things just change a little bit in the case of a selected and not selected in this particular video we would be looking at how we can solve this using end time you can always apply the same solution for the start time as well so let's start with the end time and this is the input that we had at the start now in this case the start and the end time both are sorted so we can call it as an special input but that won't be the case for other input there may be jumbled now that the end time is sorted we'll start off with the first job that we had with the start is one end is three and the profit is 50. now we are seeing that at time three what is the maximum profit that we can get so at time 3 if we select this particular job the maximum profit that we can get is 50 plus all the jobs ending at n equals to 0 or any job that is ending with n equals to 2 and we take the max of the two values so we see that we do need one value wherein we store that what is the maximum profit up till that particular time we will be storing the highest values in this map so at the end time 0 the profit will be 0 and in this case we find out that the profit 50 plus 0 becomes 50 and so at the end time 3 the maximum value or the maximum profit that we can get is 50 and we'll store that into this map that we have created now let's move to the second job in the second job we have the start is to end is 4 and the profit is 10 so we again search for the job which has a maximum profit which ends at most one so at most one up till that we have n time is zero and the profit is zero so zero plus ten the max profit till four becomes ten because we cannot use the job one in this case as these two are overlapping because the first job is not ending before 2. once we have that value that the profit is maximum equals to 10 at the time 4 we see that can we put that value into the map we cannot put this value into the map because there is a higher value residing in the map right now so the end time is 3 and the profit is 50 that will be the maximum value now let's move to the third job in this case the start is 3 and is 5 and the profit is 40 we try to find out any job that ends at 3 and we find out that the job exists which is 50 so we the maximum profit becomes in this case 50 plus 40 which is 90. so we do add that value into the map which is 5 comma 90. similarly we move to the last job and here we check any job that is ending at 3 we find out there is a job that ends at 3 which is 50 the maximum profit in this case become 120 which is higher than the last value present in this map or the highest value present in the map so we put this value 6 comma 120 and this value 6 comma 120 being the highest value in the map is the value that is the highest profit that we can make from this particular set of inputs when we apply this logic we will be able to figure out the result it will be much more clear when we code this particular approach so now it's time to code this so we'll first start off with creating the data out of the start time and profit so that we do have all the data in one space so the simplest method to use that data is to create a 2d array so there will be n elements where n will be start time dot length once we have that we can put all the data into this jobs 2d array now that our data is complete we had two approaches we can either go with the start time or the end time now in this case we will go with the end time so we need to sort this array based on end time so we'll use the inbuilt arrays dot sort for that sorting this jobs array we will be using a custom comparator and the second value of this array is the end time so we will sort according to that ascending order once the array is sorted we need to find out for every job if it is selected what is the maximum profit if it is not selected then what is the maximum profit so we need to store those values into somewhere so that we can use the previous value like we saw that we used a map and in this question we would need a map wherein we can find out the value which is less or equals to the particular start time so which map provides that functionality so tree map does gives us that functionality wherein we can find out the keys which are less than the particular key provided because 3 map as we all know has all its keys in sorted order searching any value in a key map takes log and time as it uses binary search internally so we would have a tree map and we know that at the n times zero the maximum profit that we can get is zero so that is the base value that we need to put in this map which is zero comma zero now for every job that we have we need to perform some functionality now herein we need to find out a value or the profit that we get now this value is if this particular job is selected then what will be the profit so the profit in this case would be as we all know the profit of this particular job and the maximum profit that we can get before the start of this particular job so we need to find out what is that value so we need to find out the key if existing in this particular dp map so we need to find out the highest value that is lower or equals to the given provided start time so to find out that value we have a method for that which is called floor entry so we will use that we provide the start time over here and we then get its value which is get value now as you know we need to put this val into our map only if it is a value greater than the existing value we have already sorted all the end times and now we are going in the sequential order so every key that we put into the map will be put in at the end of the map so if this current value is greater than that and value we need to put this new job end time with the profit into the map so we do a check over here if the well is greater than the dp dot last entry would get value now these are some of the methods that the tree map provides us by itself you can look them up and try to use them in your code it will really help you in speeding up your development once we have that we can put this value into the map at the end time so the job end and we put in the val into this particular position we saw that the last value is nothing but the highest value that we can get so this is the value so we can directly return dp.entry last entry dot get value return dp.entry last entry dot get value return dp.entry last entry dot get value and that will do the work for us so the coding part is done as we are using a tree map we need not to take care of all the searching and everything the tree map does provide that in built we are doing a sorting over here so that is n login and then we are using for n elements finding out the value is log n so that again becomes n log n so now let's try to run this code for all the sample test cases now let's run this so it runs successfully for all the sample test cases let's submit this so it got submitted successfully the time complexity in this case is n log n that we discussed well the space complexity is in because we're using a jobs array for that you can also solve this problem using start time the approach will remain pretty much the same do let us know your thoughts in the comments below thanks for watching this video see in the next one | Maximum Profit in Job Scheduling | maximum-profit-in-job-scheduling | We have `n` jobs, where every job is scheduled to be done from `startTime[i]` to `endTime[i]`, obtaining a profit of `profit[i]`.
You're given the `startTime`, `endTime` and `profit` arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.
If you choose a job that ends at time `X` you will be able to start another job that starts at time `X`.
**Example 1:**
**Input:** startTime = \[1,2,3,3\], endTime = \[3,4,5,6\], profit = \[50,10,40,70\]
**Output:** 120
**Explanation:** The subset chosen is the first and fourth job.
Time range \[1-3\]+\[3-6\] , we get profit of 120 = 50 + 70.
**Example 2:**
**Input:** startTime = \[1,2,3,4,6\], endTime = \[3,5,10,6,9\], profit = \[20,20,100,70,60\]
**Output:** 150
**Explanation:** The subset chosen is the first, fourth and fifth job.
Profit obtained 150 = 20 + 70 + 60.
**Example 3:**
**Input:** startTime = \[1,1,1\], endTime = \[2,3,4\], profit = \[5,6,4\]
**Output:** 6
**Constraints:**
* `1 <= startTime.length == endTime.length == profit.length <= 5 * 104`
* `1 <= startTime[i] < endTime[i] <= 109`
* `1 <= profit[i] <= 104` | null | null | Hard | null |
171 | hey guys welcome back to another video and today we're going to be solving the leakout question excel sheet column numbers so in this question we're given a column title as appeared in an excel sheet we respond its corresponding column number so what does this mean so let's say we're given the letter a and a corresponds to one and let's say we're given the letter z or z depending from where you're from uh we have uh the it corresponds to the number 26 and now let's say we have a right a is going to correspond to 26 plus one so then in this case we're going to have 27 and this is going to keep going until a b a c a d all the way up to a z and when we have a z we have a value of 26 multiplied by 2 which is 52 okay and then this is going to keep going so we could also have three uh digits sorry three letters so we could have a and a which is going to start off with the value of 53 and it's gonna keep going on right and so this is what we have to do and if you look at this we kind of have a pattern so when we have just one letter right when we have one space we have 26 possibilities that can go into that one space so now let's say we have two spaces right we so we have a space for two letters so in this case we have 26 possibilities to go over here and we also have 26 possibilities to go over here and to calculate what that is it's just going to be 26 multiplied by 26 which is nothing but 26 squared similarly just so you understand completely if we have three uh letters then each of the letter has a probability has 26 different options that could go inside of that so another way to say that is the base for this is 26 and we can use that knowledge in order to calculate the column number so let's just take a quick look at how that looks like okay so let's start off with uh the letter a right pretty simple and when we go to the first place so how are we going to calculate this so we have a multiplied by whatever the base is so in this case the base is 26 since there are 26 different possibilities and since it's only one letter right so for the when we're at the first unit or letter we're going to go do 26 to the power of zero and what is the value of a going to be here a is the first letter so it's gonna have a value of one so we're gonna do one multiplied by 26 to the power of zero which equals to 1 and if you look over here that's our answer okay so now if we go to b it's going to be the same thing but instead of a value of a1 so let's say this was b over here and so value of 1 this would have a value of 2 right so all right so let's now take a look at a two letter excel uh column number a and b okay and so that's pretty simple and we're going to start off with the first letter so that's going to be b multiplied by 26 to the power of zero now we're going to go to the next letter which is a and we can add that so a multiplied by 26 now we're gonna increase the power by one so 26 to the power of one so in this case b is going to be nothing else but 2 so 2 multiplied by 1 is 1 and plus 1 multiplied by 26 is 26 and this equals to 27. so i'm pretty sure you get it but let's just do one final example so let's say we have b z and c in this case it's going to be c multiplied by 26 to the power of zero plus z multiplied by 26 to the power of one plus b multiplied by 26 to the power of two and when you uh subtract when you solve that you should get the answer so i think it's pretty simple so now let's just look at how the code for this looks like so before we get into a code i just want to show you a quick thing so in order to write this we should understand what the ord function does and all it does is you give it a letter right in this case we're going to give it a capital a and it's going to give you the ascii value of that letter so in this case i'm pretty sure capital a has an ascii value of 65 but in our question we wanted uh so for example for a we wanted one since it was the first letter for b we wanted two and so on and so forth let's see how we can do that so let's say for example let's say we look at capital d right so we have capital d here and has a value of 68. so what we're going to do over here is we're going to take whatever letter we want so let's say we want to find the value of a capital d we're going to subtract that with a capital a so capital a since that's our first letter okay there we go so in this case we get three but d is the fourth letter a b c and d so what we're going to do is we're going to do that and we're going to add one to it so this is what we're going to be using to find the value or the place of our letter and the fact that all of our letters are capital and they're the same case uh makes this a lot easier okay so now let's go to our lead code so we're going to start off by initializing a variable called results and uh in the beginning it's just going to have a value of 0. and this is what we're going to return in the ending okay so now we're going to iterate through each of our characters so for characters in s and first what we need to do is we need to find the ascii value for it so in order to do that we're going to find do the same thing so when you first find the ascii value of our character subtract that with the ascii value of capital a and then add one so we got our ascii value and let's just save it in the variable x and after we do that we're going to add this to our results so our result is going to be results multiplied by 26 since 26 is our base and over here we're going to add this variable over here so plus x okay and that should be it and we go outside of our for loop and over here we return our result sorry return okay so let's submit our solution and as you can see our solution to get accepted and finally do let me know what you thought about the video and don't forget to like and subscribe if this video helped you thank you | Excel Sheet Column Number | excel-sheet-column-number | Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
**Example 1:**
**Input:** columnTitle = "A "
**Output:** 1
**Example 2:**
**Input:** columnTitle = "AB "
**Output:** 28
**Example 3:**
**Input:** columnTitle = "ZY "
**Output:** 701
**Constraints:**
* `1 <= columnTitle.length <= 7`
* `columnTitle` consists only of uppercase English letters.
* `columnTitle` is in the range `[ "A ", "FXSHRXW "]`. | null | Math,String | Easy | 168,2304 |
171 | hello guys my name is Ursula and welcome back to my channel and today we are going to solve a new lead code portion that is Excel sheet column number so question C is given a string column title that represent the column title sap as it appears in an Excel sheet written its corresponding volume number so we have to written the column number its corresponding value here and we will be solving this question with the help of JavaScript so just before starting solving this question guys 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 if you see here column if column is equals to A we will return one so and if you do the coil number A B we will be returning 28 and z y will return x701 so how we are going to approach how we are getting such values so let me explain it to you with an example here if a we say a 0 into 26 Plus C5 Plus 1. okay so how we are getting one where zero that will also I will explain it to you then B is this whole sum multiplied by 26 plus 2 then how we are getting 2 that will also explain it to you and now c will be if I take an example ABC later mentioned oh we have a column number ABC and if we take an example we see so this whole some Builder was 28 and 28 into 26 plus 3. now we are getting three let me also explain it to you so let us understand so these are all asai values so how we are approaching this the ACI values I will explain it to you so asei numbers ACI and if I go and scroll down here something images we can check and explain it to you what they are um yeah so here I have got something here oh see there it's starting for 60 from 64. so 64 understand it as a zero and this is 65 a b c d so it's starting from 65 to uh 90 so 60 from 90 we are getting all characters here for column number if we talk about so if you want the number value how we will get we will minus 65 minus 64 will give us 1 60 if uh six square minus 64 give us 267 minus 64 will give us three so if you want a value of C we will subtract these two numbers which two numbers we will subset 67 minus 64 will give us c 66 minus 64 give us B 65 minus 65 plus 65 minus 64 value was a so this is how we are getting so let's write instead of one let's write it 65 minus 64. and instead of this 2 here instead write 66 minus 64. and here also instead of 3 let's write 67 minus 64. so that's make more sense and it's more logical to write these things here now let's start solving first of all I will create a variable let's function the sum is equals to 0 which is my integer and I will create a count here for let in which I will first of all I will putting a variable let I is equals to 0 and I is less than column CEO and column dot length I plus now I will say that sum is equals to means this whole thing is equal to where is it's our initial value we have to return this also so let's return this also return some what in the loop Y what we will be doing here is we will just writing this whole thing into a formula so since this is starting from 0 as well so instead of uh 0 we can write some into because this is all wholesome so in 26 Plus and we will say column title Dot care code it at will give us what will give us the ACI value of that particular number so for that and minus 64. so this will give us ACI value of any particular ith character like a it will give one 65 it will give us 65 which will give us 1 at the end ultimately so let's band it and check for an answer so we have got our answer here this was all in the question guys hope you have understood this question and if you have any doubt ask in the comment section and we have done this with the help JavaScript thank you guys for watching the video see you next time | Excel Sheet Column Number | excel-sheet-column-number | Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
**Example 1:**
**Input:** columnTitle = "A "
**Output:** 1
**Example 2:**
**Input:** columnTitle = "AB "
**Output:** 28
**Example 3:**
**Input:** columnTitle = "ZY "
**Output:** 701
**Constraints:**
* `1 <= columnTitle.length <= 7`
* `columnTitle` consists only of uppercase English letters.
* `columnTitle` is in the range `[ "A ", "FXSHRXW "]`. | null | Math,String | Easy | 168,2304 |
3 | in this video I want to really explain the sliding window algorithm so let's take a look we're given a string s and we want to find the length of the longest substring without any repeating characters so let's set both L and R to be the beginning marking that our window is just the a to easily keep track of the characters we have in the window we will use a hash set for now just the letter of a so our window is valid so we want to move it forward which means moving R to the right so now is this in our set well it's not in our set so we can add it but it gets interesting here as we try to move R forward and add this to the window this current character is in our set so we need to move L forward removing its character from the set until it's valid again move this window forward we do that with b and we kick it out of the set and so we do it one more time and then now this window is valid again and we can put C back into this set and keep the algorithm going until R is at the end of the string here is some example code in Python feel free to screenshot this for later | Longest Substring Without Repeating Characters | longest-substring-without-repeating-characters | Given a string `s`, find the length of the **longest** **substring** without repeating characters.
**Example 1:**
**Input:** s = "abcabcbb "
**Output:** 3
**Explanation:** The answer is "abc ", with the length of 3.
**Example 2:**
**Input:** s = "bbbbb "
**Output:** 1
**Explanation:** The answer is "b ", with the length of 1.
**Example 3:**
**Input:** s = "pwwkew "
**Output:** 3
**Explanation:** The answer is "wke ", with the length of 3.
Notice that the answer must be a substring, "pwke " is a subsequence and not a substring.
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of English letters, digits, symbols and spaces. | null | Hash Table,String,Sliding Window | Medium | 159,340,1034,1813,2209 |
1,003 | hey everybody this is Larry I hit the like button hit the subscribe button let me know how you're doing this problem I'm gonna stop alive right about now alright when does it end we check if word is valid after substitutions but giving the string ABC is valid for any valid string read we may split we in the two pieces x and y such that X plus y X concatenated with Y is equal to me X or Y may be empty then X plus ABC plus y is also well there's a lot I don't manage to die from reading it but for example of s is ABC then string by Australians ABC two pieces wait let me read this again this doesn't know but this is a mouthful we may split V into two pieces such that okay so it is just then okay so it's like a word wrapping itself kind of can you do that infinite amount of time why is that to so many yeah okay I guess you get to kind of recursively on the definition of exclusive just try to understanding that is hard okay start the by string ABC then we insert other ABC between a bazooka hmm that is an interesting problem oh wait are these always ABC and ABC is the only valid string okay I did I think my prom with some of these LICO proms is that I always miss that part where that some stuff is a constant way or like their constraints in a constant way and I sometimes miss tie-dyed oh like cheddar Eisen in my tie-dyed oh like cheddar Eisen in my tie-dyed oh like cheddar Eisen in my head before I realize okay I'm gonna send and it's 20,000 so that means n send and it's 20,000 so that means n send and it's 20,000 so that means n square algorism I have a the naive algorithm would be a and square I think they are drying falgot Meza and square can I look how can I do better no it's just one I'm having the greedy is always just get ABC and remove them and then kind of see what happens but that means we remove one at a time like in the case where then it's going to end square ice and truce - ish well to end square ice and truce - ish well to end square ice and truce - ish well that's clearly too slow how can I do this faster the force is actually more interesting maybe so only way it could be force is if the running count of a b and c is not in worded order I don't know that's an easy way to figure out like how I got this is a guess on my part to be honest I don't know bit of a hunch but I really don't know if that's expected solution that's like how I don't know how you were able to kind of figure that out on the spot but basically my idea here and looking at the true I didn't really get a sense but again the floors I'm trying to confine like the in worst case of where as false and I feel like the case technically force is as if they're more C's that are happening before s and then kind of like in that way this can only be force if for a given prefix of the string they're more C's than B's or AIDS or more ABS than days because in that case them is no matter what they'll always be a C before one of the B's and A's I think that's probably how I would think about it I think you have and there's the show check that a B and C at the end it's the same so yeah let's do that mmm we're giving us hot Kody on this actually you see okay now if I guess I could write a loop that this is just three statements oops what was best enough time right but now let's test more cases Oh - there's another case where that's not - there's another case where that's not - there's another case where that's not true okay it's because ABC to start up here in this or but even if so now I'm thinking about this case where and I guess that's why this one has done with so many downloads where even if you have someone like this it still he goes to force so we have to think about that case so what is how do I deal with this it's not strange it makes sense that because ABC is not in it but in this case ABC is in it and we stir for so what's our easy way to be so hmm I say so every time you see a C it has to close out an A and a B immediately because like here hmm we'll have someone like this well no that's how that's a good train to write mommy it's missing a sea no but I mean I guess I said it that way but this is also already is imprisoned in this so I'm not saying anything new because you can also like from just probably you could just decrement all of them once you get a count oh I see how do I handle this case maybe CC is in a way that is like more natural so we just swap this is accurate this is good right and just right now I don't need to anything that uh mmm do I have to be linear time where credit is in blood so I had not get in time because that's only other time that would fit and then what albums are there for that I do something like this that we also still not be good the NPP sees me telling such a weird one hmm when you step off my plane juice yeah okay but it's still gonna be in season okay so we don't mean it this time we definitely need this but there's one more property that at least one more property that we're not checking I'm also trying to do it obviously without actually simulating it because n is your 20 case that's probably gonna be too slow well next is not true well it's ABC it's not in a pit you know the other ways Arendt squares that is stuff that requires you to like remove stuff or and square yeah okay well my friend I think this actually now we might smell a little bit of was it theory of computation or whatever class we're okay I mean you just use stack noka there now whenever you got a see you want to be able to pop off being a explicitly of the first two okay let's do it our let's give it a try this will be confusing to me it's Dustin to the Typhoon's yes okay non stop pop and stack that pop now start up and see and then we just have to return the link of stack as you go sumo for empty matching hmm and also let's put this in there no car oh okay yeah my hmm to be honest this is wonder one of those times where I just didn't have all right I just didn't have a great intuition about it to be honest and I think in my mind I was how long did I know spending on this 17 minutes I think I got two so one thing that I do when I stuck when I get stuck is that I will in my mind in numerate its kind of different type of algorithms and think about like hey if I use this does this work in this case that's right there yeah I guess a little bit about stone stacks but I think when I kind of describe the properties of this problem more and I guess in a way excuse me in a way the way that I was doing it before it accounting it's a little bit more like a queue where now it's more like a stack well it is a stack and I think the one wrong answer which is the abbc see let me kind of clarify that and down like thing I was trying to and having done one was this where this is force and this is true I was just trying to figure out how to differentiate between the two and stack was what I came up with in that yeah you know that you have to remove like the sub strain of ABCs and then yeah and then you kind of do it recursively in that way and I think I was kind of thinking about it in terms of when I keep on saying and square I was thinking about the stack in a way except for that was the recursive in implicit stack and also not optimal because you're trying a lot of unnecessary possibilities and here was kind of when and I have a linear time and linear space where when and I could do this in a greedy way I see ABC I just you know we move it and other properties that I was talking about where like if I see SC I want I need a sand bees to match and this is given more specific subset on that yeah oh well okay a cool problem I don't know it was okay I mean I actually don't think it's worth to down well there may be on the contest there's some issues as I'm going but uh yeah that's why I have a this one | Check If Word Is Valid After Substitutions | minimum-area-rectangle-ii | Given a string `s`, determine if it is **valid**.
A string `s` is **valid** if, starting with an empty string `t = " "`, you can **transform** `t` **into** `s` after performing the following operation **any number of times**:
* Insert string `"abc "` into any position in `t`. More formally, `t` becomes `tleft + "abc " + tright`, where `t == tleft + tright`. Note that `tleft` and `tright` may be **empty**.
Return `true` _if_ `s` _is a **valid** string, otherwise, return_ `false`.
**Example 1:**
**Input:** s = "aabcbc "
**Output:** true
**Explanation:**
" " -> "abc " -> "aabcbc "
Thus, "aabcbc " is valid.
**Example 2:**
**Input:** s = "abcabcababcc "
**Output:** true
**Explanation:**
" " -> "abc " -> "abcabc " -> "abcabcabc " -> "abcabcababcc "
Thus, "abcabcababcc " is valid.
**Example 3:**
**Input:** s = "abccba "
**Output:** false
**Explanation:** It is impossible to get "abccba " using the operation.
**Constraints:**
* `1 <= s.length <= 2 * 104`
* `s` consists of letters `'a'`, `'b'`, and `'c'` | null | Array,Math,Geometry | Medium | null |
117 | hello everyone so today we are going to do lead good daily challenge populating next right pointers in each node so here we are given with a tree and we are required to do something like this which if we get to our first level node means a node which is at the first level then we are simply we need to do is we need to insert a null and simply point that particular node towards null because we are populating the right pointers of each level of our two so in that sense we are doing like this so then when we reach at next level then two and three are there at the level so we need to think that first node which is s then we need to populate this first node or second level and its right pointer we are required to populate so when right pointer is there for this particular civil simply populate it with the three means our right point will be pointing towards this and then our three right pointer will be simply pointing towards null basically not the right pointer as the question is mentioning it's simply required to populate the next pointer this is the one which is in the structure of the tree because the right pointer of root would be 3 and the right pointer of 2 would be 5 right control 3 would be 7 right but we are required to populate the next pointer so 1 to null this is the next pointer which is being populated then two to three this is the next pointer which is being populated with three and three's next pointer is being populated with none then we are killed with four then fourth next would be five and five next would be 7 and 7's next would be null so like this we are required to simply populate the next pointer of each node towards the right but the thing is that how we are required to do all this thing in front of a question we can see that it's all about doing level by level right so from this like even if i say you that we can go towards this depth and do these things then it would be much costly for us to do so it's better to do it level by level only means when we are having uh okay before that let me also the constraints are simply that number of nodes would be still six thousand right but as it is a binary tree so these things six thousand would be divided also even if it is a few three then also at next six thousand and null towards each next pointer that also works fine as even if we do a nice manner and then the values of the nodes here the values of nodes are like um not much taken into consideration not much valuable for the question so now comes the part that how we are required to do this question so we're doing this question the thing is that we are simply required to populate the next pointer with null or the next node which we are having right so for doing that thing what we would be doing we will do a level or traversal and push each level nodes which are being there into the cube means level one then level two then level three so all the nodes which are being there at each level we would be pushing all those nodes into the queue right first thing we are required to do this now this levels nodes are being pushed then we will simply push null to it because at the end we are required to populate it with null also right so whenever all the nodes of this particular level are being pushed into the queue and we are also required to push null into this particular cube and also one thing is that we are also required to simply connect all these right so connecting all these means while we would be pushing all these into the queue in mean time only when we are having that current node with us what we'll do current next equals to whatever we are having in the front means if our current node is 2 then we will simply connect this 2 with 3 this we are required to do and then we'll at the end when we see that yeah now we don't have anything into the queue or if we are having but our last note has been pushed into the queue then we will simply push null to that and then we'll again do this particular right so we would be doing this question like this so yeah somehow i have quality to the intuition that how i would be required to do this question now comes the next part about the time complexity and space complexity so time complexity would be in our order of height only where height could be from log n when it is a density populated and it would be log in and if it is a skew tree then it would be n so we could say the time complexity would be simply order of n and a space complexity because we are using q and x max if it is a skew tree right if a tree is something like this so all of them would be required to be pushed into the queue right so that's why space complexity will be order of n again so like this we are required to do this question now let me walk you through the code of this question the coding part so here is what i the way i was explaining let me split this particular code into parts and explain you now punch the pad doing dss right so for bff we are required with this queue that i am having now first thing which we are required to check is that is our 3 mp or it is there so this is the basic if it is if root is not present that is if root equal equals to null then we are required to return nuls at that point only else we will simply push that root in the queue and also push the null because this particular first node it won't be having any other node with it right so with that only then simply push the null also right away so now comes the part of doing dss here so how we are doing dss here is that will check that if uh that means this is a standard bss only that if per q is not empty then we are do processing the nodes so we'll first take the first node from the queue pop it from the queue and now we'll start processing this node now we will check that if it is not null that is uh it is our root node itself or it is another node which we have pushed whichever node it is there will check that if it is not done so yeah a root no display which is not net so this thing we are required to do the thing which i was saying that while processing that node we will simply connect the next pointer of that current node with the one which is there at the front of a cube so this is what we would be doing and then if our current node do have a left node and also do have a right node means if it is having a left node then we'll simply push our current nodes left into the queue if it is having a right node then you will simply push a current node right into the queue so like this at this point one was simply popped out from the queue and now our cube would be having null with it right and also as it was having also it is now being connected because of this particular line it has been connected and also as other node was being processed so now our cube would be having null it would be having null and then it would be having 2 and 3 because these are the left and right nodes of our one so this is how our second level would be being pushed to the queue now connect the part means after this particular position it will be this point has been done right now it will check uh so now while loop would be there and looks like that is my q empty or not so yeah it is not empty so it will check for the current node now the current node would be simply equal to null because one was popped from the queue and now knowledge there so now null would be there now would be pass now it will check that is my current node is now not so yeah it is null so yes it is null and then our current node is being null then at that point one thing is there means while this while doing this question i just note test that uh because of this thing only we are able to push the null into it so when our current node is null right until that point all the nodes which were being there in the left in that level means the next level would have been pushed there so because of that thing only we are able to check that if i said no this null right and also our q is not empty because the null is staged for current element and at that moment current left and right would have been already pushed that doesn't mean which i was saying thus we are required to push null for those also because that level is filled so we are required to now push null for this two and three so at that point so this particular point our q would be having two three and null so this would be the thing now our one level has been completed so again this while loop will go ahead and now at current node won't be null because now our current node would be having two as its value so now two other two children would be pushed into it right and then 2 is being popped then 3 would be our current note right so three children would be pushed into this particular and they tell them means when 2 would be done 3 would be done then this null would be again encountered but when this null would be again encountered till then the level third would be completely filled into a queue and we could easily then push null to it so this is how this question is eligible to push a null at each level because the bfs is being done in such a manner that whenever there is a node having some value other than null then surely we are required to push all the children of that node but if our present note is having null value so till then our next level nodes have been completely filled at that moment so we are required to push null for that particular level so this is how this question is being done with uh populating our left right side next point of within null and this uh this is all about this question if there's any doubt or anything we could simply comment that down and this was all for it so yeah thank you | Populating Next Right Pointers in Each Node II | populating-next-right-pointers-in-each-node-ii | Given a binary tree
struct Node {
int val;
Node \*left;
Node \*right;
Node \*next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.
Initially, all next pointers are set to `NULL`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** \[1,#,2,3,#,4,5,7,#\]
**Explanation:** Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 6000]`.
* `-100 <= Node.val <= 100`
**Follow-up:**
* You may only use constant extra space.
* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem. | null | Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | 116 |
1,780 | hello guys welcome to another video in the series of coding or today we have with us a problem that is called check if number is a sum of powers of three so we are given an integer n and we have to return truth it is possible to represent n as the sum of distinct powers of three otherwise you have to return false so when integer y is a power of three if there exists an integer x such that y equal to three power x so let's try to understand this so to understand and appreciate this let's just quickly look at an example of binary representation so that we can solve this problem so suppose we have to convert the number to l to binary representation how do we do that it's very simple right so first we make some dashes so what do the 3 present these represent the weights 2 power 0 2 power 1 2 power 2 and 2 power 3 so what do i mean by this so let me also write to power 4 okay so 2 power 0 is 1 2 power 1 is 2 power 2 is 4 2 power 3 is 8 2 power 4 is 16 right so i have these weights and using these weights i have to try to make the number 12 how can i do that right so what can i do i can pick up 8 so i pick up 8 that means i put 1 here then i pick up 4 so i put another 1 here so when i pick up 8 so what i do is first time i picked up 8 i had to make 12 so when i picked up 8 i made the sum from 12 to 4 because now i have to make only 4 i have picked up 8 means i have made it i have to just make 4 so now next time when i'm making 4 i do 4 minus 4 and that gives 0 so now i have to make no more and finally i get 0 that means i made whatever number i wanted to make so i put 0 for the remaining so this is the binary representation and it is made up of these quantities right so 12 is nothing but 8 plus 4 or 12 is nothing but 2 power 3 plus 2 power 2 so this is a binary representation right let's take another example to appreciate it okay so if i have to make some number like say 7 how do i do that so again 2 power 0 2 power 1 2 power 2 let me write okay so 2 power 0 is 1 2 power 1 s 2 power with 4 to power 3 is 8 so what i do i have to just pick up weights right so now 8 is greater than 7 so i need not consider these because from 8 how can i make 7 so i need to make 7 so i'll make it up by sum of smaller numbers only so i take the biggest number 4 so 7 minus 4 is 3 so first i pick up 4 that means now i have picked up 4 okay and now only 3 is yet to be made so how can i make 3 so i pick up the next bigger number 2 3 minus 2 is 1 so i write 1 here then i still have to make 1 so i pick up the next biggest number 1 minus 1 is 0 so i make 0 so that means i have made the possible sum that i wanted to make and i write 1 here so i have made up 7 using 4 plus 2 plus 1 so i made up 7 using basically just 2 power 2 plus 2 power 1 plus 2 power 0 okay so this is binary representation why did this is because it's going to help us solve this problem so similarly uh we can you know we have to just represent in the base system of three in place of two now okay we have to just do the same thing okay let's consider this example it says we have to make 12 but now instead of weights of powers of two we have powers of three so this is what is the question so let me write the same thing so 3 power 0 is 1 3 power 1 is 3 power 2 is 9 3 power 3 is 27 okay so now let me start picking up weights 27 is greater than 12 so let me ignore that so i will start picking up weights from 9 so i pick up weights from 9 okay so now i subtract 9 from 12 because i took 9 from the sum now my sum is just 3 i have to just make 3 more so how can i make 3 more i try to pick up the next weight so i have 3 minus 3 and it gives 0 right so i have already made 0 so i need not use other numbers so 12 is basically just 3 power 2 plus 3 9 plus 3 is 12 so uh i can make 12 right because in the end i got this quantity as 0 okay let's take some example uh where maybe we cannot make okay let's consider some example like 17 so if it is 17 again we try to you know take this example i write the weights 3 power 0 3 power 1 3 power 2 3 power 3 so 3 power 0 is 1 3 power 1 is 3 power 2 is 9 3 power 3 is 27 and i try to pick up weights so say i need not take 27 because 27 is larger than 17 let me take 9 okay i take 9 so now what is the remaining number that i have to make from 17 i've already made 9 my sum is now 8 so i have to make 8 let me see if i can make 8 okay i've already picked up 9 so let me pick the next number so 8 minus 3 is 5. so i have used this 3 also ok now next i can use the next number so 5 minus 1 is 4 now i am still short of 4 i have used up all the numbers but i still couldn't make because my final answer is not 0 because 4 is still remaining right so what i have done i have tried to make 17 using 9 plus 3 plus 1 i've tried to use all the weights that i have but the weights that i have are not able to give me 17. i am still falling short by 4 right so if this had been 0 if final crap in 0 means i would have been able to make the number 9 plus 3 is 12 10 plus 1 is 13 i am not able to make 17 so this is uh what it is okay and let me just consider one last example before going to the code so let me try to make 30 okay so how can i make 30 let me just write 3 power 0 3 power 1 3 power 2 3 power 3 okay 3 power 4 will exceed 3 power 4 is 81 so that will exceed let me write all other powers so i need not use this because uh 81 is larger than 30 i have to make 30 right so i pick up the uh largest weight so 30 minus 27 is 30 okay so i have used up 27 and now i have to make only three right so now i go to the next number so next number which is in line such that i can make 3 i have to just make 3 so i need not take 9 because if i take 9 i will get negative number right so i will take 3 only i will take a number which is smaller than the sum so now sum is 3 i have to make 3 minus 3 is 0 so i finally reach 0 that means i have used so if it was the 3 system this would have been the representation if it was the base system of 3 this would have been the representation just like we write binary and we have just used these two quantities so 30 is just 27 plus 3 so 30 is just 3 power 3 plus 3 power 1 so i have been successfully been able to make 30 because finally i am getting 0 that means i have consumed the weights required to make the number which i wanted to make so now let me write the code of this the code of it is should be simple because if you have understood logic it's a three line code so if n is less than equal to 10 power 7 is given so what we will do so we cannot have a number which is greater than 10 power 7 so what we will do we will take power of 3 which is smaller than this particular quantity because you need to subtract the powers of 3 from this number n so we will take the power of 3 which is just closest to this but smaller than this so we will start from that so that is 14 so 10 3 power 14 will be your just closest to this 10 power 7 so i will start from 14 so for in i equal to 14 i greater than equal to 0 i minus okay so basically i is just the powers that i am going to take so it will be clear once i write this okay so let me write number so into number is equal to power of 3 power i so power of 3 comma i just gives 3 power i okay so in this case when we consider 30 so we are just you know initially what we will do is we are starting from i equal to 14 but uh those quantities will anyway be larger right so we will start from 3 power 3 only in this case so i will be 3 first i will be 3 so you will get 3 power or 3 okay which is 27 now what you have to do is you have to subtract 27 from n okay so if n minus x is greater than equal to 0 that means if you are successfully able to subtract so i mean number n minus number so if you are successfully able to subtract this number from our n okay if n minus number is greater than equal to 0 for example in this case when i becomes equal to 3 then you will be able to subtract 27 from 30 if n is 30 minus 27 will be equal to uh 3 right so you will be able to subtract so this is n this is a n or o or which is number n minus number okay and if that is so fine then what you lose n minus equal to number so what i'm doing then i'm subtracting it so now my number which was 30 now number becomes 30 minus 27 right so my number becomes 3 because i have already made 27 successfully from 30 was the number that i wanted to make 30 was n 30 was the sum that i wanted to make so from 30 i subtracted 27 i need to make only three so i reduced my number by okay so i reduce my n by number so this variable is confusing but uh i hope that logic is clear so ah this becomes equal to 3 so now my n has taken the value of 3 okay now if any time n becomes equal to 0 right so next time what will happen is next time in this iteration i will become equal to 2 okay when i becomes equal to 2 so let me write i becomes equal to 2 so 3 power 2 is 9 so now n is 3 when we check 3 minus 9 okay that will be a negative number so this if n minus number greater than equal to zero condition will not be satisfied so we will just go to the next iteration so in the next iteration uh i will become equal to 1 so 3 power 1 is 3 then 3 minus 3 is equal to 0 so now we have given this condition n minus number greater than equal to 0. so this condition will be satisfied so n will become equal to 0 so n becomes equal to 0 right so now if n is 0 we can return true that means we have successfully been able to make the number otherwise at last we can return false okay and now i took the example by starting from 3 power 3 but what it will do is it will start from 3 power 14 because i just explained that we have to take n less than equal to 10 power 7 so that is the maximum case that they can give us so what will happen even if your n is 30 okay when we start from 3 power 14 when we try to subtract okay when we try to subtract 3 power 14 okay so and number is 3 power 14 n is 30 so 30 minus um let's say 3 power 14 that will be a negative quantity it will be large negative quantity so we need not worry n will just remain as n and it will keep iterating it will keep decrementing i okay so this will become 13 this will become 12 and so on unless we reach uh 3 power 3 okay when once we reach this then um so 3 power 3 is 27 30 minus 27 is uh greater than equal to 0 so then we n will uh subtract and we will get the iteration that we just saw so i hope that this was helpful let me just run and see if it is accepted so it is fine for this let me just submit and see if it is accepted so it's an accepted solution that's it thank you for being patient and listening | Check if Number is a Sum of Powers of Three | lowest-common-ancestor-of-a-binary-tree-ii | Given an integer `n`, return `true` _if it is possible to represent_ `n` _as the sum of distinct powers of three._ Otherwise, return `false`.
An integer `y` is a power of three if there exists an integer `x` such that `y == 3x`.
**Example 1:**
**Input:** n = 12
**Output:** true
**Explanation:** 12 = 31 + 32
**Example 2:**
**Input:** n = 91
**Output:** true
**Explanation:** 91 = 30 + 32 + 34
**Example 3:**
**Input:** n = 21
**Output:** false
**Constraints:**
* `1 <= n <= 107` | Traverse the graph visiting root, left, root, right, root to make an Euler Path Return the node (LCA) that is at the lowest depth between p and q in the Euler Path | Tree,Depth-First Search,Binary Tree | Medium | 235,236,1790,1816 |
70 | hello everyone I'm going to be showing you guys how to do 70 climbing stairs and it's ranked easy for elite code so it says you're climbing a staircase it takes n-steps to reach the top each it takes n-steps to reach the top each it takes n-steps to reach the top each time you can either climb one or two steps and how many distinct ways can you climb to the top so it's just checking the possibilities of uh how many times you can climb to the top and you have one or two steps uh for the first example there's two steps so the output is two because there are only two ways to climb to the top it's either one step plus one step or two steps but you should also recognize example two n equals three the output is three the explanation is that there are three ways to come to the top so it literally takes every uh way to climb to the top so One Stop Plus One Stop plus one stop plus two step and two steps plus one step so we gotta keep that in mind first you can set two variables so step two variables you can set it to you let's name it one two and we'll do one okay so you wanna Loop through n minus one all right so you want to set one equals to one plus two and then two equal to one but if you think about line seven two equal to one doesn't make sense because uh will equal it to one plus two we don't want to do that we just want it to equal to the value of one right here so what you can do before uh one equals one plus two you can do uh temp equals to one so temporary value and equal to equals itself so one plus two and then one uh the value of 2 will be one because we made a new variable right here so making a new variable and iterating through n minus one Okay so we have this down now we want to make sure we return it on the outside so we return one and this should give you the value yep there you go and I hope this makes sense to y'all have a great day thank you | 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 |
735 | We have to do that so we will see later how it comes in this type of picture first let's understand so what is given here is where life is asteroids of wait representing asteroid in ours okay so we have the ering of an asteroid asteroids Richter absolute value represented size on Ka, so whatever the error image is, it tells the size of the asteroids, like here we have 510 and -5, so if 5 is 5 here we have 510 and -5, so if 5 is 5 here we have 510 and -5, so if 5 is 5 and if 10 is OK, then the size of the rate of 5x is suggested. If it is then it will be bigger than 10 Okay so this is tells our size of D story Okay so D sign in represents its direction So positive meaning right and negative meaning left Okay so if this five and this 10 if positive AIDS means this what does this mean You are going to the right, okay like moving right and if this is minus five here we can see -5 then what will be its size, what will have to be done can see -5 then what will be its size, what will have to be done can see -5 then what will be its size, what will have to be done but it will go to the left because its sign is negative here okay so I just steroid move. Coming at speed from D, what does it mean that these two asteroids which are five and 10 are going at speed from this, if they are going in the same direction then they will never collide but if they are going in a different direction then it means collision okay so Find out d state of d asteroid after which colleges so what we have to do in the last return is to direct an output in which what is the state of the asteroid we have to give that means asteroid concept children that is what we have to return here and if collide ok if If they are over then it will not remain here OK so here what we have given is that IF tu asteroid made d smaller one will collide OK so 10 and -5 collide OK so 10 and -5 collide OK so 10 and -5 will collide here right so what is given here that the smaller one is that Will be explored means mines five bill explode and these both are R of D size both bill explore like here fiber is -5 so 5 and -5 if here fiber is -5 so 5 and -5 if here fiber is -5 so 5 and -5 if collide then both x will be loaded neither of them will be left 2s so right Moving in the direction from D. Okay, so if there is five and 10, they will not weigh, so from our example here, like 8 and -8 are from our example here, like 8 and -8 are from our example here, like 8 and -8 are given here, what does it mean that both the asteroids are of the same size but they are traveling in different. Direction, both of them will collide and both bills get destroyed, so here our output is the output which we have given, it is empty iron. Okay, so what will be the approach in this, what will they do? Here we can see that whenever such a thing happens. When we have to pop the action or destroy, we have to give it after seeing the first element and the second element, then the date time is mostly given by time. Okay, so in this we are doing it for stay because here we have to eliminate. It is doing one of the two and it depends on looking at the previous ones, meaning like we took 10, like we put five, but from this we will not know what we have to do next, so if we get minus five, then we He has to do this 10 and if we do n't do this, then this time will come, okay, if we strike him, then how will be the solution in our strike, what will we do, we will start traveling from here, right okay and right, we will be able to do that. We will maintain and what we will do is that if we come to any of our elements then if it is empty then directly we will push it here OK and if any element remains if it is assumed we will push it positive and the next element is positive then still proceed directly. But if the next element if is negative so what bill do they bill compare with our top of D Okay so what can we do here like our 10 put we give over next element is positive so they bill again no problem but if our The next element here is pe-5 so we'll look at minus five so element here is pe-5 so we'll look at minus five so element here is pe-5 so we'll look at minus five so what we'll do is we'll compare it to our top of D cent tax so what's bigger between -5 and 2 here is this minus five what's bigger between -5 and 2 here is this minus five what's bigger between -5 and 2 here is this minus five is bigger because here This is not a problem with mines Bill Have you take d absolute of d number so take its absolute value so will be 5 so five give it greater 2 so what bill do they bill pop this out and give what bill compare -5 Without top of this type bill compare -5 Without top of this type bill compare -5 Without top of this type again so our top of this type is 10 right so this is our top okay we will compare 5 and 10 so here 10 is greater so this is five's we will not do anything here okay so which office tag That will be our final result. Okay, so the asteroids left in the strike now will be the same result as the steroids left in the last strike. So here, when we compare -5 and 10, So here, when we compare -5 and 10, So here, when we compare -5 and 10, then the bill C's -5 will be then the bill C's -5 will be then the bill C's -5 will be destroyed and the U bill. Note push it in it okay because they are smaller written and give what bill do you bill compare our so 11 is greater give 10 so or it's a greater so what will we do pop this and here what we will do -11 insert and here what we will do -11 insert and here what we will do -11 insert Because there is no number ahead and this is strike vote then bill directly insert minus 11 so this is the logic way bill try you implemented okay in the morning also start implementing so what we will do first we will write our style and do normal and one what we will do we will size First we will take one word size ok after that what will we do and what will we do Asteroids come ok what will it do ok so here what happened is that when the strike will not be our empty ok second will not be empty then what will we see that our stock is If that's top, if that's greater than the current element, if that's more than that, negative pocket top, and that's going to push our current limit, okay, so what we're going to do here is STK dot top, that's your greater. Den is zero which means it is positive if it is positive and our asteroid which is okay so our asteroid now which is the current element current asset which is if it is negative so if it is negative then what will we write top which is our which is the positive element okay so Aggarwal Lee, ours is asteroids, so what will we do, we will take its absolute, okay so we will take its absolute, and what will we write here, if it is less than what is ours now, we will make it okay, then HD card top, if ours is Greater Abraham, who will do our topic and If the same if the top is getting bigger then what they bill do they bill just to I plus okay so I plus rate and will do direct increment if we look at the next negative number then it means whatever students are left in the last will be our There will be a result because he is a start back, so what will happen here, we will not do cadence, what will you put in the condition, the one who is going in asteroid negative and the one who is on top i.e. who is positive, i.e. who is positive, i.e. who is positive, what will happen if both are of the same size. Will get disturbed right so what bill just like dot com because we will pop the positive one which is in strike and we will also increment the bill and sound ok they also incremented the value ok so this is ours what was this in this condition Our style is on top if it is positive and when the current element is negative then we have to do all this but if the time we have is positive and the next element is positive then what we will do is we will directly push right so here after the if condition. What we will do here is we will do something directly and after that we will do something i plus what is happening, we will first do something increment so here we have done okay so now what we will do is finish smile loco and after that what we will do we will simply whatever Whatever asteroid we have in our track, we will simply put it in the result, so what will we do to make it useless, what will we do, we will put another one for the asteroid, we will pop the egg and put it in the result, then what will happen with that is our starting. Otherwise, if we put in this type also, it is the opposite, meaning if we look here, we have done something like 10 here and then you have pushed, if one - 5, everyone and then you have pushed, if one - 5, everyone and then you have pushed, if one - 5, everyone is not here in front. When we do something, we have to give him the result, don't you give another 10, we have to give 10 and 2 sitters, okay so what bill do they bill him, type it back, correct order and this what they can do this but they can do this water Can take one vector bill If driver seat pops from back and back side travel, then we will put it in the last, right so date is our way, you do it, so what will we do here, we will put it on , which is top, we will put it Back in I plus means I can go to the next element okay so by doing this our result will be populated and give what they can do it they can just return our result so here we are right time offer okay so when does this come when Sometimes we are traveling reverse and we do plus here, sometimes we make the error straight, so we can see here that if we travel from last time is zero then travel and they are increment so this OK, so what will we do here and here our result will be in dot size because here the result which we have taken as a vector, what will be its size will be result minus one, we will travel from there, okay, we will submit it and see. Next Video By | Asteroid Collision | asteroid-collision | We are given an array `asteroids` of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
**Example 1:**
**Input:** asteroids = \[5,10,-5\]
**Output:** \[5,10\]
**Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
**Example 2:**
**Input:** asteroids = \[8,-8\]
**Output:** \[\]
**Explanation:** The 8 and -8 collide exploding each other.
**Example 3:**
**Input:** asteroids = \[10,2,-5\]
**Output:** \[10\]
**Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
**Constraints:**
* `2 <= asteroids.length <= 104`
* `-1000 <= asteroids[i] <= 1000`
* `asteroids[i] != 0` | Say a row of asteroids is stable. What happens when a new asteroid is added on the right? | Array,Stack | Medium | 605,2245,2317 |
1,550 | uh hey everybody this is larry this is a cube one of the recent contests uh three consecutive odds um so this is easy and it's easy i think you should just do the first thing that comes into your mind and in this case given that n is less than a thousand just do the stupid thing uh and that's basically what i did um i you could see me solve it during the contest and i solved it in something like 40 seconds or something like that but i was even too lazy to put minus two here because i didn't want it to have enough by one so i just did you know if the first numbers are the second numbers are then the third number is odd then return true otherwise just return first so it should be straightforward uh if you're watching this video i don't know why to be honest but hope you solved it quickly um and yeah let me know what you think and you can watch me stop it live now | Three Consecutive Odds | find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows | Given an integer array `arr`, return `true` if there are three consecutive odd numbers in the array. Otherwise, return `false`.
**Example 1:**
**Input:** arr = \[2,6,4,1\]
**Output:** false
**Explanation:** There are no three consecutive odds.
**Example 2:**
**Input:** arr = \[1,2,34,3,4,5,7,23,12\]
**Output:** true
**Explanation:** \[5,7,23\] are three consecutive odds.
**Constraints:**
* `1 <= arr.length <= 1000`
* `1 <= arr[i] <= 1000` | Save all visited sums and corresponding indexes in a priority queue. Then, once you pop the smallest sum so far, you can quickly identify the next m candidates for smallest sum by incrementing each row index by 1. | Array,Binary Search,Heap (Priority Queue),Matrix | Hard | null |
266 | guys this is you sir hi Serena going in this video I'm going to take a look at 266 button pattern from permutation clean a string to me for the permutation of the string could form a palindrome told not okay may be true your rear rack true so what is palatal it means like a be a and AP day right so you read it from left or from right it could be saying so actually we if we because it's symmetric if it's all it means they will be always duplicate numbers right two plates accepts the middle one so for this case will be one odd count for the characters and or even else and for the case here or even right so actually what we can do is just account count the characters count the character and the are count the doubt count must be smaller waited one men it could be a parent oh yeah so it so we do we get the count quickly count no we have to count to four all of them yeah let's count it so user created map years already we're not saying that okay we're not guaranteed a B the B string is only half of it so this is cat okay for a minute actor of SAT tool okay so now we count the all count of aunt earth okay so for that or an it's count is not these brings values divided - he's a macho equals one values divided - he's a macho equals one values divided - he's a macho equals one which mean we have found that articles so plus one right and then if either one then the triangle pose finally we try to write so this is the solution to look at force and then autocrine uh my head is in the work it's too late count and occurrence of devalues it should be all ah there's a typo here man who yeah it's breezy now hug helps say the exact right | Palindrome Permutation | palindrome-permutation | Given a string `s`, return `true` _if a permutation of the string could form a_ _**palindrome**_ _and_ `false` _otherwise_.
**Example 1:**
**Input:** s = "code "
**Output:** false
**Example 2:**
**Input:** s = "aab "
**Output:** true
**Example 3:**
**Input:** s = "carerac "
**Output:** true
**Constraints:**
* `1 <= s.length <= 5000`
* `s` consists of only lowercase English letters. | Consider the palindromes of odd vs even length. What difference do you notice? Count the frequency of each character. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times? | Hash Table,String,Bit Manipulation | Easy | 5,242,267,409 |
470 | hey everybody this is larry this is day 28 of the august decode daily challenge i hit the like button hit the subscribe button and let's get started uh join me on discord and implement rent 10 using van 7 using a given when seven one two seven uh okay yeah i mean okay what are these oh they're just number numbers um so the couple of ways we can do it uh the most naive way is just we do it twice and if it's outside of um you know you have two numbers uh and you can i was gonna say you could add them but then that doesn't give you an even distribution because then you have this binomial thing right so you could just multiply them and um and then if it's not from um if it's not uh um from 1 to 40 or whatever it is then now can you multiply them uh i mean i guess the most naive is just do it 10 times uh and then sum it up is that right my math is pretty terrible today um i think that should be rough yeah i mean i think for some reason i think i'm square boot but i think what i actually wanted to say was just do a base seven um oh sorry i think of square but uh but yeah this is one of those one-off is one of those one-off is one of those one-off farms maybe an even interview from but it doesn't really come up that much so my tools are a little bit rusty for it uh so that's what i'm thinking about again but this is a good problem to think about i just come up like i'm gonna sell the sim requirement elementary um algorithms back in college uh so definitely it's a fun brain teaser e problem uh and yeah and i think i was thinking of squaring it to get to base seven but what i actually want is just the base seven um and then now we have a base seven number um we can just divide it by in this case it goes the ranges from one to forty nine uh we just want to get it to 1 to 40 divided by 4 so we get 1 to 10 uh and then we um we roll it right uh if it doesn't uh and you could do another way as well you got this base 7 number uh and then if it's not between one to ten but then you would reroll a lot of times right um so yeah and we'll do the math uh afterwards maybe we do these follow-up questions uh follow-up questions uh follow-up questions uh but yeah so that's what i'm gonna do for now um so now we have let's just say a rand 49 um which i guess is it 149 i guess it's around 49. now it just depends on with the serial base or one based is what i was thinking of um so yeah so this is just return rand of seven uh times seven plus random seven um maybe plus one wait is one seven one two seven okay so actually um minus one because yeah and this is also minus one but then you wanna plus one again right i'm just trying to think about the edge case of like okay so this is uh one and this is zero um sorry if this is two this is so this is one then this would be seven right so okay and then now we do wow when 49 um is less than or you go to i'm just going to do this in uh so this gives us a number from just to be clear this gives us from zero to 48 um so yeah so now while this is less than 40 or this is greater than or equal to 40. uh we operated in yet i don't know let's try if not then we just do it's fine um someone like that right yeah yes it's just getting random numbers uh let's see if it gives us any issues uh okay the world's operator kind of works but not really oh no this is fine for some reason i thought it was seven uh let's try again i mean randomness is always tough to kind of eyeball uh but it looks okay in that it doesn't give you anything bigger than 10 it doesn't give you anything smaller than uh one right so yeah let's go submit this and then we'll analyze this uh code later with cool uh yeah uh again so this takes some practice and it took and i just woke up that's my excuse but uh but you know it took me a little bit to catch up on it um because i was seeing some at because you know and one thing is just with experience you can at least validate your dots very quickly right i said oh you could just add them and then you know and it adds up to 14 and you just stick to it one to ten but then i was like oh right now that's just obviously binomial uh choose two so then that means that you have this like peak thing right um because that was not going to be uniform and then i said squaring uh not squaring them but multiplying them but then obviously you're not going to get the right distribution even though it goes from 0 to 49 so or 0 to 48 uh or 1 to 49 i guess so the domain is right but it's a little bit off uh because it's not you know every number is going to be not equal to represent represented so then i just remembered i was like oh yeah you just need a base seven number um yeah and basically um so what is the expected number of calls right so this so you do something like uh so you could also do something like this uh and they would probably work but it may be a lot slower so if you have something like this then well what's the chance of success right um so the expected value of x is equal to x um just expect the value of x plus um in this case it is well this is one but oh uh i think i just messed it up it's like i said um so it's four fifths roughly speaking i mean i'm hand waving is actually um okay fine let's just be precise then right so it's like 39 out of 49. um chances maybe i'm off by one but it's still roughly right um so this is the recurrence uh and if you sell for it then it's you know it's a lot more i'll leave that as an exercise at home there's a formula for it but um when you do something like you know and if you reduce this to 40 then you reduce this to 9 over 49 times use of x um plus one and you know and this is clearly um this is clearly a convergent because you can show that this is uh clearly less than this is clearly less than uh one half u sub x plus one uh and this obviously is just maybe not obviously but if you have uh this formula of e of x is equal to one half to oops u of x is equal to one half y of x plus one uh that's just like the classic conversion of um you know dot uh is one plus one half plus one fourth plus dot right and that obviously is just you know linear slash you know uh well not linear sorry it's just two right so that's what the convergence series is uh so that and because this is less than uh the function that we're doing is less than this that means that we're only going to call this uh less than two times is the expected value um and you know and each of these calls this twice so you could say it's less than four as an expected value uh can you minimize the number of coursework um you can probably do some funky math with different bases or something like that to play around with it so that maybe the number of course but uh but that's all i have for this one i think i'm confident with it so i'm okay uh let me know what you think let me know if you optimized it or did it a different way because i assumed i think there quite a couple of ways to do this so let me know what you think let me know how you celebrate hit the like button to subscribe on drum and discord and i'll see y'all tomorrow bye | Implement Rand10() Using Rand7() | implement-rand10-using-rand7 | Given the **API** `rand7()` that generates a uniform random integer in the range `[1, 7]`, write a function `rand10()` that generates a uniform random integer in the range `[1, 10]`. You can only call the API `rand7()`, and you shouldn't call any other API. Please **do not** use a language's built-in random API.
Each test case will have one **internal** argument `n`, the number of times that your implemented function `rand10()` will be called while testing. Note that this is **not an argument** passed to `rand10()`.
**Example 1:**
**Input:** n = 1
**Output:** \[2\]
**Example 2:**
**Input:** n = 2
**Output:** \[2,8\]
**Example 3:**
**Input:** n = 3
**Output:** \[3,8,10\]
**Constraints:**
* `1 <= n <= 105`
**Follow up:**
* What is the [expected value](https://en.wikipedia.org/wiki/Expected_value) for the number of calls to `rand7()` function?
* Could you minimize the number of calls to `rand7()`? | null | null | Medium | null |
62 | ne them big this time and welcome back to new video in this video before going to solve six second problem only code and visiting squad unique parts software will give and grade of clan hair in this case which has great of three 2279 teen rose seven columns no This point to be our starting co in which 1000 that is laptop portion of the great and will have to furnish etc subscribe bottom part of the hero 10 whole grade only option hate here and there right side and off the side of the great subscribe possible powder Can Take To Do Subscribe Possible All Possible And So On 500 Or Hafta The Same Kind Of 3570 This Point To The Worst Position And This Point To Be Our Position Subscribe Programming Problem Solve Every Possible Parts And Password To Start With What Is This Point Possible Way Should Start From A Number Of Way To Go To Is Just Like Subscribe And Possible To Reach The Well Simran Liye What Are The Possible Ways To Reach At The Next Point Which Never Ignore This Way Can Take The Andher Only Option Left Right Left The position which like and share and to go to all the like subscribe and share and hear water the best tourist this point sauvir will have two option will come from upward from left side and on left side number of the top 10 way subscribe Top and from left from subscribe possible record quick end oneplus 5 hair record 6 and hair oneplus 6t quote 7 if you want to reach at its particular position it is 512 subscribe must subscribe possible final 700 plus 7v quote 28 sudhir 128 Possible Ways To Teach From This 020 Leftmost Position Of Great And This Is Part Of The Best Possible Thursday Subscribe Values Subscribe To Our Thursday Subscribe Values Subscribe To Our Thursday Subscribe Values Subscribe To Our YouTube Channel Subscribe To The Software Which Has Given Benefit Which Is The Number Of Crops And Columns To The Worst Thing Happened Two way switch of create and there were doing this to all the values for values for values for grade 03 Patience to you a bill passed and which are the end columns of this will all the phone I love you the soul will Simply Call Win7 Passing Accused Chords The Column0 Trolls Pale One And Similarly I Need For Column 1 Column Values Of 1808 Jaune Player I Column 1 Column Values Of 1808 Jaune Player I Column 1 Column Values Of 1808 Jaune Player I will also subscribe Row End Column One Em Lucky Warden Ek Singh VHP Snake Singh Bihar Feel Patience With All Possible 500 We Need To Arrested For Us For Peon In School And Subscribe List Play List A Foreign And Junior Executive Vijay Love And Joy Please Like This Page Don't Share Market Value Here To Z With Me To The Value Of Subscribe - 1898 - Switch Of The Value Of Subscribe - 1898 - Switch Of The Value Of Subscribe - 1898 - Switch Of The Year Film Triple X That all dance with falling they are not meat by the way Hussain player return the value of the right bottom part which is defense position then simply return layer - 110 - 110 handed over simply return layer - 110 - 110 handed over simply return layer - 110 - 110 handed over money abroad lax long distance and css working or not 210 settings default accepted So let's submit this and see testing accepting ok solid this submit and behave with force solution that research set for this video will have seen how they can you white ko rural solve this problem solve inch width like button and dislike subscribe The Channel for More Code Interview Problems Next Video | Unique Paths | unique-paths | There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The test cases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** m = 3, n = 7
**Output:** 28
**Example 2:**
**Input:** m = 3, n = 2
**Output:** 3
**Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
**Constraints:**
* `1 <= m, n <= 100` | null | Math,Dynamic Programming,Combinatorics | Medium | 63,64,174,2192 |
37 | uh today we're gonna be working on lead code question number 37 suru suroku solver so last time we did just uh we checked for the validity of the circle and the last question this question we're gonna be solving the sudoku so it's going it's gonna be done using a back tracking uh here are the rules it's gonna go from one to nine and the blocks are three cross three and wherever there is a dot that means it's an empty one which we need to fill out and we're gonna be doing it using backtracking here uh because uh basically we're gonna be trying all the different combinations and see if it still keeps it valid or not and that's how we're going to be coming up with the solution so here is a basic structure of it we're going to be returned so it's uh initially n is going to be the length of the board which is going to be 9 actually and then we're going to be depth first search we're going to have a function definite search which we're going to be providing the board and the length of um you can say row or call and then we're gonna go through we're gonna basically traverse through the board uh the right one is gonna go from zero to nine and then uh sorry rows are gonna go from zero to nine the columns are gonna go from zero to nine so while we are traversing that and we find out that where we are it's uh the board's value is equal to a dot we're gonna do something about it what we're gonna be doing is like we're gonna be continuing we're gonna say that okay uh this is good we're gonna oh sorry if it is not equal to dot we're gonna say that okay continue we don't wanna worry about anything like that is the case but if it is a dot if there is an empty if this is the place where we need to fill uh fill up what we're gonna be doing the possible solutions can go from one to nine so we're gonna try all of them so what we're going to be doing is like we're going to take the i character which is basically what it's a it's an integer converted to a string and its value can be from one to nine we're gonna take that i character we're gonna check we're gonna before each even putting it in we're gonna validate it sorry validated we're gonna send the board the row like the which row we are in which column we are we have right now n which is basically nine in this case and i character which is the you know the character we want to try out if there is a valid that like after putting that in if it still stays valid we cannot put the i character at that place and after that we're gonna undo uh we're gonna call back the dfs with the board with the new board with that ver edit value and the n and if we receive um true we're gonna repeat a total intro and after this like after checking all the nine values what we're gonna be doing here is like we're gonna say that is so basically in back backtracking once we are done testing with these values we're going to move it back to if none of them work we need to move it back to a dot and return false now the last thing we need to actually before that uh after uh coming out of these two traversal loops we're gonna be returning true the last thing we need to do is to program this is valid function so the is valid function is basically going to take the board um the row the current column uh n which is the total num like the total number of rows the total number of columns which is nine and the i character which is an integer from one to nine converted to a character so we're gonna try that out so for that what we're gonna be doing is like first of all we're going to be doing the block row which is r divided by 3 and after taking the floor of that multiplied by 3. similarly the column the block column like which block we want to check for is again c divided by three taking the floor of that and then again multiplying it by three now we're gonna traverse through like the i is gonna be going from 0 to 9 and then we want to check that the row we want to check few things here first of all we want to check that like yeah we are checking that whether if in three different cases if uh the value of that i character if it is already equal to i character which we want to put in uh that means it's a false we shouldn't be able to do that so yeah there's a mistake here though we're gonna check at the earth row and the eighth column i throw and the c column yeah we basically want to check in these two things we need to return if that if we have that then we're gonna say that the current row is equal to the block row because we also want to check uh in that block do we have that value in that block right so we have to have like a three cross three block which we want to try out so the current row is gonna be equal to the block row plus the math dot floor of i divided by three similarly the current column is going to be equal to the block column plus the math dot floor of i divided by 3 oh actually this is this time it's going to be equal to the modulus of 3 so once we have the once we have calculated the block so we have to make sure that if the board of that current row and the current column becomes equal to i character that means we're going to be returning the false so initially we were just checking the rows and the columns now we are checking on the whole blocks if we come out of that for loop that means we are good to return the true that after putting it putting on the i character at this current row and column we this is gonna still be a valid uh invalid sudoku so that is it we implemented the is valid which actually gives us that whether it's going to be valid after putting the value in and then we have the default search when it passed let's see if it how it does for the other test yeah on the test pass passed so thanks for watching | Sudoku Solver | sudoku-solver | Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy **all of the following rules**:
1. Each of the digits `1-9` must occur exactly once in each row.
2. Each of the digits `1-9` must occur exactly once in each column.
3. Each of the digits `1-9` must occur exactly once in each of the 9 `3x3` sub-boxes of the grid.
The `'.'` character indicates empty cells.
**Example 1:**
**Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\],\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\],\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\],\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\],\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\],\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\],\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\],\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\],\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\]
**Output:** \[\[ "5 ", "3 ", "4 ", "6 ", "7 ", "8 ", "9 ", "1 ", "2 "\],\[ "6 ", "7 ", "2 ", "1 ", "9 ", "5 ", "3 ", "4 ", "8 "\],\[ "1 ", "9 ", "8 ", "3 ", "4 ", "2 ", "5 ", "6 ", "7 "\],\[ "8 ", "5 ", "9 ", "7 ", "6 ", "1 ", "4 ", "2 ", "3 "\],\[ "4 ", "2 ", "6 ", "8 ", "5 ", "3 ", "7 ", "9 ", "1 "\],\[ "7 ", "1 ", "3 ", "9 ", "2 ", "4 ", "8 ", "5 ", "6 "\],\[ "9 ", "6 ", "1 ", "5 ", "3 ", "7 ", "2 ", "8 ", "4 "\],\[ "2 ", "8 ", "7 ", "4 ", "1 ", "9 ", "6 ", "3 ", "5 "\],\[ "3 ", "4 ", "5 ", "2 ", "8 ", "6 ", "1 ", "7 ", "9 "\]\]
**Explanation:** The input board is shown above and the only valid solution is shown below:
**Constraints:**
* `board.length == 9`
* `board[i].length == 9`
* `board[i][j]` is a digit or `'.'`.
* It is **guaranteed** that the input board has only one solution. | null | Array,Backtracking,Matrix | Hard | 36,1022 |
665 | um hello so today we are going to do um this problem non-decreasing array non-decreasing array non-decreasing array uh basically what the problem says is we get an array of numbers with n integers and what we want is to check if this array can become non-decreasing this array can become non-decreasing this array can become non-decreasing which means basically increasing um by modifying at most one element so we take that away we can modify at most one element and we want to see if we can make it not decreasing or not by just modifying zero or one element at most um and not decreasing of course it's the previous element is smaller or equal than the next element um and that's pretty much it so if you take a look at this example four two three um we could just change form here maybe make it one and that would make it increasing right make it increasing which is not decreasing um here we can't right um we have to modify maybe two elements maybe we have to do here put here one and then put here three to make it non-decreasing right non-decreasing right non-decreasing right um so here we can do it with just one element um and yeah these are the bonds so that's pretty much the idea now let's see how we can solve it so one idea here uh we'll take these two examples and use but the one main idea here is that if you have a number at the previous position right bigger than the number at position i then it's always more optimal to replace with the smaller value because uh let's say this is i right and this is i minus one and we find that this is bigger position i is bigger it's always more optimal to place i minus one with the value at position i right and make that the modification because then um numbers we will find here if this array will return true a numbers we'll find here will be always bigger so it's more optimal to replace with the smaller value and so here we'll place we can just take um the number at position i minus 1 and replace it with the number at position i and count this as a modification so if we have a counter for the number of modifications since we are allowed only at most one uh we count it here okay however there is one case where this is not working properly for this example it works because we find that okay four is bigger than two and so we replace four with two right and so now we end up with two three which is and decreasing so this works out however with this array it doesn't work out quite well because okay so uh we if we are this is smaller so it's good so we move to i being at position two here and so we find that it's um it's smaller right and this i minus one and so we do what we did here which is replace and so what do we end up with two here but then the problem is i minus 2 is also smaller so if we do the same thing as well then 2 is also smaller than i minus 2 if we do 2 here as well then we did two modifications right so the count here is two and do our load only at most once so this is not the optimal solution actually we can do um we can solve it differently what we can do instead is for this three four two six we can instead replace the two with four so replace the element at position i with the element at position i minus one and so with that we'd have here 4 and we'd end up with an array that has 3 4 6 so it's sorted here and so the conclusion here is that we can do only two modifications either place the element at position i minus one with the element at position i or replace the element at position i with the element at position i minus one and how do we decide it's just by comparing if the element at i minus 2 is already smaller than the element at position i then we will get a sorted array because we'll have the smaller number at i minus 2 the same number at i minus one and i uh the position i and then the rest hopefully it's sorted um but we'll check and if count is exceeds one then we'll return false um and then for the second case where we need to place the element at position i we just need to check if i minus 1 minus 2 both i minus 1 and i minus 2 are bigger than i then we need to just replace the number at position i with the element at position i minus 1 and that way we'll get a non-decreasing sequence there right and non-decreasing sequence there right and non-decreasing sequence there right and so here in this case basically if in addition to this we have a number at position i minus 2 is bigger than the number at position i then what we want to do is replace the l limit at position i with position i minus 2 right and so this is what we need to do here okay um okay so that's pretty much it for this idea now let's cut it up and make sure it passes our test cases um okay so let's solve it with this with the solution here so uh we need to go through the array right and we'll go through from one to end because we'll check the number at position i minus 1 and so we need to be to start from one and here we need a to initialize our count and also we need to have n which is equal to the number of elements okay um and then what we need to do is just do the check so if um numbers position i minus 1 is bigger than the number of position i then what we want to do here is of course increment the count because we found a correction or a modification that we need to do but before finishing there we need to check i minus 2. if it's bigger than at position i then what work to do here is replace the number of position i so that we replace this element with i minus 1 instead of modifying both are minus two and i minus one which will give us count of two instead of one and so here we'll just replace with i minus one otherwise it means this is already smaller than the number of position i so we can just replace i minus 1 with the number at position i since it was bigger what a place it becomes smaller it becomes non-decreasing non-decreasing non-decreasing and now after each increment if we increment count each time we check if the inc we incremented and we exceeded one because that means we need to modify more than one element and so that means we need to return false because we can't make it non-decreasing with just one element non-decreasing with just one element non-decreasing with just one element with just one change right um and then at the end we can just return if the account is still smaller or equal to one which is at most one element um and that's pretty much it so also on this make sure it passes um looks like no we got uh false in the first test case um and the problem is here so python if you do um oh sorry python if you do a number at position if you do something like this minus one then it counts right and we don't and that's what is happening here we so with if i equal to one then we'll get minus one so we'll get minus one at the end which is actually um the last element in the array and so this check here we need to check also that this is valid right that is a valid index um and that's pretty much that should work source front again okay so that seems to pass there let's test it and their classes test cases um yeah so that's pretty much it um you can solve it a couple of other different ways but i find this to be the most straightforward solution um yeah so thanks for watching and see you at the next one bye | Non-decreasing Array | non-decreasing-array | Given an array `nums` with `n` integers, your task is to check if it could become non-decreasing by modifying **at most one element**.
We define an array is non-decreasing if `nums[i] <= nums[i + 1]` holds for every `i` (**0-based**) such that (`0 <= i <= n - 2`).
**Example 1:**
**Input:** nums = \[4,2,3\]
**Output:** true
**Explanation:** You could modify the first 4 to 1 to get a non-decreasing array.
**Example 2:**
**Input:** nums = \[4,2,1\]
**Output:** false
**Explanation:** You cannot get a non-decreasing array by modifying at most one element.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 104`
* `-105 <= nums[i] <= 105` | null | Array | Medium | 2205 |
212 | So hello friends today I have given 48 and my name is Keshav you are watching take it world search second actually this is a hard problem why is it hard actually no problem is hard it just has more parts so if we divide it part by part If you understand the parts then it becomes easy then why is there a reason for it being here because look at which number 20 we saw this look at the 23rd day which is our cup's gone then you will get the video of the complete playlist of Blind 75 If Rakhi has been made, then I had told in the word search, okay, then you will say that it is okay, I told you on 23rd, but why have you taken it so far, that is, after giving 24th, you can do it, but it is being implemented in it so that it If it can be optimized then it was necessary to understand for whom word search has been made, then look at the question, this is the question, first you will remember what happened in word search, if not then please watch further, please give me the video. You have to see, one is the tree date, I think, now I had also shown which one was 46, and the other one was 23. I had seen the one with word search, so what is there in it, what do we do by searching the word, we get it here. It's okay, return true, return two characters, return false. Now the matter has progressed a little, the matter will not end in true and false. Now we have a lot of words in the input, whatever is there inside the board, we have given the word key. Rakhi has given us the list, okay now I have to find out the list of this board inside this board and here I have to find out if anyone from these worlds can see me, then whoever can see me is at And it is visible as you can see that here they have highlighted it, I am seeing this is the output that we want, so what do we do, whenever we search, we do dfsbfs, what do we do, each particular group of us. What is done in force technique is to go and see each and every value, what is the point of doing this, there are four directions, top and bottom, and look from above, there are some constraints too. If you read carefully, then he has told. That it will be between A and S only and should not go out of bounds, keep in mind that there is nothing else left, you will sit up and down and on top of that there is a cross of M and also which word is which from the list of words. So the process of all those things will slow us down a lot. Time complexity increases, so to avoid this, we have try, we do prefix tree, so I will tell you about it in the notebook, right? So let's move on to that and I will say again that you should check the prefix tree once because we are going to write its code here, then you will say, have you understood, why not, then we have explained it there, okay, so let's make one thing clear in this. It is like this has been given to us and like a word search van, I take it in a particular word, like in the beginning, I have to find the other word, a list of such words is being made, so what will I do here, each one? I will check by going to the value. If we talk about root force approach, then I will check by going to each value and going further like O came A came ok, meaning from O we get only two directions, one to go forward and one to go forward. Actually, there are four ways to go down, forward and backward, right, but it will be out of bounds, right here and here, you can go here only and you can go here only, so we checked this possibility also, then did this one also, so O A Then below is my t and then we have found it, so I have found it from the list of many words from the world list, we have found our particular word which can be formed, we have it through word search, but this is A good case is done, but if we do not want to find whether a particular word is there or not, then I will have to reduce each one by going to each particular value, going forward, backward, right and left. Otherwise, when you remember, I have written the world Search was taught to you, so what was there to do in it, we were reducing it like this, there are four directions, but tell me once, you have given me so many words and I don't know which word it is, you did not tell me anything, okay, the list will not go on such words. We mean, start from where you can go. Well, it's lucky that O was there, so it was there in the beginning. Now let's talk about P is not there. TV is a good example. Look, it is not there, so why search for it? We have made a fixed tree by taking a small example, it will become bigger, is n't it? I take four at random, I have kept a list of words from late, I will do it from here, so if I make a prefix tree. It seems that I know what all I have given here, it is true that I have given it, I know that if there are more, they will come from here, for the time being in this case, it is given by O, then where are we? After OK comes my A, is n't it? From A, we have two values. One A comes, so we go to this A, so the value comes 80, one A comes, so we go to this A also and from here. Moved to T and after OK, there is also A here. Look, OK, the point is, A is followed by T, so by doing this, our prefix becomes 'Tu'. Okay, our prefix becomes 'Tu'. Okay, our prefix becomes 'Tu'. Okay, this thing is clear, now we have to check. Man lo, it is not here at all, let's say it is being formed, so there was nothing below it means that the word ends here, so it is present in our world, so the person named Vote is present in the list of the answer that will be given to us. There will be talking about OK, after I, after TPT, A was to come, so here there is nothing below A, but we got this, so we also got the word named Oye, whatever it is Ot, isn't it? This way we will go, is, it is Ot, isn't it? This way we will go, using prefix will also work, okay, there are going to be a lot of previous concepts, isn't it is the same thing, let's make it again, so friends, I am here again and look at this, the code has already been written because it is very big, isn't it? So what is the reason is that we have implemented Try Note here, so much so that you can imagine how well it is being implemented in the solution, you must be seeing that we have got some things from the familiar. Can you see what a family there is? Firstly, we created children inside the class tree road. What does a child do? I told you that if the value is a foot, then it will be our character and what will be the value of its child, the value of the tree note. Whether or not the tri note will be created, it will have that value of the child and whether it is the end of the world or not. Like we just saw the example of Oath, it had teeth in the last and there was end of word, so for now we have kept false for that also, we will counter it in future. We will also have to run a counter. Why, if I tell you further, what will we do? We will add a word and remove a word. We will have to see both the conditions. We are increasing the counter to add a word and decreasing the counter to remove a word. Okay, and the four C's in Word are the same concept that I told you in Word, which we had read about Edward etc. earlier, it is the same that if we do not have an account in the current children, then we will add it to the current and increase the counter. The end of the world will come true in the end, it will go meaning the whole world, we have seen it, we are removing it from the concept, the current counter will be decreasing and the counter will be increasing, meaning it will be moving forward, what have we done inside the solution, find the word. Inside, I also took the board, it is the same as before, I left the rest of the words as words, no problem and took the root of the tree note for in the world Sam, what are you doing to each word, adding the initial and row columns. Length of board and length of board zero date is for this column, so if you are reading it before then we have taken answer and VS, it is ok for visit set, both of these are set, what should be the answer, do you know in the answer? Is there any word that is being repeated? To avoid this thing, we have set the answer also. Visit must happen further because look, I am writing to you, that to me is the excite code with prefix tree written above and The exit code of the word search van is written here that we do only this, I have taken the unload and the world separately, why have I taken the road because it is already visited to see which all have been visited? Because how much of the word has been made by us till now, no word and how much have I taken, how much have I made, so are you equal, you cry or are you greater, give equal, whatever you have to do, and meaning, the role should not be exceeded, it should not become more, the column should not be equal. If it doesn't happen, give it smaller or if it doesn't happen, it means we have to check auto bound and if R and C are in our visit set then it is a matter of problem, no, this is a matter of problem and if it is a matter of problem, then return it as base case, right? So how can the base be used here brother, its meaning cannot be reduced and similarly, if it is not in the board and not in the children, then what is the use of the board, the word is not there in the board and there is an Android children counter, so take care of that too. It's okay to keep our counter. Decreasing the time limit does not mean that we get a seed. The counter is running, so it is guiding us. If we put it to check, what will we do? Like before, what will we do? By adding it from the visit, adding it and adding R and C, making it a tuple and removing it from the visit, less is going on in between, how many times did we have to call four times, so I told DFS four times up and down. Right, left, plus one, minus one, we will do it from the row, then we will do plus one minus one from the column, along with N and W, note and word, these four parameters are variables and we will create a note by calling the end of the world, we have got it. And add it to the answer and also remove it, we will score two runs and when we go to remove it means we have removed it from the visit set, now the court will run in our place, we take R and C separately, right? For the column DFS, initially we will give RC root team and along with it we will give an empty word because the word that is our increase is going to increase, here is the word plus equal, we have initially put empty, we will increase it, our To make the string, finally the list which was created by our set will be returned. The list of our answers will be returned. By the way, I have already run it, I will do it again for you just for sure. Okay, so see if you are getting success, give it in the description. I am with you this play list of Blind 75 etc. Questions etc. Go to the description and hit check. You will get it in the next video. My name is Keshav. You are watching. If you have any doubt then what should you do once. If you have any doubt then just once. Watch the video again, understand what is not said above, what is said because if we keep typing each and every thing, then a video of 20 minutes to 40 minutes will be made, so understand a little bit, analyze it and think what is happening. Everything is fine in every step, let's go | Word Search II | word-search-ii | Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_.
Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
**Example 1:**
**Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\]
**Output:** \[ "eat ", "oath "\]
**Example 2:**
**Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\]
**Output:** \[\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 12`
* `board[i][j]` is a lowercase English letter.
* `1 <= words.length <= 3 * 104`
* `1 <= words[i].length <= 10`
* `words[i]` consists of lowercase English letters.
* All the strings of `words` are unique. | You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first. | Array,String,Backtracking,Trie,Matrix | Hard | 79,1022,1433 |
46 | hi everyone once again welcome to my channel today in this video we are solving another problem from lit code top and derby question list and the problem is permutations so if you see this problem like and dislike ratio you can get automatically how much important is this problem so and this problem is get asked in all type of companies so this problem is very important to solve if you are practicing for the upcoming your interviews so the problem is like we are given input integer array with all integers is distinct and we need to return all possible permutation and we can return the permutation in any order that does not matter so for example one we are given input array nums which has three integer one two three and we need to return all possible permutation of this so if we have n number then we will have n factorial permutation for three we will have three factorial permutation that is six so we will have six different permutation and we are returning in the output so how to solve this kind of problems so this kind of problem can be solved easily by the trying to formulate recursive solutions and that netting what called the backtracking algorithm so let's start implement like understanding it so initially we are given like one two three so this is our input array so what we need to do we need to first fill the first place of our uh result like permutation so if i draw it so the first place can be filled with the three possible numbers so we can have three possible first place numbers candidate and we will draw three branches from this so first we can fill one then two then three and the rest let's keep it is as it is so if we keeping one and two three like as it is we are swiping with two so this is one and three and similarly this will be two and three so that just we are swapping with this 0th place so we will also get by index initialize from 0 at this place the index is 0 and we are filled with 0. so after that when we are calling next the permutation call our index at each level this will become 1 one over here now we will try to fill the second place for this call so for this call for filling second place we can fill like one is already filled so now we have again two option two or three so first we can fill two then three is as it is similarly we can fill one is already filled three then two so this is now over here two second place is filled again from here we can do again two one and three and another we can do this is two is already then three and one similarly from here we given then finally we need to fill the third place index over here will become two at each all this is like index in the level so level of our tree so we are kind of now when we fill three we have only one option so we will keep one two three as it is so this is our one permutation and at this place our index becomes three so when our index becomes equals to number of elements so initially number of element of in our array is and which is three so once it becomes that means this is a valid pair of permutation and that we can store in our result so we can also declare a result that will be list of integer and once our index equals to the n then we will fill that into the ah list of integers so that is the idea behind it and from here also we will get one pair then one pair so from total we are terminating this approach in these six places so that is the idea now how to implement in code so for implementing this code i have already given some idea but let us see what we can do we will initialize this in the our we will write a backtrack helper method here we will have a list of list that will hold our result first as a reference we will pass from kali method also we will pass an index that we will initialize from 0 from the calling method as well as we will pass our nums this is nums original the input array so once we got and the base condition here we will check if our index is equals to nums.length if this is the case that means we found the permutation so we will do some processing and store the permutation into the result obviously so here we need to fill the list as a list so we will first convert this current array and store into the list now what we need to do we will run like for starting from int i for in i starting from index current index we will go until the length of our array so nums dot length and we will first call the backtrack method so before that we will fill the place so we are storing in the so here we are uh keeping this in the integer variable so this is our input original array nums and initially let us say we are 1 2 something 3 so at this place we will swap with this place so whatever place the value of our initial index so we will swap this at place like index and the current i once this done we will call again the method backtrack with the new index so the index plus one and after that once we done we will backtrack because we need to try other possible case once we done with either we found the solution or not we will backtrack again so we will swap it back the index and the i same place because initially first we swap we put at the index integer into the ith index and then we are swiping back so that we will try other possible cases so this is the code idea now you can try to pause the video and implement the code by yourself so here is the code i have already implemented so this is the code as i initially this is our main method where we are declaring a result list of list as a output and we are calling the permuta so that is nothing but the backtrack method and here we are passing this an index from initializing from 0 now we are checking if index is nums dot length we are creating a list uh from the array and this is box we are using as we are converting primitive data type into the reference object integral object and then we are restoring into the creating a copy list and then we are storing back into the list of list this in our result variable otherwise we are iterating from index to the length of our array and first swap that index i element with the index element and then backtrack it here so this is the step where we are backtracking back track it back now what is the so before that let us try to run the code so this code will run as it is already i have tested so it is working as it is now we can submit the code so let me show you this these submissions so it got accepted so it's like running 5 millisecond as i am using the streams so if you use normal convert the normally this array that will improve your runtime as i don't know like in using a stream will take more time in lit code compiler so just we you can also do this like with the very basic approach so into num in nums and store this into the copyless start add the num once is done we will store lets submit give a submit again for this so this will be faster than the previous one so this is like you can see 100 percent faster than all the java solution now what is the ah what is the like time space complexity of this solution time and space complexity so as we saw in the tree in our this permutation tree so we will have total and factorial permutation and for each we are this we are copying from here in arrays to the list so that will be n times so this the time complexity of this solution will become so the time complexity is o of n into n factorial and the space complexity is so space complexity is off and factorial so that's it so you can also try other backtracking problem which i have already published the video solution on my channel and you can find in the all the important top interview question in the top interview playlist so that's it if you like the solution hit the like button and subscribe to my channel thanks for watching | Permutations | permutations | Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Example 2:**
**Input:** nums = \[0,1\]
**Output:** \[\[0,1\],\[1,0\]\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= nums.length <= 6`
* `-10 <= nums[i] <= 10`
* All the integers of `nums` are **unique**. | null | Array,Backtracking | Medium | 31,47,60,77 |
847 | hey everybody this is Larry this is me doing attempting day 17 of the legal daily challenge hit the like button hit the Subscribe button drop me on Discord let me know what you think about today's problem is going to be 8 47. uh shortest path visiting or notes this seems like a short platform is the name let's take a look uh you give an undirected connected graph of endnotes label from zero two and minus one you're given in a way graph where graph survives a list of all nodes connecting connected with node I by an edge we turn the link with the shortest path that visit every note oh okay that is actually not the path that oh not the problem you may start and stop it and you know you may revisit notes multiple time and you may reuse edges okay so you have a graph uh I thought it'd be a little bit maybe interesting but n is going to be equal to 12 and N is equal to 12 means that they're probably some like you know 12 factorials a little bit too slow but n times two to the N which is 12 times 2 to the 12 will be fast enough so something like that some sort of bid Mass dynamic programming is where the hints at I actually thought that there may be a better thing for it oh wait did I misunderstood oh it's listening oh no so this is okay well I think I misread this due to this problem or this thing um I think you have to raise it every Edge in that case it'll be some sort of oily and path or Lillian psycho or something like this and don't the thing with that one is you know it is polynomial right um but and I guess we did something similar recently but if it was it all notes then it's a little bit different because um because now basically this is uh depending how the problem is structured uh it's either you know tsp travel salesperson or hempath hamiltonian path hamiltonian psycho well that doesn't have to be in cycle in this case but yeah something like that but and you know uh the common part about all those things and I just misread it a little bit is that they're all NP plus right I say NP plus just because I'm a little bit lazy I always forget where hempath is in um NP or MP complete uh for me it doesn't really matter uh or whether it is um yeah I always forget whether it's an MP computer or whatever but I mean it's exponential I think is the point that I'm trying to make which of course is going to be hard enough and what that means is that uh there are two things right in general for NP problems uh one is uh you know once you the ability to recognize the MP problem is that you stop looking for well a polynomial solution right uh or if you do then maybe you'll be world famous or uh you know maybe there's some constraints that you can exploit that makes it not MP maybe there's like a um you know like one random rule in the problem that is like oh it's this but you can do this one thing and then like okay well this one thing changes everything it's not an NP anymore right uh and yeah and then in real life what you would end up actually doing is uh kind of well the couple of things a lot of things you can do but I think the couple things that are off my head one is just looking for an approximation algorithm so in that case you know you'll try to find an algorithm that uh you can maybe prove is within certain percentage of the optimal uh especially in this particular mtsp like there's a such a thing of course um or you may you know look at the you know like try to figure out their additional constraints or looking for properties within a certain input that you can exploit right like maybe for whatever reason like you realize that 80 of your input is by parti or something like this right I don't know and then in that case you can solve 80 of your things like your real life data set may be useful or maybe you notice that the graph is plainer or something like this right some sort of property that you can play around with and kind of uh you know make a special case for and maybe you can solve them in a piecewise me or something like this in any case that's a lot of talk but yeah knowing that this is an MP means that we don't really try to find something better than that uh NP uh of course in this case you can do dynamic programming and given that two to the N or n times two to the N where n is 12 is fast enough we can kind of just get started and of course the way that we're gonna do this is with is such a fancy word if you haven't done been masked before uh I'll do a great brief intro but I think it's very intimate it can be intimidating to say and see all these like funky symbols for the first time but it's not that bad I promise you uh okay you know it's understandable I believe in you uh but yeah um so let's say we want to write a Brute Force right how would we kind of write this so the way that I would just write it is like the 12 factorial way where I go from zero then one then zero two like you know just all the permutations right so yeah so maybe we can do something like uh what are we supposed to return the length of the shortest path okay um a couple of ways you can do it but I think like for start in range of n uh you know maybe best as you go to some Infinity right so best is you're gonna men a best and then calculate from the start and then return fast right something like this uh and maybe you know we were writing before us maybe we have a scene thing uh where you know scene as you go to force times n or something like this right uh I'm gonna write it to Brute Force way a little bit first I mean just to kind of you know you could skip ahead if you already thank you all you know what I'm gonna do but you know uh yeah so then now um to the current node and then you have the scene away and then the idea is pretty straightforward it should be um uh it's structured like oh what did I do record graphs of current so for that's the next node we can yeah uh we can calculate you know same thing expressing infinity and then we turn it up we can do a calculate on WE and then scene right and then maybe like scene of v as you go to true and this is if you need to go to four something like this and then press is equal to Min best uh This plus one because we took an edge or something like this right so a couple of ways you can write this as well or even optimize even this but that's the really straight core part of um of writing it in a Brute Force kind of way right uh quite right because there's no base case and you can kind of go back and forth I am aware of these things but that's kind of like the most basic um way to kind of write just like a proof first like we said before this is a book first and this will never terminate just because you can go back and forth um and also we don't have a base case so base case is something like or scene is uh so it's actually good enough we've all seen them we return zero right meaning that we've visited every node then we return zero we're gonna run it will never finish I don't think oh well they'll never even start apparently but even assuming all the syntax is correct they'll never finish right uh oh actually a little surprise we're not that surprised because uh yeah probably only a thousand but yeah it goes it's too much of a recursion depth and if you let it'll probably even go even more uh and you'll always run out of Stack space eventually uh yeah okay first thing to note uh what are we doing man uh first optimization step um one thing that we can do here is you know we go back and forth from notes we already seen so how do we skip notes that we've seen before well if we want to skip the notes that we've seen before then we can just do something like this right if not seen of me then we do this but this is not gonna work either because or by itself it doesn't work because like we have example one where you want the zero to go to two and then back up right you there's no path at least the way that we've written it there's no path going from one zero and then two and then three directly or it's not as given so maybe one thing that you can do and there are different ways to tackle this but the way that I'm going to tackle this form is just write the shortest path thing right uh so yeah so what I mean is that now I'm creating all pair shortest path there's only n oh there's only 12 or n is equal to 12 number of notes so 12 squares n Square you know that's enough to do anything really so yeah so let's get to that but so let's just say infinity times n for to do right uh yeah and you know maybe you can do something with the base case like if I is equal to zero something like this and then now we can also go through the list uh so for I and range of N I guess we already have that Loop right uh for we in graph of I um D of IV is equal to D of v i is equal to one right I think it yeah it shouldn't matter whether we do it I mean it's a symmetric thing right so that now we have the one distance away thing and here I'm just gonna you know uh there are a couple of ways you can do the all pair shortest path I'm just going to write it with um Floyd shows algorithm right and dfij is gonna mean of the ik DFI okay I'm not gonna go over this point too much to be frank uh you know they're different ways to do it yeah can I type uh definitely looked that up and Googled it up or whatever uh as you need so then now we can actually get this to you know be a little bit correct in that instead of you know now going from current to V we can just do D of current unique right and you know and now we don't have to do dupes so that's good right uh maybe in theory anyway yeah actually don't know why this is Infinity hmm uh I think they should I mean this Pro will still timeout for energy go to 12 but it should be okay for these inputs to be frank so I'm trying to think what did that there is something silly which is probably possible and yeah uh well I didn't do scene of starters to go to true so I guess that's one thing but where am I doing this I mean I know that this is infinity but dude um did I mess something up let me clearly but okay so the this array is fine well then why does this work huh I did forget this part though but hmm okay what is going on um this has never hit maybe misunderstood it should always be possible um I'm being dumb sorry uh I did uh okay I made a modification for this but that also means that this is no longer true because these are only um one distance away edges so now we have to do something uh we have to change this to going from zero to n all together okay there we go uh and yeah and like I said this is gonna be n factorio uh which is fine up to like seven or eight or something like this right maybe even I don't remember what the numbers but 12 is getting it over tight what is 12 factorial is 479 million actually maybe in some languages it'll fight it'll be okay maybe I don't even think that's true but right away now we have to do something called uh well I mean and this is you know uh at this point we have to do some memorization note that every time we you know we call this if we give it the same input we expect the same output and that is basically the only condition for memoization really no side effects no uh no weird things and that would allow us to do it so how do we memorize this well current can go from zero to n so that part is easy so to n minus one scene is just basically a brilliant away of you know and what and uh pulling away of n values right and so this is where the bed mask stuff comes in um you can kind of see how I did it with the uh with the Boolean away but you know what is a brilliant away well but in a way you could think of it as like just ftftm you know like force and True Values and if you can't convert these Force Through values to zero and ones so f for zero T is uh one so you could kind of uh you know you could convert them to Binary values and instead and now instead of an array of um in a way of bits you can just condense them into one number um and that's basically a bit best right every other operation will do together but uh but this is basically the logic of how what it looks like and yeah and because of this and now we can think about it with NYU is how many possible distinct values there are well each one of them could be have two values and there's n of them so it's two times two dot which is also two to the N so that means that total number of inputs is O of n times two to the n um and each input takes both end times is the way that we did it so that means that total is actually going to be total time there's going to be o of N squared times to the N so I was off by n actually whoops in Total Space though would be n times to the N but uh that's pretty much the idea but just to kind of make a little compact and you can actually at least in pipeline you can actually use like a frozen array or something like this maybe I made that up but you could definitely memorize on this thing already if you really want to you have to be a little bit careful about you know a race because you want to uh memoize not the memory address which may be the thing with cash I don't know so yeah um and for this and for particular uh this for this particular video I'm gonna just try something funky uh and kind of just keep it the same and then just change the memorization function right so good current and the scene fine uh like hopefully this is understandable so far this is wayproof force um you know top down kind of thing right and then now we just have to basically has uh same thing that I always do at least on these videos just to kind of um you know uh just could kind of visualize a little bit better um both the space and their usage right so here now if we're seeing we return zero that's fine otherwise uh let's see what do we want to do right otherwise we have to see if has cash right of current and scene but of course scene cannot you know seen as in a way it's not a number so we just have to convert it to a binary number right so yeah maybe we have a helper function right or something like this but uh and maybe we store it I don't keep calling it right maybe BC for by now foreign of course we have to write the two binary function and you can write it to Binary function in a number of ways as long as you're consistent about it right so for example now we can say for me and scene um cone we shift by one so we multiply by two or and then we added uh if V is true then we add it by one or something like this right uh and that's pretty much it really uh yeah I'm gonna give us uh I'm gonna give some I mean the idea is gonna be right it's just like I'm worried a little bit about uh typos and such but I'll actually give some it and very well but we could fix it yeah and that's pretty much it 12 65 day streak um yeah I mean the timing is a little bit well but that's fine um yeah I think with these kind of problems uh hopefully the way that I Illustrated you know uh you know maybe another way of doing bit mask uh DP right to show what big Mass DP is it doesn't have to be intimidating uh but yeah um that's all I have for this one I think one I would also say is that um you know over the years if you have been following my Channel or server or whatever and you see me do bitmashdp um I've kind of done it in a number of different ways and you know uh I think that's and I don't know I don't if it sounds like a brag you could skip it's not really meant to be but what I want to showcase is not even just like me bragging but or me saying that like you know this is the kind of understanding that I always try to teach is not like memorizing code or memorizing you know big Mass DP and be like oh yeah it's been Mass DP always do this right like uh it's about different you know ways of visualization different ways of coding um you know there's a lot of different things and yeah certain ways will be more um optimal but you know getting to that point and you know being able to get that point and really have that understanding to kind of make changes along the way it's gonna be the real difference when it comes to tougher problems that are a little bit more difficult this one's okay though uh but yeah anyway that's all I have for this one that's all I have for this problem let me know what you think if you're doing a contest in an hour and a half or so good luck uh wish me good luck uh but yeah stay good stay healthy take your mental health I'll see y'all later and take care bye | Shortest Path Visiting All Nodes | shortest-path-visiting-all-nodes | You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge.
Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.
**Example 1:**
**Input:** graph = \[\[1,2,3\],\[0\],\[0\],\[0\]\]
**Output:** 4
**Explanation:** One possible path is \[1,0,2,0,3\]
**Example 2:**
**Input:** graph = \[\[1\],\[0,2,4\],\[1,3,4\],\[2\],\[1,2\]\]
**Output:** 4
**Explanation:** One possible path is \[0,1,4,2,3\]
**Constraints:**
* `n == graph.length`
* `1 <= n <= 12`
* `0 <= graph[i].length < n`
* `graph[i]` does not contain `i`.
* If `graph[a]` contains `b`, then `graph[b]` contains `a`.
* The input graph is always connected. | null | null | Hard | null |
273 | today we're gonna be working on read quote question number 273 uh anterior to english words convert a non-negative integer num to convert a non-negative integer num to convert a non-negative integer num to its english words representation so the num is equal to 1 2 3 which is going to be 123. this number is going to be 12 345 and this one is 1 million two hundred thirty four thousand five hundred sixty seven so in this class we're going to be uh declaring few like the hard coded values these are the uh this is going to be like an uh an array so we're gonna say private final string array we're gonna call it less than 20. it's just gonna be an array having all the numbers below 20 which is nothing and then one two three four five six seven eight nine ten and we're gonna go all the way up to 20 less than 20 so it's gonna be we're just gonna keep it up to 19. okay eleven 12 13 14 15 16 17 18 and 19. and still we are not done yet because we're gonna have ups we're gonna have two more of such variables now one for covering all the tens and one for covering all the thousands so um private final string and for the tens we're just gonna quarter turns empty 10 20 30 40 50 60 70. eighty ninety okay the last one is for the thousand and it's only three some kinds of thousands we're gonna cover as like it's gonna be less than a billion so okay so for that one we're gonna say private final string thousands which is going to be again an array that the first element is empty the second one is going to be thousand then a million and then a billion that should be enough okay once we have that the logic is very simple it's like if the num is equal to zero we're gonna be saying that return zero right that is just a conditional like if we are in that condition we're going to be returning zero we're gonna initialize our i equals to zero and we're gonna initialize our answer uh word equals to an empty string once we initialize it we're gonna look keep looking at the number while the number is greater than zero we're gonna keep processing it otherwise we're just gonna return the num sorry word um dot words let's just call it words dot trim i should do it okay and once we still have our number like it is greater than zero first thing we want to check if the number if we take the modulus of the number by 1000 right uh if that thing is not equal to zero meaning if it is uh like oh that means like if it is not like that if we take the modulus by 1000 and the answer is not equal to zero right the answer is gonna be the answer is only going to be 0 when the number is less than is it's going to be less than 1 000. if it is greater than 0 all we need to do is like uh all we need to do is like divide it by a thousand and just keep an eye on our eye we're gonna keep incrementing and i so other than that the only time we're gonna process it is when the number will become less than uh a thousand right when the model is when you take the modulus i'm sorry when the number modulus doesn't mean that if it is not equal to zero it doesn't mean that uh like it does not mean that it is less than one thousand or greater than one thousand all it means is it's not completely divisible by one thousand so if it isn't completely divisible if it becomes equal to zero right that means if it is completely divisible by 1000 and we're going to keep increment or we're going to keep dividing it by 1 000 and keep an eye on i like keep incrementing the i if it is not completely divisible by one thousand we're gonna take now we're gonna make sure we do two things the words is gonna become equal to we're gonna use a helper function in order to uh like calculate anything less than like 100 sorry anything so we take the modulus of that and we send it to the helper function and the helper function is basically gonna be uh looking for two things one is the like what's the uh what's the mo like where does it stand for anything less than 20 and anything less than tens and uh like basically it's gonna go through all of it and then it's gonna like it's gonna go through all of the all of these variables and see which ones we're going to be using right that helper function is going to just give you for the first thousand so we'll say we're gonna once it comes out we're gonna make use of this thousands of i plus we're gonna put some space in it and plus the words so every single time what we are trying to do is to process it but in the end we are actually appending the new strings at the beginning so we process the first 1000 and then divided by 1000 right and then just remove that last uh least significant three least significant bits and then we process the next uh next three significant bits and then significant digits and then that's how we keep doing it until it becomes equal to less than zero equals or less than zero so the last thing we want to do is to implement that function public string helper and num okay so for that the base condition is going to be if the num becomes equal to zero that is the case just return empty string if it is not but the number is less than 20 then we're gonna oops and then we're gonna be just returning the this less than 20 array and like a num plus some empty space um like uh plus a space so we're gonna append it that's better than else if the num is less than 100 so we're gonna be recursively calling this helper function for that uh first thing we're gonna be doing is return then half num divided by 10 plus a space plus the helper function for the number modulus 100 oh sorry 10. and the last thing we're gonna do exactly the same for the thousands for that we're gonna say return less than 20 num divided by 100 plus helper function num modulus 100 so basically we are processing two things here one is like less than 20 and less than 100 so only two of the uh these final string arrays are used in the helper function less than 20 intense all the thousands processing is done in the main loop okay let's give it a try so we are missing a space somewhere i think the space is missing over here looking good so far and it works | Integer to English Words | integer-to-english-words | Convert a non-negative integer `num` to its English words representation.
**Example 1:**
**Input:** num = 123
**Output:** "One Hundred Twenty Three "
**Example 2:**
**Input:** num = 12345
**Output:** "Twelve Thousand Three Hundred Forty Five "
**Example 3:**
**Input:** num = 1234567
**Output:** "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven "
**Constraints:**
* `0 <= num <= 231 - 1` | Did you see a pattern in dividing the number into chunk of words? For example, 123 and 123000. Group the number by thousands (3 digits). You can write a helper function that takes a number less than 1000 and convert just that chunk to words. There are many edge cases. What are some good test cases? Does your code work with input such as 0? Or 1000010? (middle chunk is zero and should not be printed out) | Math,String,Recursion | Hard | 12 |
63 | question 63 the code unique path two so you're given an m by n integer array grid there is a robot initially located at the top left corner the robot tries to move to the bottom right corner the robot can only move either down or right at any point in time an obstacle in space are marked as one or zero respectively in the grid a path that the robot takes cannot include any square that is an obstacle return the number of possible unique paths that the robot can take to reach the bottom right corner the test cases are generated so that the answer will be less than or equal to 2 times 10 to the power of 9. so this question is just an adaptation of unique paths 1 but in this question we have an obstacle which we need to take into consideration so in this first example we have an output of two where the first path is all the way across to the right and all the way down and the second possible solution is down and then right all over paths include this obstacle here and as it states in the question if any path includes the obstacle do not include it in your output so let's dive into the solution to this question so with this question just like unique past one we're going to be utilizing dynamic programming and what dynamic programming does is it builds upon sub-problems so it has overlapping sub-problems so it has overlapping sub-problems so it has overlapping sub problems in the question we need to find all possible unique paths and that should be a good indicator that we will be using dynamic programming so right here we have the grid array we have the start the finish and an obstacle here and then this is going to be the dp array and what we'll do is we'll initialize every single value within this dp array to zero okay so this is the starting point so what do we need with dynamic programming we need some base cases in order to start populating this dp array we're going to need some kind of base to work with and with unique paths and unique paths too it includes the first rows and the first columns so what we need to do is we need to loop through the first column and we need to decide whether there are any obstacles in there and we can populate this dp array with that value so we know that we can reach this value because there's no obstacle there we know we can reach this value and this value so there's one way to get to each of the columns in the initial row and then let's loop through the rows in the grid to see whether there is an obstacle we have an obstacle here right so this value stays at zero and then we break from this loop so we do not check this initial row value here we just keep that at zero which we initialized the dp array to so now we have carried out the section outside of this and we've created that base to work with so we have created the solutions to previous sub problems and what we're going to do with dp or dynamic programming is we're going to use the solutions to those problems to work out the rest of the values so how many possible ways are there to get to this value well there's one from here and there's zero from here because that's an obstacle so we can just add those together so one plus zero is equal to one how many ways are there to get to this value here well we have one from above which we calculated previously and we have one from the left which we just calculated so that is going to be equal to two how many ways can we get to this value down here well we only have one from above because we didn't check the value on the left because there was an obstacle up here so we can add that into there and then finally so the value for this last one is going to be the summation of the potential solutions or the potential paths to the cell above and to the cell at the left so that is going to be equal to three and then we can just return this value so time complexity for this solution is going to be o m times n where m is the number of rows and n is the number of columns and then space complexity is also going to be o m times m because we are utilizing a dp grid array here so let's code this out so let's get the obstacle grid.length let's get the obstacle grid zero dot length so the columns and then let's create this dp array and we're going to initialize this array with zeros so like we said in the solution let's loop through the rows and let's check to see if the value within the cell so obstacle grid at i zero so we're looping through the right here is equal to one so if it's equal to an obstacle let's set dp at i zero equal to zero so because there is an obstacle within the grid we're going to set the value at dp to zero because there is no potential way to get to this and this is a really important part because if we don't break here we're going to loop through to the next row and we're going to check that value and if there's no obstacle in there it's going to populate the cell with one so we need to break out of this loop and because we have initialized the dp array with zero up here the next row within this is automatically going to be set to zero else what we can do is we can set dp at i0 equal to 1. so if there isn't an obstacle there is a path so we can add that into the dp array and then we need to do the same for the columns so remember it's the columns so we're going to be looping through and checking obstacle grid 0 and changing the column value so j in this case and we're going to be setting dp at zero j equal to zero remember to break otherwise we'll set dp at zero j to one because there is a potential path so that is the base of this dp solution sorted so we have filled the initial rows in the initial columns now we just need to populate the rest of the dp array grid so we can loop through i starting at position 1 because we've already filled in the values at index 0. look through j as well so if obstacle grid at i j is equal to one so if it is an obstacle we just set dp at i j equal to zero because there are no potential powers there else we calculate the recurrence relation so dpij is going to be equal to i minus 1 j so the cell above plus dp i j minus 1 which is going to be the value to the left then we just need to return the last value within the dp array grid okay let's give that a go okay let's submit it and there you have it | Unique Paths II | unique-paths-ii | You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle.
Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The testcases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** 2
**Explanation:** There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
**Example 2:**
**Input:** obstacleGrid = \[\[0,1\],\[0,0\]\]
**Output:** 1
**Constraints:**
* `m == obstacleGrid.length`
* `n == obstacleGrid[i].length`
* `1 <= m, n <= 100`
* `obstacleGrid[i][j]` is `0` or `1`. | The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0 | Array,Dynamic Programming,Matrix | Medium | 62,1022 |
460 | Peace be upon you, my dear friend. What are you doing? I hope you will be fine and in the best condition. God willing, we will solve the problem together today. Today, if you have not tried the problem, as usual, you must switch to it first before you watch the video. Give yourself some rest at this time, tomorrow, the problem, and try to understand it, and try to write the code or You think of an idea and then write the code. If you tried, you wouldn't know. Let's start. In the name of God, he will tell you that it's called and it's called "Kit." Or let's say, for example, that you now have, for example, will tell you that it's called and it's called "Kit." Or let's say, for example, that you now have, for example, will tell you that it's called and it's called "Kit." Or let's say, for example, that you now have, for example, a memory in which your house is completely fine, and you have cash. This cash will remain faster than the memory, but it will remain. Less space. Today, there are four places like this in the cash. The first place is in, for example, Kilo Value, or Study, and here, for example, Zero, One, Two, Three. The place is 0123. This is FIFA today, for example, X, ABC, and CD. Okay, in order like this. My hand uses it the most and I use it the most, but After, after the verse, and the C is my father, and so on. Now, if I want to enter “ A,” for example, “D,” I want to A,” for example, “D,” I want to A,” for example, “D,” I want to enter it in the cash register, what will happen if I want to use it, then enter it first in the cash register? It is better. I take out the “A,” and “B,” and “C,” better. I take out the “A,” and “B,” and “C,” better. I take out the “A,” and “B,” and “C,” and “D.” Why, okay? and “D.” Why, okay? and “D.” Why, okay? I came to use the verse once again until I started using it larger than the C. At that time, I would put the C under the hand, so the verse would remain fine, so when I come, for example, a new one. Something new, so he entered the prison place, and again, if I kept using CC until it came up above the verse and the verse went down at that time, the verse would come out, even though it was the one used the most, but I didn't why let him do what I should do, so the usage would remain hers. I mean, for example, I used it, that's it, three times, that's it. Twice, I came and said, “ three times, that's it. Twice, I came and said, “ three times, that's it. Twice, I came and said, “ By God, the operation is coming up, I need to call for my hand. Finish, add its usage to a cell of six, and for example, I used it the next time, and it will be okay. I used it again once, and there will be five days left. This is going up, and this one is going under, and so on. I am using something, so I supply my Frequency every time.” I do not use it in any operation, and I say that every time.” I do not use it in any operation, and I say that every time.” I do not use it in any operation, and I say that I used it, so I provide the difference from the priority to the lower, the priority to the higher, the priority increases. Okay, and when I come to enter new data in the lowest, I use it, so I take it out of the cache. Okay, okay. This is an idea. Ok, what do you have in your hands? The first thing in your hands is cholesterol that passes through the cache that we were using. Here are 4 places. Okay. After that, Capricorn will give you a cake. The cake is supposed to be ducks. Okay, based on today's complex, my medal, so it's supposed to be me. I mean Okay. In the first example with us, Okay. The first thing he told you is what type of constructor, and after that, what happens? Send two. And three of mine are exactly two, so I have crazy people like that. The first one was the second one, Al-Aqsa evidence, something that I first one was the second one, Al-Aqsa evidence, something that I first one was the second one, Al-Aqsa evidence, something that I could store in the detector. After that, he told you what happened when he made the cash bot. There were two places in it, one place remained in one place, and the second place, the first place remained in one place, and the second place remained in one place. The second one remained empty, perfectly fine. After that, he said to you again, Monday, and her team had two, so the cash was now full by two, one was full, and their counter was full, and the one they were using alone brought the three bots, so when you made a bottle of three, your cash was supposed to be full by now. Okay, when Please tell me what happened. I am supposed to remove either the one or the two. Ok, you will finish one of them. I will remove the two. The one I will remove is the two, because the two are more. I mean, I worked for the two, and the one also does. I deleted it because my cup was two, but two numbers, but okay, it remains the same. What should I do second to the first and what should I do first? I have two places in the cash register, which is the first place and the second place. After that, what should I do for the two? There will be two. One is Syrian. Okay. So when I came to make the three bouquets, what happened? Either I remove this one and put three in his place. Okay, this one and put in his place. Three, so I will have the lowest fricon, so I will put three in its place, and her video is 3. If I come to do it, I will come to the two again. What will happen to the two? It is no longer available. I have two places, but where is it in the cash, so either one or three, the two are not there, so it is returned to a minus one. He expresses half of it, and you go ahead and remain as you are, and this is the first example. Ok, something like this. How do you do the first thing we did in the code? The first thing I told him, by God, is that I have two buttons. My pain is in Value and Frequency, and its place is in the last. Ok, I want to say One thing before I explain the code is how we have our idea in the first place. Before we explain the code, we will say what our idea is. Our idea is that we have something called cash. Okay. So, we are supposed to have this cash. It has a few places depending on the pressure. Okay, and we have another thing called a sweet friquency. Okay, now I am storing in the cash register what is the value, meaning everything is nice, his bathtub is 3 fine, and I am storing with me what is, for example, one with ironing. Three is fine. This is nice, meaning that I want this friconciy to be there as well. I mean, I am here if you look at the code. You will find it written, “ Okay, okay.” Okay, okay.” Okay, okay.” I said, for example, I entered on Wednesday, and her Frequences are one so far. I mean, my consultations will be based on this place. Okay, okay. I’m doing what I’m doing now. When I do it, you brought me the three. What will change? I will my consultations will be based on this place. Okay, okay. I’m doing what I’m doing now. When I do it, you brought me the three. What will change? I will my consultations will be based on this place. Okay, okay. I’m doing what I’m doing now. When I do it, you brought me the three. What will change? I will return her value, which is yours. Three of yours is okay, but there’s something. The Frequency will increase okay, but there’s something. The Frequency will increase okay, but there’s something. The Frequency will increase because I used it more than once, so I change the Frequency and it will remain at two times. Okay. After I change the Frequency, I tell him, “No, tell him, “No, tell him, “No, wait.” As long as I change the Frequency, then I will change two things. The place is still here at two, and we said this represents Nancy’s team carrying it. What is the number 4 on it? Of course it will be erased from above. Okay. It will be the second. The first thing is this video, and this is a review here. Sory, I made a mistake. This is supposed to be four. Okay. Beautiful. Okay, if this is if I make a bot. Okay. If I do this, what happens? The same thing happens. I said that I when I made a woman change the fricon, which is the two, so that she would let him marry her as she was, I provided her with the two, and after I provided her with the two, I changed the one, I removed the three from here, put them in the two fricon, and said to the pointer, I let him consult on the three, ok, this is the one that is the boot and the dry, ok, if I want Delete it completely by deleting the problem of the lowest value or the lowest Frequency. Ok, I will know how to roll the Requency. I will go to the Frequency, which is four. The one that is Syrian is one of them. This is supposed to be correct. Ok, it is not. One of them will tell me, ok, maybe this one will no longer be available. It is assumed that I am already full of cash and want to delete from it before. The new tagline will not be published, so what will happen is that I will go to the lowest value and find it, which is the one that is the thousand requinti. What will I do? I will find this four in it. The ironing is fine, so I will go to the LLL cash register and wipe the place from it. This four are completely fine. I will wipe it and remove it from here and change the aluminum fricons from One thing remains, this is what we will do. You will understand more if you do not understand the code. Ok, the first thing I did was this pen. You are ours. It will remain in a video that will be consulted on its place. This is a subscription to it. This represents what this represents. This expresses what it expresses about ironing. Okay. This represents the cake and its video will be stored in it. Three things, the value and the frequency are fine, and you want the one that is a pointer to his place in the frequence, ok, this is for the first one. Okay, Pasha, number three is stored in it. How many kilograms are stored in the bathtub here? It will be about his fricons. This is the frequence. This is the second one, which is the cash that is stored. It has my real elements, which are our main ones, and the value will be three things. The value in which the verse is stored is fine. As for the team, Nancy the Fulani, who is number three, will tell me your bag is such and such. Their Frequencies are three. What is the first thing I will do with a premention? What is this constructor? He will do anything except that I will take this capsule that you will store in the capsule that I made above here, which is fine, but it is like that for her people, but he prefers that we write it here. I may have forgotten to write it, but he prefers that we just answer it. If you write it down, it will pass. I mean, after that, you will take the key. I am supposed to return, either with one negative note. If that is the case, you have not counted on it before that. Either the one inside will come back. You will return, or you will return one negative note if this key is not in the cash register or it is in the checklist at that time. I returned it, fine. Here, what did I do? The first thing I said to my cash was that I counted this cake by checking it for the amount that was in the cash, or if it was there, it would be returned to us. True, if it was not there, it would return us money in front of the money. I mean, if it was not there, it would return Fault 2 via the note, and it would come back at that time as negative one. This means This iron of yours is not in the cache right now. Well, we assume that there is an existing type that continues to complete normally, so what will happen? I said, “By God, I normally, so what will happen? I said, “By God, I am going now. I am supposed to take this Frequency and remove the plot from the Frequency. I mean, when I agreed with you now, we will remain the boss or say it is not okay, so I am.” I will go to the Frequency with the iron on the cash. I mean, now I will go to the first army. Okay. I will tell him that my iron is, for example, three. Here, it stores three things. Okay. What do I want to do with it? I want to go to the first to the cash register and get your second Frequency from it because the cash stores three things in it. Valeo and Frequency needs. I need to completely remove the kidney that I want to do. I came to this one that is there. What am I supposed to do with it? I am supposed to move it from Frequency 3 to Frequency 4. That is right. I mean, now if I have a key, let’s set a I mean, now if I have a key, let’s set a I mean, now if I have a key, let’s set a better example than this if. I now have a regular cash register, which is fine. I will assume that our cash register, for example, has a set of three, while his Palio is 3, and his Frequency is two, fine. Certainly, as long as it is two, he will continue to consult on the second place here, which is two, then whatever happens, it will be stored here in the Frequency, not It has the number three. My cash has the number three, so I say, I swear to God, what is cash dot com is three, and he tells me that it is there. He will return under circumstances. He will continue. I mean, he will not enter the end at that time. What will happen? I need now before I return the video to him that is here. I mean, he is supposed to return two to him. I return it to him, but before I return it to him, I'm supposed to change your phone, Syrian. This is fine. I'm supposed to want to go back to the video, which is three. Okay. I took the two. I mean, I'll replace the whole place of this talk with two. So, I'll be free in the two that this place is. Okay. What's up? What will happen is Dot IT, which is, give me the cash, and in the K, which is the three, and in the A, I.T., which is the place of his, which is this. This is a nice place. This is the in the A, I.T., which is the place of his, which is this. This is a nice place. This is the three, I am supposed to delete it. This means that it is not the same in three, and in numbers other than the three, so I am the I.T. A consultation other than the three, so I am the I.T. A consultation other than the three, so I am the I.T. A consultation on the place of the three in the studio, and Okay, and a consultation on the place of the three, and I go to erase the three, he delete it, that is because he told me, boss, so I said, the three erasing is nice, so I finished this line, okay, after I finished the line, Syrian, it is nice, what do I want to do? I will go to the place three here in What is this, I put the verse in it, which is the three, so I went to see if it is the frikonis of the new frikonis, which I still changed two, it became three, or remains three, it does not have the three, which is fine, and after that, change the verse to your tritur, the one who is peshawar here, it is not he who was peshawar here, this one is no longer there. He is there because he is holding on to erase what will happen. I want to leave him instead. He was consulting here. He is not consulting about the three. In this place, he is consulting about the three. This list will happen. How did you tell him about your examination? What is the plan behind his I.T.? He he is consulting about the three. This list will happen. How did you tell him about your examination? What is the plan behind his I.T.? He he is consulting about the three. This list will happen. How did you tell him about your examination? What is the plan behind his I.T.? He made him consult about me. The preface is still working with a pushback. I don't have it. I didn't make a pushback. If the last place is in three, the Peshawar is next to the last one. Okay. Give me his preface, which is the three. Where is the safe in the next one? So, it's like I'm telling him to go and take a shower on the three like that. Okay. After that, I'll say it. I swear to God that the German from Frequency Plus Syrian is good. There, at that time, I will say that my sperm is fine, and after that, after I finished these operations, I went to the cash and in the ironing Total, fine, I do some things that are supposed to return his property, and if he is not there, it will return negative one, but in the half that I am supposed to do. A few calculations. What are the calculations? The first thing I need to remove are the three from her current Frequency. I don't have a Frequency. For example, it used to have three, so these three inside are supposed to not have all the bag that they had in three. Okay, now I made a new query in my Frequency. You will know that for three, there will actually be four left. I should delete it. From here, I will go and put it with him. Ok, if I delete it is not that I am supposed to go and look for it, and then it will take time. That's why I'm storing her alter, which is her place, so I will go straight away and tell him to delete such-and-such place for me, okay. So delete such-and-such place for me, okay. So delete such-and-such place for me, okay. So when I told them under such-and-such place, that's it, I when I told them under such-and-such place, that's it, I when I told them under such-and-such place, that's it, I deleted it, okay? Okay, give me the new place, which is at the end of the studio. Okay, and see what I deleted. Is it still empty or not? If it is still empty, then my toilet is supposed to increase by one. Well, if it is not empty, then it is not empty. What do you do? Other than that, go back to the video, just to get the video back. That's about it. Ok, what should I do if we are Syrian? I do n't know how to draw seconds. The first thing I have is the cash that is supposed to be at three, for example, as we agreed at three, and her freebies are four. So I need to go to place number four, and it will be a shower at place 3D in India. Fine, fine. I'm supposed to first see what these thousands mean. If my capsi is zero, I won't be able to add. I don't know how to add anything. Okay. I mean, I don't know how to add any value. Okay. Then, Okay. The first thing is Okay. Okay. I mean, I'm going to go now and get his video. mean, I don't know how to add any value. Okay. Then, Okay. The first thing is Okay. Okay. I mean, I'm going to go now and get his video. mean, I don't know how to add any value. Okay. Then, Okay. The first thing is Okay. Okay. I mean, I'm going to go now and get his video. For example, he wants me to leave these three with 6, for example, so I go and delete the three and put six in their place. Someone will tell me for a few seconds, “ and put six in their place. Someone will tell me for a few seconds, “ You are not supposed to set the frequency. This is not considered queer. This will be provided to you, Frequency. You are like that.” It means that I will go and delete it from here from all this talk, and we did. What will you do in each verse? This art itself will do. It will go and tell us that I, by God Almighty, have such and such example with three. For example, these three frikones have four. What will happen? As we explained, these four will increase. There will be five left and they will be deleted from here and put here. This item will be discussed here. Right, okay then. It won't come back to us, but after he returns home, okay, then what do I really need to do for Abbott? If this value is available, I think it's there, so I'm supposed to change its fricons and change the iterator, okay. Delete it, I mean, from here and put it here and consult about what's new, right, and after that I change it. Okay, I want. The first two have done a function. I don't need to do them. The second one will be better. I can change the video. It works. Nice, nice. It's not here. The problem will start. What is the problem? I have two things. The first thing is that it's not there at all. There are still empty places in the cache. Or it's not there and it's not there. I have empty places in the army. Ok, I will post a conversation about it that is worth the maximum I can get to it. I opened it, I am full of everything else, so I need to do what to take an empty place, a right place, and an empty place, which place is less frictional, so I stood up and told him, by God, the cash for the fricony, which is an aluminum fricony. Give me the rest. It's fine. It's nice. Delete it for me from the cash. I'm assuming that it's, for example, how many four. I'm looking around the army at the place of four. That's it. I'm going to delete it from where. It's nice. I'm still deleting it from the army. So, where will I remove it from my soul? It's fine. It's okay. As for the cash. Cash. The first place it is saved will be where you will put the value and free content. It will remain in one and the other will be in the same position. There is nothing less than that. Okay, okay, then we say The The The second bot is like this on the fast bot. What am I doing? I will see if I press zero, then I am done. It is not okay. I will be able to put anything in the cash right away and it won't happen forever and nothing will happen. It's fine if I come to do two things. If it's a negative one like this, she told me that this one does n't exist. Okay, if it's a second number other than a negative one, I mean, it's not a negative one. What did you do? The first benefit is that she made me know that it was not a single negative. Ok, the second benefit is that she provided me with his fricones and edited the fricones and the cup for me. Okay. So, I am not empty, except that I am editing the video, so I edited the video. I made a retrieval. Okay, we assumed that it was him. It turned out to be negative one. If you are new to me, new at that time, what will I do? I have two cases in this place. The first episode is that this is me or Syrian. The cash is either there is no empty space, or there is no empty space. Okay, okay. After that, we assume. After that, I will put the video up. The new one that will remain in the new value is one new value and its iterator will be set and everything. If it is in an empty place, it will not be afraid. If it is in an empty place, it will be fine. If it is in an empty place, it will not be afraid. In the end, it will be fine. Finish this video. You give an example like this and walk away. You can draw one by one with your hand as I drew the Quraish like this and walk one by one. But if you do that, the time of the video has already reached 40 minutes, so it will be very long. You have the gates that happen in this, it takes one size or, and in the summer of the cover, one perfect, and here you have one cloak and this one in one. And this is one and this is one, then you have the new one, or in Suez, it is not perfect and zero, you can say that it is full, and in Upper Egypt, for the people you are looking for, spread one, what will it be? It is not nice, it is not nice, this cash dot is one, because it is the cash, this is a hashtag, and this is also one, the front is one. The internet is one, the pushback is one, this one is one, and this one is one, so you can consider their free charge as off 1. So we are the same as we are in the question: You need to make an off 1 we are in the question: You need to make an off 1 we are in the question: You need to make an off 1 release. He told you that if you feel like you have not understood a little, you can repeat the video again, or it is possible, and this is better, that you answer with an example. This is exactly the same as the one above, for example, this is the first thing the bot tells you to go to the bot's funk and take the one, and the other, and draw the rest of the cash like this, and draw the frequences like this, and let him consult, and these words will make you understand more, God willing, and examples will make you understand more, and sending this code will make you understand more. Can you write to me in the comments? God willing, I will continue to see the comments. But I will see you, God willing. I will see you next time, God willing. All will be well. Peace be upon you. | LFU Cache | lfu-cache | Design and implement a data structure for a [Least Frequently Used (LFU)](https://en.wikipedia.org/wiki/Least_frequently_used) cache.
Implement the `LFUCache` class:
* `LFUCache(int capacity)` Initializes the object with the `capacity` of the data structure.
* `int get(int key)` Gets the value of the `key` if the `key` exists in the cache. Otherwise, returns `-1`.
* `void put(int key, int value)` Update the value of the `key` if present, or inserts the `key` if not already present. When the cache reaches its `capacity`, it should invalidate and remove the **least frequently used** key before inserting a new item. For this problem, when there is a **tie** (i.e., two or more keys with the same frequency), the **least recently used** `key` would be invalidated.
To determine the least frequently used key, a **use counter** is maintained for each key in the cache. The key with the smallest **use counter** is the least frequently used key.
When a key is first inserted into the cache, its **use counter** is set to `1` (due to the `put` operation). The **use counter** for a key in the cache is incremented either a `get` or `put` operation is called on it.
The functions `get` and `put` must each run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "LFUCache ", "put ", "put ", "get ", "put ", "get ", "get ", "put ", "get ", "get ", "get "\]
\[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[3\], \[4, 4\], \[1\], \[3\], \[4\]\]
**Output**
\[null, null, null, 1, null, -1, 3, null, -1, 3, 4\]
**Explanation**
// cnt(x) = the use counter for key x
// cache=\[\] will show the last used order for tiebreakers (leftmost element is most recent)
LFUCache lfu = new LFUCache(2);
lfu.put(1, 1); // cache=\[1,\_\], cnt(1)=1
lfu.put(2, 2); // cache=\[2,1\], cnt(2)=1, cnt(1)=1
lfu.get(1); // return 1
// cache=\[1,2\], cnt(2)=1, cnt(1)=2
lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.
// cache=\[3,1\], cnt(3)=1, cnt(1)=2
lfu.get(2); // return -1 (not found)
lfu.get(3); // return 3
// cache=\[3,1\], cnt(3)=2, cnt(1)=2
lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.
// cache=\[4,3\], cnt(4)=1, cnt(3)=2
lfu.get(1); // return -1 (not found)
lfu.get(3); // return 3
// cache=\[3,4\], cnt(4)=1, cnt(3)=3
lfu.get(4); // return 4
// cache=\[4,3\], cnt(4)=2, cnt(3)=3
**Constraints:**
* `1 <= capacity <= 104`
* `0 <= key <= 105`
* `0 <= value <= 109`
* At most `2 * 105` calls will be made to `get` and `put`. | null | Hash Table,Linked List,Design,Doubly-Linked List | Hard | 146,588 |
1,675 | Hello everyone, so today we will do division, the problem is that we have given the end of positive integers and we can perform two operations on it. What are the two types of operations we can perform that if the element is and then we can perform it. We can divide by tu means like this is 4 emails then we divided it by 2 to get tu and if the element is OD then multiply tu means if it is OD then from tu like if it is 1st or 3rd order then we can convert it into 6 or 2. Now it is said that the division of D is the maximum difference between other elements, which is the maximum difference between other elements present in this means that the maximum difference of any two elements is said. Okay, and what we have to get is the minimum division. Means we have to perform this operation and find out the minimum possible division. Okay - - - maximum - minimum element. maximum - minimum element. maximum - minimum element. Maximum possible equal or approximately minimum element. Now in the question we have two operations which are and if any element is our and. Okay, if any element is ours and then what can we do with it, we can do it by you, okay, this was ours, now look at one thing, we still talked about that means we cannot increase, so we can take our minimum. If we want to increase, okay, then what will we do, as soon as our first thing, what will be our approach that like this is our okay, this van, what will be the maximum possible value of all these elements, what will be the maximum possible value of four, no, four of four has become four. What will happen to three? If three comes then what is its maximum possible? Now this means that we cannot make the maximum value of any element more than this and what we had to do was to increase the minimum. So what will we do? We have found out the maximum value of all these. Took and we will take a minimum of them, ca n't they increase more than me, so the minimum has reached till now, just like you are here, your minimum has reached here, now what can we do, minimum can't do anything, what can we do with the maximum? Now because the whole number is and, these are all the numbers, okay, and we can further decrease the number, we know this much and we write the number, so this is our element, now our division is how much is 6. - 2 Decrease Ca n't ever Ours is the same Then we are ahead Gradually Ghat is happening Meaning Arey's Still What is the minimum maximum value Three Audition Kitna Aa Gaya 3 - 2 1 Division Three Audition Kitna Aa Gaya 3 - 2 1 Division Three Audition Kitna Aa Gaya 3 - 2 1 Division Ours Aa Gaya Van Division Can Because we cannot further decrease more elements because if there is any more element then we can multiply it by 3, this means our further increase will be three and for the maximum element, we have to make a decrease division. If we want a minimum then we cannot do anything less than this, as soon as our maximum amendment is changed, our loop will be terminated and the value of our division will be our minimum possible. You must have understood, again let me tell you first of all what I said. We did this, we took the error and told what it means, what can be the maximum possible values that if the number can be the maximum possible values that if the number can be the maximum possible values that if the number is and because after and, we cannot increase it, we have to decrease it, so we multiplied 1 by 2. So it was done, we converted all the numbers and converted it to the maximum value, now we had to increase the minimum, so we calculated the maximum possible values, after that we stored the minimum element from AD. After this, now we plan the maximum and we have to decrease the maximum because if there is a saree element then there will be a decrease also, so we have to check that, so we have taken a maximum, in the maxip we have entered this saree element which is our first maximum element, here we stored the division. And I saw that I can further decrease this element or not and it has decreased, we again put it in hit and always keep checking this, that means it is minimum of add, so we compared that and then went ahead till then. This will continue until one more element is reached which is on our top and if the element is reached then it means that we cannot do the degree, that is our minimum possible which will store the minimum value [laughter] so we have to name it with the name Namaskar. I will store the meditation and it is done for 1 minute, we have to leave from here, we have to leave, then we will check after leaving. | 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 |
396 | hi so this question is rotate function so you are giving the integer numbers array and then you want to rotate the nodes by K position clockwise so you define the rotate function so this is the formula and then you want to return the maximum of value F of 0 f of one all the way until F of n minus 1. so uh let's look at this so I'm just using this example right so you will have to have a coefficient in front of every single num side so this is going to be what zero times four plus one times three plus two times two plus three times six and then you will sum every all of the multiplication up and then you again the value of 25 so let's just swap what swap the num's eye to ABC so the coefficient is going to be still the same so all of zero times a plus 1 times B plus 2 times C plus three times d right they are the same 0 times a 1 times B right 2 times C plus 3 times d right so what happened to F of one you want to rotate what clockwise so zero will be what at a d position right so it's going to be Zero D right so Zero D right and then what clockwise so it's going to be about one times four so one times four imagine sorry not imagine look at this one or one times above one uh four is uh a right so one a Plus 2B Plus 3C and then plus right so let's do one more F of two so we in this one which one is a zero it's going to be here and C 0 C right one d right one D q a and three e I so this is like f of zero f of one F of two and then using a b c d uh to represent so let's do a little bit math so imagine F of one minus F of zero so what do you get 1n minus zero a one day right plus 2B minus one b right plus so we see minus two c one C plus zero D minus 3D negative 3D right all right so let's not uh over yet look at this I'm going to do some magic so 1A is still going to be the same one B this is still send one C still going to be the same so if I add another 1D over here does that mean I need to say subtract 4D right oh and make it wrong over here so if I add one d right here I need to subtract 1D again in the same equation right so what does a plus b plus C plus d is what the sum of the nums right so sum or equal to a plus b plus C plus d so let's replace some over here and then minus 40 for this equation right all right so we have minus 40 right here right so let's look at F of 2. so I'm just using another color so what does f of 2 minus F of 1 so this is f of 1 minus F of zero right so we got this so let's still get F of 2 minus F of 1. so 2N minus 1A Plus 3B minus 2B from B Plus zero C minus 3C negative 3C and then plus 1D minus zero D One D all right so it's still going to do some magic let me write this clearly so I'm going to say a oh sorry this should be equal sign let's move on here A plus b plus if I add another C I need to subtract another C right so I'm going to just write plus d here and then I will say minus 4 C am I right so I just double check a I use it B I use it D I use it see I use it right so minus 3 C minus C is going to be minus 4C right so again this will be what this will be the sum right so sum minus 4C equal to F2 minus F1 all right so if you know the pattern uh let's move over here so if you know a pattern F of one minus F of zero this is equal to sum minus 40. F of 2 minus F of one it's going to be sum minus 4C and then if you can guess the pattern F of 3 minus F of 2 this is going to be sum minus 4B last but not least forever four minus F of one so do we have F of 4 uh a b c uh it looked like we have it right with e actually we don't have ever fall this is biggest one we only have four uh nums value in the numps array so this will be what this will be a pattern and if you can move minus uh minus F of zero onto the right side it's gonna be plus F of zero right and then minus F of Y is going to be plus F of one minus F2 is going to be plus F of 2. so F of 1 is equal to F of 0 plus sum minus 40 right so for every single iteration once we find out the F of zero and then also the sum right and then T is given y this is a e c t if D is given then we don't need to calculate right so we need to calculate for the sum we need to calculate F of zero right and F of zero is super straightforward what does f of zero represent zero a plus one B plus two c plus three b d sorry all right so we need to keep added keep up updating for every single uh h of f of I right so it will be in the full for sure right all right so let's just stop holding so what I have is what I will have some people to watch the nums sum and I'm sorry sum right so this is a sum straightforward now and then I have if initial is starting from zero right and then I need to service a photo in the num sorry and the F will be equal to 1 plus equal to I times right so this is going to be 0 a 1B 2C 3D right and then I need to return the maximum value okay so I would say Okay F of 0 is going to be represent the maximum for now right and then I will Traverse the entire uh four iteration right F of 0 to F of three right but since F of 1 minus F of zero is equal to sum minus 40. so if you know D this is the last element in the nums array right so we need to starting from the last all the way to I equal to one we don't need to Traverse I equal to zero this is represent what we already calculated F of zero right so we don't need to calculate F of zero again but if you're one you can do it but I'm not doing this so it's going to be ever num side minus one and then you have the greater equal then one and I minus so uh straightforward enough and then for every single time I need to keep updating my math result right so this is going to be represent the maximum Uh current maximum value for f of 0 f of one all the way to F of n minus one so if you still remember the formula this is going to be what sum plus F of zero in this case this is f of one right F of one equal to sum plus F of zero minus the length which is four right four is representing the length of the nums uh length of nums times the current d right you need to times d right so um in this one is three D right and then you need to calculate that half the next iteration F again right again this is a formula for f right if you still remember F of 1 is going to be equal to sum plus F of 0 minus the three right this is three times and then this is going to be c p a and for every single each iteration later on so I'm gonna just say run it so here we go says look at the time in space for a second this is the time and then obviously right all the fun and then space this is space so it's constant so that's pretty much it right so let's just try to use a debug mode and then to see what just happened and yeah all right pause the video at any second and then you see uh the result right so 25 represent F of one zero right if you can remember F of zero right so now I'm going to Traverse so look at this is going to be the maximum of f here we go so we just finished and if you still have caution leave a comment below and then subscribe if you want it so peace out bye | Rotate Function | rotate-function | You are given an integer array `nums` of length `n`.
Assume `arrk` to be an array obtained by rotating `nums` by `k` positions clock-wise. We define the **rotation function** `F` on `nums` as follow:
* `F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].`
Return _the maximum value of_ `F(0), F(1), ..., F(n-1)`.
The test cases are generated so that the answer fits in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[4,3,2,6\]
**Output:** 26
**Explanation:**
F(0) = (0 \* 4) + (1 \* 3) + (2 \* 2) + (3 \* 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 \* 6) + (1 \* 4) + (2 \* 3) + (3 \* 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 \* 2) + (1 \* 6) + (2 \* 4) + (3 \* 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 \* 3) + (1 \* 2) + (2 \* 6) + (3 \* 4) = 0 + 2 + 12 + 12 = 26
So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
**Example 2:**
**Input:** nums = \[100\]
**Output:** 0
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `-100 <= nums[i] <= 100` | null | Array,Math,Dynamic Programming | Medium | null |
437 | in this video we're going to take a look at a lethal problem called paths on number three so in this video i'm just going to show you how we can do this in a n squared time complexity as well as a linear time complexity and basically the question is that we're given a binary tree and we want to find uh we want to find the number path that has a sum that is equal to the given sum and the thing is that we can have a sum where we can have a path that star that does not have to start from the root and it also does not have to end at the relief node and if the path must travel downwards we can have negative value in the node we can also have a positive value in the node so basically uh you can see here we give an example where we have a binary tree so we have uh in this case we have three we're returning three there are three paths right one is we can do five plus three the other one is uh five plus two plus one the other one is negative three plus eleven which also gave us the sum of eight so in this case we are um we're returning three because they're total three paths so how can we do this well what we can do is it's very similar to the path number one capstone number two right we can traverse using that first we can traverse the trees in that first search and uh we're gonna have a list of elements that were traversed in our list right all the elements that were traversing the list uh are all the elements that we traverse so far we're going to put them in the list if we were to backtrack we will remove that element off the list and then we're just going to basically for each and every single um iteration right for each every single node that we traversed we're just going to do a reverse traversal like a reverse iteration to find the sum that has we're trying to have a trying to find a sum that is equal to target sum right basically if we were traverse right we're going to have a let's put a commons there so let me just demonstrate to you how we can do this using n square time complexity um right basically we're starting from the um starting with a empty list right so we passed in with an empty list and the target sum is eight right so first when we get to the first level right we have uh 10 right we add 10 onto it then we know that 10 does not equal eight then we just continue traverse the left reverse the right so we're doing that for search so we're going to focus on the left first so that we have five then what we're going to do is we're going to start to iterating starting from the last element to the first element in the list so 5 does not uh so far the sum is five plus 15 it does not equal eight so we're just going to continue do that first search now we have three right so we have three here and basically what we're going to do is we're just going to have a we're just going to iterating backwards and getting the sum so we have 3 plus 5 is 8. so now we just basically found a path that has a sum that is equal to eight we just increment the counter by one then we continue that we have 18 which does not equal to eight so then we're just going to terminate right so after we do that we're just going to continue to um go deeper right we have three here right we're going from here right we're going that first search we're traversing from to the left first so now we have three plus three is six that's not equal to eight then we have eleven twenty one right so then we are on the leaf node uh in this case then we're gonna start to do backtracking then we're going to remove the last element off the list and now we're going to a different path we're going to negative two right so we have negative two we know that negative two plus three is one plus five which is six plus 10 is 16 so far didn't really match so we backtrack right so we backtrack um back to the root which is three so then basically what we're going to do is we're going to backtrack because we exhaust all the options for three now we backtrack to five and then five we have another path which in this case we have two right so in this case we're going down the right side so now we have two so two plus five is seven right we're traversing we're iterating uh reverse or reverse order so now we have two plus five uh does not equal to eight so continue two plus uh 5 plus 10 in this case is 17 so that's not equal to 8 so we're just going to continue to go down the right side because the left side is null and we have one right so now we have 8 right we have 8 here and then we just increment the counter by one but you get an idea right basically we're just have a list that we're just going to keep track that we're gonna pass down and then try to iterate starting from the last element to the first element to get the sum if our current sum is equal to target sum then we just increment the counter by one otherwise we're just going to and then we're just going to traverse the left side do that for search for the left side and then do that for search right side and then after come back we want to remove that we want to remove the last element that we add added on to the list and then we're just going to continuously do that until we traverse each and every single node in our um in our binary tree right so in this case what we're going to do is we're just going to have a basically have a deferred search method right dfs it takes the root node and it also has a list empty list so far like at the beginning we have an empty list and we also going to have a we're going to make the target sum in a global variable so that i don't have to pass that in every single time and then after we're also going to have a counter which is a global variable so if we found a sum that has equal to the target sum then we're just going to increment the count by one at the end the goal is we want to return the counter right so dfs is just there to traverse the tree what we really want to return is the counter right so that's basically the idea of it so now let's try to implement the dfs method which takes a tree node and as well as a list of integer which basically contains all the nodes value that we traverse right so in this case the current list and then basically the base case here is that if we found the root is null then we can just return right so if root is null we can just return okay so that's our base case right so if root is null we can just stop searching uh down this path and then what we're gonna do is we're just going to first get the um get the current note value added onto our list right and then we're just going to so first we're going to add a current node's value onto the list onto a list then we traverse then we iterate the list backwards to get the current sum right so if the current sum so let's say the current sum is equal to target then we're just going to target some that we saved on in a global variable then we're just going to increment that by one you can run the counter by one i should say then what we're going to do is we're going to uh traverse the left side right we're gonna after we iterating all the elements that we have on our list we're gonna traverse the left side towards the right side so traverse left traverse right and at the end when we when they coming back to this current level we're just going to remove the last element so remove the current element current node's value of the list right so those are the steps that we're going to write so basically add the current notes value onto a list basically it's pretty simple so let's add root.value right so adding the current root.value right so adding the current root.value right so adding the current notes value onto our list then we're going to start to iterate but first we're going to have a counter right so the current sum is zero we're starting to iterate starting from the last element so it's gonna be list dot size minus one i is bigger than or equal to zero so i minus so what we're gonna do is we're gonna iterate uh the list backwards and try to get the current cell right so um in this case current sum plus equal to let's get i which gets the current element so we're gonna uh get the current sum which is we're basically updating our current sum and then if the current sum is equal to target we're just going to increment the counter by one so counter plus right and then at the end what we're going to do is we're going to traverse focus on traversing the left so we're going to do a dfs rule.left so we're going to do a dfs rule.left so we're going to do a dfs rule.left and then the list current list that we have right and then we're going to do a dfs that right i'm gonna pass in the current list that we have after they're done they're coming back to this level we want to make sure we remove the current notes value off the list so it's going to be list remove list.size minus one list.size minus one list.size minus one okay pretty simple uh now let's try to run the code and let's try to submit so as you can see it takes uh it's only five percent right so in this case because this solution give us the n square time complexity so what we need to do is we need to focus on how we can be able to improve this time uh solution down to a linear time complexity by using a hashmap so let's take a look at how we can do that to solve this problem using a linear time complexity um we're going to use something called prefix up so a couple of videos ago i made a video called leeco 560. in that video i talked about how we can use a prefix sum to solve a problem to reduce the time complexity down to a linear uh init array basically the prefix sum is there to get the sum of a sub array between i and j right it's between a um between a specific um index to a specific index in the array right so we can be able to do that using a hash table using a hash map so how can we solve this current problem so to solve this problem what we need to do is let's say we have 10 5 and 3 right so let's say we have a tree node 10 5 and 3. so what we need to do is we can use a hash table right just like how we talked about in the 560 lego problem we're just going to have a hash map with zero right zero is basically the prefix sum by default in this case uh prefix sum of zero appear once and uh what we're gonna do is we're going to have 10. so the target sum in this case is eight right so target sum is eight in this case 10 has a prefix sum of 10 right so the sum of the current node uh current sub node right subtree in this case just this node right here has a sum of 10. so in this case we say 10 up here once right this is the prefix sum and this is how many times that prefix sum appeared we're just going to get the current prefix sum right remember 10 is the prefix sum of this element right here so we're just going to get the 10 the prefix sum minus 8 the target sum we want to see if two contains in the hash table in this case we don't right so we don't have a prefix sum like we don't have a prefix sum of two in the table so we did not have a previous sum of two then we move on to the next node in this case we have 15 right so the prefix sum of this node is going to be 15 so we're just going to have 15 which appear once and then we also have a perfect sum of 18 but 15 minus the target sum which is seven does not have it in the table so we're just going to move on to the next iteration the next node now we have 18 which only appear once so in this case we have 18 right 18 minus 8 it's target sum is equal to 10 is the prefix sum we know that 10 exists in the table so we're just going to uh increment the counter by one because we found a path it makes sense because we have five and three here right so basically the goal is we want to store the prefix sum in our table and uh if we have the c if we get a current notes prefix sum minus the target sum we want to see if the if that difference right the prefix sum container table if it does that means we have a path that means we have a node that has a prefix sum that is equal to that right so let's say we have something like this right we have and the target sum is going to be negative one now we have to um like we have to do the same thing right so in this case one so zero and one so we do the same thing so no one has a prefix sum of one so then we're just going to get the prefix song for this album right here which is one right one appear once so the prefix sum of this element is one minus this element we get two do we see two in the table in this case we don't so we continue going down the left side right so in this case we have left side uh we have negative two and uh now we have negative two but the perfect sum for this element is going to be negative two plus one which is going to be negative one and appear once so this is where this zero right this element right here come into play so basically we have previous sum of negative one minus the target sum which is negative one which give us zero and do we see zero in our table in this case we do because uh for at the beginning we have a prefix sum of zero the current sum we when we before we start it was zero so zero appear once right so in this case we have zero there in this case we're just going to um increment the counter by one and then we're going to start a backtrack right we're going to move on to the next uh path so we have to delete this element uh if we don't delete it if we go back to a different path right then we have negative three has a prefix sum of negative uh yeah basically negative two um in this case negative two minus negative one has a pre um has a has a prefix sum of negative one and we see that negative one is appeared in table so that does that will not give us a correct answer so what we need to do is we need to before we backtrack right before we backtrack to the root node we have to delete or not delete but like decrement it decrement this element by one if this element is equal to one we can just delete it in our off our table so that we're not getting the incorrect answer right so those are the coordinate cases that we considered let's take a look at how we can do this in code so to do this in code uh basically i delete some of the our code our existing code and we're just going to add a hash table right a hash table uh hash map there and the key is going to be the prefix sum and the value is going to be how many times that prefix sum appear so we're just going to pass in the um zero because in this case the current prefix sum is zero right and we also have to have a hashmap.put hashmap.put hashmap.put zero up here once so the prefix sum for zero appear once right so that's basically the uh the general idea of our main function so let's define our dfs so this is the current sum right the current sum uh in this case what we're going to do is same thing we're going to have our base case so if root is null we're just going to return and then what we're going to do is we're just going to update uh current sum right because we're now at the different level we're just going to add the current sum uh add uh current sum is equal to current sum plus the root of value then after we update our current sum right we're just going to um check to see if this current uh we're just going to get the uh we're just going to see if the hash table contains current sum minus the target sum right check if current sum minus target exists in the table if it does we're just going to increment the counter based on the hashmap.get current sum minus target hashmap.get current sum minus target hashmap.get current sum minus target right and uh then what we're going to do is we're going to start to traverse the left side right traverse the left side and we also have the traverse the right side but before that we also have to do something very important we have to make sure that we're getting the currents on we have to update the table with our current sum our current cell right and then after we're done traversing the left and the right we're going to remove the current sum of the table okay pretty simple so let's start to implement this in code and basically we're updating the current sum so current sum plus equal to real value and the current sum basically check c if hash map dot contains key current sum minus target so if it is then we know that we have a path in your table so we're just going to increment the counter based on how many times that prefix uh current that's that prefix sum appear in our table or in our tree so hashmap dot get current sum minus target right and then we're just going to start to update our table now with our current sum so in this case if hashmap dot put hash map documents sorry current sum right in this case there could be a situation where this current sum already appeared in our table so we want to make sure that um that hashmap git right so hashmap dot gets sorry git gets or default current sum plus one okay once we update our table we traverse left to right dfs root dot left we're gonna pass in the current sum right we already update our current soft so dfs the left side the right side and now the most interesting part is to delete the current sum of the table and basically if we found that the current sum right so hashmap get current sum is equal to one we can just delete that element off of the um table otherwise we're just going to say hashmap dot put current sum hash map dot get current sum right minus one we're just going to decrement the time slip here by one so basically that's just the idea of the code and uh let's try to run the code okay let's try to submit and here to see we have a six set so this is how we solve this problem using a linear time complexity by using a prefix sum using a hash table | Path Sum III | path-sum-iii | Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
**Example 1:**
**Input:** root = \[10,5,-3,3,2,null,11,3,-2,null,1\], targetSum = 8
**Output:** 3
**Explanation:** The paths that sum to 8 are shown.
**Example 2:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22
**Output:** 3
**Constraints:**
* The number of nodes in the tree is in the range `[0, 1000]`.
* `-109 <= Node.val <= 109`
* `-1000 <= targetSum <= 1000` | null | Tree,Depth-First Search,Binary Tree | Medium | 112,113,666,687 |
476 | Ki Welcome Everyone Today In This Video Bihar Ko * Solid Code Is Question And The Question Is Ko * Solid Code Is Question And The Question Is Ko * Solid Code Is Question And The Question Is Number Complaint In This Question Will Be Given And Enters In Important Where To Written And Judgment Is So Ki Sapoch Bhi Hai And Input S5 Subah Hai 2012 Flat Like 101 will be the banerjee representation for 5 This diabetic patient who is the digits in the representation of nine days to return the number of sleeping mother in 200 Answer will be id ok so basically but you can think of that you can convert deposit in it Pimentel St And You Can Sleep Obs In You Can Calculate The Recent Years By Converting Balance Representation To Decimal Form But This Process Will Much Less Than Two Years Ago We Used To Operator Which You Can Find On Your Keyboard 6 Long Something Like This Key And What is and operator basically which raw two same numbers will be 2000 but or of different number one can find another number subscribe will tell you how to find the number one five we can do it is the representation of that ific force with all weapons with inputs But without the roof i one spoil basically one will be slip 2010 will be clip 212 david morning using that roadways vacancy lipid calculators number two how to calculate this number i morning from for the country number is the number of but seervi you the number 24 For joron 5 in this number will be an answer okay so let's ride download and a superstar for what will need this in a oil declare half long and I answer is vansh and that reach and face name is 110 boil phone par afan This is trying to calculate number of birds and according to that I am trying to calculate a answer ok so by the way that country number will be bluetooth race to the power number of birds phone number of the bits has click here vihar-3 so what Will be the has click here vihar-3 so what Will be the has click here vihar-3 so what Will be the tourist to the power then will be 98 but will be one 0f sector-21 format will get this the but will be one 0f sector-21 format will get this the students and time train tourists to the power number of birds minus one ok so let's go back to the co dog show the wild The world you and multiply an answer film to is time basically in calculating power that n that i will divide android oil subscribe only android one and it should avoid to ok to equal to that married wedding by to ok sleep nowhere calculated tourist co power number of But reduced by this vansh n every answer will be a roar off if input thanks 157 ok so let's try running state that cassette knowledge was submitted ok hai so aaj disawar number complement problem-solving jor can be pretty woman problem-solving jor can be pretty woman problem-solving jor can be pretty woman After the times so thank you so much and figures in next video bye-bye | Number Complement | number-complement | The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.
* For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`.
Given an integer `num`, return _its complement_.
**Example 1:**
**Input:** num = 5
**Output:** 2
**Explanation:** The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
**Example 2:**
**Input:** num = 1
**Output:** 0
**Explanation:** The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
**Constraints:**
* `1 <= num < 231`
**Note:** This question is the same as 1009: [https://leetcode.com/problems/complement-of-base-10-integer/](https://leetcode.com/problems/complement-of-base-10-integer/) | null | Bit Manipulation | Easy | null |
144 | hi today we're solving this code number 144 binary tree periodic traversal and basically we are given a root node of a binary tree and we're supposed to travel seeds uh using the pre-order method and seeds uh using the pre-order method and seeds uh using the pre-order method and this is an easiest problem and the only problem the only hiccup for this particular problem is just the fact that in the follow-up it asks us to solve it in the follow-up it asks us to solve it in the follow-up it asks us to solve it iteratively as opposed to solving it recursively and that's what the solution we're actually going to be showing today so basically when you have the root node in this case root node here is one and you are trying to Traverse it by using the pre-order method it means they using the pre-order method it means they using the pre-order method it means they are going to be getting the leftmost number or let me spoke to you or leftmost node rather on the binary tree or you can't go any left then you go right so for instance here we have one and then the leftmost part of one is not expecting to nonsense there's no other um number there and then we have a shoe by the right then two on the left has three but on the right it has no so if there's no number attached to his friend let's assume that the next number there is no right so um in this particular case first of all we print the root node at this point which is one that's correct and then after painting the root node we try to print the leftmost node at this point level slope is null so we don't print that right so we move to the right most one instead and we print the rightmost node which is now currently the roots so we print two and then after printing to we're supposed to print the leftmost node at this point and at this point that's straight so we print three and uh and because three at this point does not have like a leftmost node and also doesn't have like a right nose node so we move back to two and two also doesn't have like a writing smooth as well so that's it ends there so that's basically if we don't have like a node let's just return like an empty array as well so let's actually get on to solving this for the solution I'm proposing we're going to use a stack right so let's assume that this is actually the question the problem we are trying to solve by this example right here and for the root node of course we have one and then in our stack we start with one obviously now when we get the value at node right we get the rightmost value first I don't get the rightmost value we add we change that we take this the value out of this stack and replace it with the value in the rightmost part while we're going to start with the right mode before the left mode this is because when we're going to be taking it out of the stack we want to get the left first before we get the right so to take no in this instance and then as we put in law in this instance and then the next one is going to be two right now that we have to I know of course now output we're going to have one already saved here right now when we pop up this next value at this point the next value is going to be 2. so when we take off two we're going to take off two we have two here right now we have to replace this two that we've taken now with the rightmost value now at this point two does not have any rightmost value so it's just going to be null right and then we have the leftmost then we try to get the leftmost value of it that's this dot left of this particular node so which is at this point is straight so now that we're done with this we can just put this through in our output as well now that I've done that we have we don't have um we don't have any meaning values to go back into our stack right now I'm going back into our stack we get the last one last value at this point which is straight now when we get three reject if it has left me if it has rightmost value it doesn't have right nose value objective translated then it does not have left value so we just put string inside there just put three inside there and since it um let's actually get to solving it I think that when we actually when you actually see me try to implement it to understand a little bit more what I'm trying to say so you have to order Driver cell access for them to declare our variables of course in which case we output you against an entirely and then what I'm going to work on at the end once we turn out then once you check for some things price stands for where is for like instances where we don't have anything uh mcre right now we're going to of course I forgot that you said you are going to use a start to start this way here this video now because of the fact that there isn't a start to represent this it means that our space complexity is going to be of all it's going to be o of n because in this case every single value is going to go into every single value in this tree is going to go into the stack right and then uh time complexity is going to be o of n as well because we're going to run through every single item in the tree right so like you said earlier I'm going to be starting with the rules now as far as the stock links zero you just want this right so that's basically so what we'll be doing here and the first place is that I just have we're going to declare the node which is just going to be only pop off this is transforming the last 10 out of the stack at every point and then when we take this off you just have to check if this note that if it's not more right if it's up now then we just push the value inside output here and then 11 with that because we want to oh we're done with that like I said we're going to take the leftmost right first of all we'll take the right most value right and push it into this stack so we're going to push in and left so that's why we have to pop in we get the left face before we get the right I hope that makes sense that's it that's what Solutions is oh I'm so sorry but I've been stacked up the push stop it here we are pushing the value in the node let's run that again yep and then now we can submit our solution and um yeah that's it and because of factorizing Stack our memory doing this so well but our runtime is better than 96 percent of the submissions um so yeah that's how you solve that please don't forget to like And subscribe and come back soon bye | Binary Tree Preorder Traversal | binary-tree-preorder-traversal | Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,2,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively? | null | Stack,Tree,Depth-First Search,Binary Tree | Easy | 94,255,775 |
1,248 | See, in this video we will see lead code 1 2 4 8 In the previous video, we had asked a question, the question was sub ars sum = I told you that when the restrictions which are there become = I told you that when the restrictions which are there become = I told you that when the restrictions which are there become strict on all ars, okay then the old sliding window which we approach was they don't do that okay we did that in this the prefix even okay the prefix even that we did that in this and has you used in okay that's a good thing now we have a question 1248 count number of nice sabridge good is speaking to you There will be a wait, there will be an error and there will be a life. You have to find out the sabri which has exactly odd numbers. Now see here also the restrictions have been stated exactly and it has become strict. Okay, so like we did the last problem, we will do this problem in the same way. Okay, it is saying that exactly the odd numbers should be reverse, good in your morning, like here in front of you, there are exactly three odd numbers in it. Okay, as you will see now, this is one, there are three more numbers in this, there are 11 and there is only one in this. Three and number one, there is no one else, see, this is not this is also not this, and one Puri, and this is not this, we are doing this too. Do you understand, so what will we do like we did in the previous problem, see. This is how we do it, if you have not seen the previous question, then see it, okay, it is very important, your eyes will be opened, so what did I take, RS, what will be our result and we will return it in the end, okay. What do we take? Let me tell you, let's take a variable which will keep the count of how many odd numbers have been added till this number. I call it current like in the previous question we prefix how much till this number. How much percentage I was putting till here in time and current, in this way what will we do here, how many votes till here, how many votes from here, okay, so how can we make it 4 inches, okay, name forint i numbers here But I will keep adding to the current plus it is equal tu i modulo you now look at it like this, what does it mean that if that number is even then it will add zero, if it is odd then it will add one to it, okay and this Okay, we will store it also, okay, and we will also store the current, brother, okay, we will store the value of one current, which is okay, brother, see how many times two odd numbers have come. And how many numbers have you killed, came here and came here, okay, that's why two and two, okay, if it has come twice, then I store it, I am okay, I lie down depending on the first, okay and I would dot pat. Is the current okay? What will you put in the current? So take the value of the old one plus one. At this time, I am here. Okay, on this one, the old one, you have come once and here you have come twice. Okay, so map dot. If he had already got gate and defaulter, then what was that value. Okay, if the current is not there, then zero and plus one are okay, brother, so we are storing this thing in the map, one more number has come once, okay two odd. How many times have the numbers come, one and the number have come once, okay race, how many times have the numbers come, twice, like this, how many times have the numbers come, once, do the odd numbers, how many times have they come, do the times, sorry, come once. Okay brother, our map has been made, now you will see that K = 3, this is ours, now you will see that K = 3, this is ours, now you will see that K = 3, this is ours, how can we do it, please pay attention, if okay, now we saw in the last video that I now give one dal in dot pat zero, okay i.e. K is a prefix, even okay i.e. K is a prefix, even okay i.e. K is a prefix, even prefix and whatever is there must have been zero. Okay, K = 3, so let's see the example, K = 3, so let's see the example, K = 3, so let's see the example, look at this one, look carefully at this one, okay, what is here, this is our answer because there are three more numbers in it, okay. And even if we have this current, then let's say by doing this, it's okay, what else is up to this, it's three, okay, so if you pay attention, if someone is doing more with the key and number like here. Okay, so that's okay, that's the mines and mines will exist in our map. Okay, like what's here 3 - 3 0 has existed. like what's here 3 - 3 0 has existed. like what's here 3 - 3 0 has existed. Okay, let's take another example like this. Mother, I am here at this moment. Okay, I am here, okay, no problem, if there is any sub error here, okay, here and doing it, then doing minus three, what will exist in our map or in Israel, okay, so what is it, here is one a There has been one time, there has been one time, okay, so what will we do here, we are yes plus this is equal to map dot get and see the defaulter, I had studied in depth in the last question, that is why here I am doing it quickly. And by default, if mines had come then how many times they had come, we will keep adding them, okay, this is it, let's remove this one, it is accepted, I submit, okay, time complexity is big of others and space too. Pick off and submit, okay, that's good, you will get the link to the next video, starting | Count Number of Nice Subarrays | binary-tree-coloring-game | Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it.
Return _the number of **nice** sub-arrays_.
**Example 1:**
**Input:** nums = \[1,1,2,1,1\], k = 3
**Output:** 2
**Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] and \[1,2,1,1\].
**Example 2:**
**Input:** nums = \[2,4,6\], k = 1
**Output:** 0
**Explanation:** There is no odd numbers in the array.
**Example 3:**
**Input:** nums = \[2,2,2,1,2,2,1,2,2,2\], k = 2
**Output:** 16
**Constraints:**
* `1 <= nums.length <= 50000`
* `1 <= nums[i] <= 10^5`
* `1 <= k <= nums.length` | The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x? | Tree,Depth-First Search,Binary Tree | Medium | null |
215 | So in this video the problem of soil is the test element against quality of Africa and so in this brings your energy in the tenets and number of dry is basically a number which we want to return from direct which is the largest number presented here so let's Ban Sri Lanka Only Nikalna Bulk Rajesh Number Three Se Limit Third Largest Element Of Second Plant 3D 400 How To Prove His Point For The Basic Approach Will Be Sorted Different Sources Of Sexual And Effective On How Should You Can Return Time Tax Credit So Let's See How We Can do something so let's get started in descending order something like 6532 and world want to return like and share number's element which you want to return person minus one index is okay so if I want to short in ascending order one 's good luck r the element Which you want to 's good luck r the element Which you want to 's good luck r the element Which you want to return with me and midcap index like RNA 6 and this three sued in 3D from this 0123 alerts for is the largest third statement from this approach cooperative and went to consider using and taylor swift not very often solution free consider and rubs seed different se z900 gift veer vs triple Will Be Scent Back Slow 210 Hit The Root Of Alarm Liquid Will Always Be Smallest Element Which Will Present And Scent It All Its Population Have Benefited From Active Voice Alarm Distant Places For Giving Dark And Bloody Mary Celeste One And Logistics 800m G Temple Also Always Present Chairman Time Any one topic Must be reserved Right up to top 10 How they can stop this A few hints only 10 search operations are involved Which time Can always protect The citizenship for mini And you can find a small age limit Period that in darkness in tight Wally bank where Is Simrely Information And Action Operation Is Midnight Sach Log In Time For This Is The Time Complexity Of Operations Happy To Receive Phone How They Can Be Started Constructing Is White Is I Will Release Patience 3215 Six Inch And West's Is Three Left Side Of Directors Tablet Upaya Not Exist For Why This Way Small For Example Giver That 13 Subir Vibes Should Problem Adding All The Elements Of Obscuritism Sanjay Vyas Travel Through The Worst In The How To Do Lagi Formation In Find Nothing But Na Dhari Arrangement Of Elements Of Yogic That sagotra to of turmeric and cost will consider only number of film indian army co 108 ambulance first sweet shop alstom and indicative price and 2001 solve world will put this in itself something like this sochna pathak etc names 2.2018 difficult expensive and etc names 2.2018 difficult expensive and etc names 2.2018 difficult expensive and daddy come dot 202 side Effect Step Wise First Question Second Step Three Love And Approved And Researchers Have Not Even Suhaagsays Prithvi Par Something Like This [ Suhaagsays Prithvi Par Something Like This [ Suhaagsays Prithvi Par Something Like This 12345 See No Veer That Soft Forget What Will U Will Remove The Evil Elements And Content Should Be Placid Over 12.5 Liquid Subscribe 15 Ki salary bhi hua hai wake up to 6 years will pop up to android something like this reel the 5th and 6th and order last element college limit for b id will have two of three from all hit songs person something like this after rearrangement of elements 242 Minute cost is basically a the status of electronics and it is the cost of earring swift on the other hand in the wedding elements of [ __ ] and building itself wedding elements of [ __ ] and building itself wedding elements of [ __ ] and building itself very first flowers is hair soft private security association's secretary and channel like incentive and total number of 200 grams pims Bhego of endless and love members of the city have seen how they can do this in code and for how they can find team district president elements present 100 and 200 test and also PM something like this 500 600 off the number of elements in which is the Largest is that in the beginning it is always for the person point out prescription limit site Soviet plant genetic elements of this up that 24 how they can find the air filter element frequency identification for this next day whole coriander fennel notification Neetu Paul's limits to connect with And Laptop This Is Your Favorite Place From 1.5 Lakh Awadhesh Mishra Shoaib Squidoo 5530 Element Persona The Limit For B Id M Id To Welcome Teacher Info Point And Click On Subscribe To RSS Feed Subscribe To R Channel Subscribed Nahi Kiya In The Size Of Adi Displaced And detect r's person withdrawal that how to the element managing editor use this point time not fixed MS Word Delhi toe return back toe top spot in vitamin A a little kids school | Kth Largest Element in an Array | kth-largest-element-in-an-array | Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_.
Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element.
You must solve it in `O(n)` time complexity.
**Example 1:**
**Input:** nums = \[3,2,1,5,6,4\], k = 2
**Output:** 5
**Example 2:**
**Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4
**Output:** 4
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `-104 <= nums[i] <= 104` | null | Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect | Medium | 324,347,414,789,1014,2113,2204,2250 |
91 | Hello Hi Everyone Welcome To My Channel It's All The Problem Record Beans Message Containing Letter From The 2G Is VPN To Dr To Numbers Using Following Mapping 102 And Monitor 2016 Dholi Digits Determine Total Number Of Best Dancers Guarantee 232 Sorry For Example A Number Of Different Video subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to office number to protection and fix so how many different ways we can decorate software like just do and 126 rates on electric to and subscribe our YouTube channel subscribe Now to that and 2 and six and Mrs in are not doing anything for the width one adhoi subscribe 60000000 the father with 20 have anything e have only from 126 fans this is not fair continue with speech scandal ki ek solution record wife online Like first to leave one and contacts from where they can continue withdrawal inches and 2.1 a dhoye inches and 2.1 a dhoye inches and 2.1 a dhoye or channel subs shyam subscribe and share 1090 can only to which is this point to the number 90 subscribe skin example will oo will start from zero for string in The village quote 1 one will increase in next and you will welcome like to web tracking tool and lag increase 2nd id 1st 2nd id 1000 to two to that from i2i plus to the number dial serving this garlic and to 2610 veer they continue Like this is question and share this will not go 800002 MP3 Subscribe to Lohe 4021 channel Like comment share and subscribe so totally different subscribe and this length and question spring which means the process all districts will have evil return and fuel tank Please like character in power string airtight indexes 0 conductor middle menu subscribe to be lit character vaikuntha 2G switch to return 180 subscribe my video and implement food and only in the court has been implemented and see the number of problems for education say you in Thursday Subscribe to A Tragedy Languages Don't Like It Is That A Tragedy Languages Don't Like It Is That A Tragedy Languages Don't Like It Is That Case Will Just Return Because They Are Able To Liquid Android Is 000 Clear To Convert Into What We Do We Need To Calculate Total Channels Subscribe To My Channel Will First Effigy Thursday In To-Do List To-Do List To-Do List That Form i2i Plus Two Software Testing Two Character Effect Is Less Than Or Equal 226 History And Inco 2016 Patience With 10 Seconds To Like Subscribe Of Forests And Villages Return Of The Rebel To Subscribe To 200 Hair Also Is Needed You Can See Wear Checking Two Characters Add Vegetables Sentence This Like Share Plus One Should Be Length Garlic And Equal To Short Length Lee Thursday A Fetish Walking And Wear Getting Correct Answers Left Side To Randi Custom Test Cases Like 00000000 subscribe and subscribe this Video give time let's understand A few seats for one celebs or 21 to 0512 two which hair on this I will welcome to and here I will be less 3 because of this lighting also points to entertain hair will get is 30 feet for list that opposition 2010 problem android Problems in Life with Three Idiots Problem Ghrit Problem Solution for You Can Do It Use This Map of Interior to Mind J Remedy Solution of the Already Calculated Is a Problems and Newspaper Encounter Dam Against Here This is Practice Na Android Map Not Born In solution of birth problem content that I will return in Indian villages and effective way yes where is the content type hair retweet content that surgical see it's working now they can submit this and see the problem will not return in flight mode Start the time forget his leg return from fear and its effect on returning festival solution sid time complexity of dissolution subscribe time complexity of dissolution and complexity and space complexity you can also change this like share and subscribe like and share will withdraw pf office late and later Of Strangers Take Care If Life Is My Channel Thank You Will Return To Defeat After Is Not No Loot For Using Chief Secretary Dare And Written Over Cardiff And Share Subscribe Button Must Subscribe To Nifty 126 Laptop Patience The College Girl Don't Forget Disting Ayush Tourist Again Soft Classification Solve This Problem In Water Supply And Suez Religion Subscribe No Problem Amazon Placid At Home And Share And Subscribe Like Share And Subscribe Fast Track Court Se 1000 V Way Will Proceed From 2ND Year Will Update Character 90 512 MB This Hair Pack To Retail Company British Midlands And One For This And Answer In Number Of Veg Sandwich Subscribe Button Subscribe My Channel Subscribe Like Share And Different Only Boys Channel Tarf Quarterly Spider Live With His Big Space User Free Variables And Solve This Life Bana Ki Mute Stuart Wright Any Five percent problem but this comment section thanks for watching | Decode Ways | decode-ways | A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping:
'A' -> "1 "
'B' -> "2 "
...
'Z' -> "26 "
To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into:
* `"AAJF "` with the grouping `(1 1 10 6)`
* `"KJF "` with the grouping `(11 10 6)`
Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`.
Given a string `s` containing only digits, return _the **number** of ways to **decode** it_.
The test cases are generated so that the answer fits in a **32-bit** integer.
**Example 1:**
**Input:** s = "12 "
**Output:** 2
**Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12).
**Example 2:**
**Input:** s = "226 "
**Output:** 3
**Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6).
**Example 3:**
**Input:** s = "06 "
**Output:** 0
**Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 ").
**Constraints:**
* `1 <= s.length <= 100`
* `s` contains only digits and may contain leading zero(s). | null | String,Dynamic Programming | Medium | 639,2091 |
433 | hello everyone so now we are solving 433 which is minimum genetic mutation it says that you are given a string given two Gene strings start Gene and engine and the gene bank which is basically an area of this written the minimum number of mutations needed to mutate star okay so um I just solve this sum which was I think Word ladder yeah where this is pretty similar to that where you are just supposed to generate this word using the bank of words and you're supposed to generate this and yeah it was pretty similar but I think the only change here is that your given choice is acgt so basically in Word ladder you could just generate all the 26 possible characters but here you have only four so it's very similar to that if you guys want to refer you guys can check that out video out but I'm just gonna go ahead with the solution here I think that should be the solution for this as well where I'll have a queue which will take in strength right and this queue is basically keeping track of all the possible combinations which are valid I'll have a hash set of strings right and this is basically a hash set for the bank foreign I'll also have a hash set which will keep track of my scene strings right and then I'm gonna do Q dot add start point right and what I'm going to do is while my queue is not empty right so what I'm gonna do is um since I need to return number of steps I need to keep track of steps so in steps will be one initially right and uh I'm gonna start from here right and at the end of this I'm gonna do steps plus so it's kind of like a BFS search and every time I do I'm gonna do Q dot po this is going to be my current string and I'm gonna check if this dot equals my and G if that's the case I'm gonna return steps straight away otherwise I need to generate all the possible values so what I'm going to do is for okay so I need the possible characters carry of um let's say possible cash is equal to new calorie of a C G and T okay uh okay and then what I'm gonna do is for care C4 and I start oh I can resize J starting from 0 J less than current dot length J plus uh what I'm going to do is I'm gonna use cap C and possible cats string new word will be equal to oh current dot substring of 0 comma J Plus C plus J Plus 1. right and then I'm gonna check if this new word is in my bank so if that's a valid word and my C dot contains this new word actually should not contain this new word then I'm gonna add it to my queue and then I'm gonna add it to my scene as well yep and it's at the end of this I still don't have it that means it's not possible yeah this makes sense okay so I failure okay so I messed up something let's see so I did a start Gene with steps one I'm gonna start with this I'm gonna pull that out if that equals my engine inside that's the end otherwise I'm gonna go over my current length and for all the possible cares oh okay let's see yes that's the reason I'm just making sure it's this able to add uh yeah and then let's see okay let's print this I guess oh so I'm taking it everything and then I'm not sure if this is how you do character dot to string let's add C I think maybe that's the reason I'm not sure okay that's not the reason so what's happening here let's print a new word is it even able to produce the right word okay let's see the words that we are generating thank you a c g t okay the first word is changes okay so it's able to generate the new watch so that's not the issue uh oh I see because my bank set has not been populated so I gotta populate my bank set for oh string X in my bank bankset.addex yeah that makes sense bankset.addex yeah that makes sense bankset.addex yeah that makes sense let's see okay so output is two right now oh let's see why so I start with steps of one I pull that out if everything works fine I guess it has to start at zero and then if I add I do one and then yeah this makes sense okay let's submit yeah this works yeah so the basic idea is similar to the word ladder I didn't explain this much but if you guys want to check that out that's the video you guys should look up and yeah in terms of time and space complexity that this one is tough which I don't know so basically it's like you go over these are the number of nodes that you are going to go over right so each in word is a word so the graph would be o of n Square where n is the number of words in the bank and then to generate each of these Banks it's going to be Dot M where m is basically the length of your board so the length of your start G so that's your space and time complexity uh but yeah I mean this is kind of tough but yeah all right so that's it thank you | Minimum Genetic Mutation | minimum-genetic-mutation | A gene string can be represented by an 8-character long string, with choices from `'A'`, `'C'`, `'G'`, and `'T'`.
Suppose we need to investigate a mutation from a gene string `startGene` to a gene string `endGene` where one mutation is defined as one single character changed in the gene string.
* For example, `"AACCGGTT " --> "AACCGGTA "` is one mutation.
There is also a gene bank `bank` that records all the valid gene mutations. A gene must be in `bank` to make it a valid gene string.
Given the two gene strings `startGene` and `endGene` and the gene bank `bank`, return _the minimum number of mutations needed to mutate from_ `startGene` _to_ `endGene`. If there is no such a mutation, return `-1`.
Note that the starting point is assumed to be valid, so it might not be included in the bank.
**Example 1:**
**Input:** startGene = "AACCGGTT ", endGene = "AACCGGTA ", bank = \[ "AACCGGTA "\]
**Output:** 1
**Example 2:**
**Input:** startGene = "AACCGGTT ", endGene = "AAACGGTA ", bank = \[ "AACCGGTA ", "AACCGCTA ", "AAACGGTA "\]
**Output:** 2
**Constraints:**
* `0 <= bank.length <= 10`
* `startGene.length == endGene.length == bank[i].length == 8`
* `startGene`, `endGene`, and `bank[i]` consist of only the characters `['A', 'C', 'G', 'T']`. | null | Hash Table,String,Breadth-First Search | Medium | 127 |
1,588 | hello thanks for checking out this video in today's video we'll be looking at lead code problem number one five eight the sum of all odd length sub arrays the problem description says given an array of positive integers we want to calculate the sum of all possible odd length subarrays we're told that a subarray is a contiguous subsequence of the array and we want to return the sum of all odd length subarrays so here's the first example that they've given us we have an array of length five with the numbers one four two five and three and just to clarify real quick what a sub array is a sub array means we're going to start at some number maybe i start at one and we're gonna move in the right direction and end at some other number maybe i'll end at two here the sub array here would be one four two we have to include all numbers from one to two and you just choose some number and then go right and end at some other number i could also if i have wanted to start and end at five this would produce the sub array just five it's different from a subsequence because in a subsequence you can start and end at some value but you don't need to include every number in between i like to just be very sure that i know that we're dealing with a sub array or a subsequence because there's been a few times where i thought it was a subsequence that i was looking at and i made the problem more difficult than it needed to be but in this problem we are looking at subarrays now i've gone ahead and written out all the possible sublim sub-arrays sub-arrays sub-arrays with their lengths so in this purple column on the left i have all of the sub-arrays of length i have all of the sub-arrays of length i have all of the sub-arrays of length one there's one four two five and three and then likewise in the second column i have all the sub-arrays of length two i have all the sub-arrays of length two i have all the sub-arrays of length two and then there's the sub arrays of length three four and five but we're really only interested in the odd length sub arrays so the odd length sub arrays are one three and five we don't really care about two and four because those sub arrays are all even length so what i'm going to go ahead and do is look at this first number one and look at for every odd subarray how many times does it appear it appears once in the purple once in the blue for length three and then one in length five so it appears three total times how many times does four appear in an odd length sub array it appears once on the left it will appear twice actually for a subarray of length three and then it will appear once for a sub-array of length five so once for a sub-array of length five so once for a sub-array of length five so it actually appears four times now we'll look at how many times does two appear it appears once for a sub-array of length one for a sub-array sub-array of length one for a sub-array sub-array of length one for a sub-array of length three i actually have these three here so i'm up to four already and then i have one more here for length five so this actually appears five times and then if i look at how many times five appears it appears once two three four times and then how many times does three up here one two three it appears three times now i want to go ahead and multiply these together if i do that i'll get 3 16 10 20 and 9 and if i add up these five numbers together i will get 58 which is the expected answer now look what we did there we looked at how many times each number appears in an odd length sub-array odd length sub-array odd length sub-array and then however many times they appear in that length sub-array we just multiply it by that sub-array we just multiply it by that sub-array we just multiply it by that number and that's how we get the answer the hard part of this problem really becomes calculating how many times each number appears in these odd length sub arrays so let's try to figure out how that can happen if i take a step back and i look at for whatever number is at index 0 i'm going to write the indices above here real quick if i look at for index zero how many subarrays total not just odd length subarrays but sub arrays total index zero appears at i can calculate that by taking the sub arrays that start with that and then multiply it by the sub arrays that end with that so here's what that means let's say for example you have city a you have city b and you have city c there are two paths from a to b and there's three paths from b to c if i asked you how many paths total unique paths can we are there from a to c that go through b here's how you could do it you could just count them you could say well there's one if i go from the top to the top that's one i could go top to the middle that's two i could go the top to the bottom that's three i could also go from the bottom to the top that's four i could go from the bottom to the middle that's five or i could go from the bottom to the bottom and that's 6. another way to calculate that is there's two choices from the left-hand side and 3 on the from the left-hand side and 3 on the from the left-hand side and 3 on the right there were two choices that end at city b and three choices that start at city b so it's kind of a similar process here we're going to look at for each index how many sub-arrays start at that index how many sub-arrays start at that index how many sub-arrays start at that index and how many sub-arrays end and how many sub-arrays end and how many sub-arrays end at that index here's how we can do that so for index zero how many sub-arrays so for index zero how many sub-arrays so for index zero how many sub-arrays start with zero i look at how many sub-arrays start with i look at how many sub-arrays start with i look at how many sub-arrays start with zero index zero there are five there's the one of just the number itself zero i could go zero to one zero one two three and zero one two three four so there's five and how many end at index zero there's just one there's the index of just itself when i is one if i'm looking at index one how many subarrays start with one the answer is four there's one two three four that's it if i look at how many end i have two choices it could be zero one or just one and you might be able to see the pattern that in general the number of subarrays that start from your from whatever index you're looking at is n minus i where n is the length of the array and i is whatever index you're looking at so if you look at the case when i was zero if we take five minus zero we get five or in the case when i is one five minus one is 4. if we look at how many sub-arrays end if we look at how many sub-arrays end if we look at how many sub-arrays end with that value it's i plus 1. but if we look at this when i is 0 we have one choice when i is one we have two choices and that just scales literally like that and if we multiply these together we get the total number of sub-arrays not the odd length number of sub-arrays not the odd length number of sub-arrays not the odd length but the total number then the next problem becomes well if i know the total number of sub-arrays how know the total number of sub-arrays how know the total number of sub-arrays how can i calculate the odd well if i know the total and i cut that in half just take the total number and divide by two that'll almost give me the answer it actually sometimes will give me the answer because i know that half of them will be even and half of them will be odd however in the case where a number appears in an odd number of subarrays there will actually be an extra odd one so here's what that means let me scroll up a little bit we saw here that for the number one on at index zero it appeared in three odd sub-arrays but only two even odd sub-arrays but only two even odd sub-arrays but only two even sub-arrays sub-arrays sub-arrays the total number of sub-arrays it the total number of sub-arrays it the total number of sub-arrays it appeared in was five so it appeared in five total when we cut that in half we get two for rounding down so that's how many even sub arrays it appears in if n is odd the number of sub arrays it appears in is odd then i have to add one more to take into consideration that extra odd sub-array it appears in odd sub-array it appears in odd sub-array it appears in so if i add one to this it would be three one index zero the number one appears in three odd sub-arrays appears in three odd sub-arrays appears in three odd sub-arrays it appears in five total it appears in two even and three odd so you have to pay attention now to if the total number of sub-arrays to if the total number of sub-arrays to if the total number of sub-arrays is odd or even i'm going to do one more example now with our original input using our formula we're using where we look at how many sub-arrays where we look at how many sub-arrays where we look at how many sub-arrays start and end at a particular index and then how many total sub-arrays and then how many total sub-arrays and then how many total sub-arrays include that and then the odd just so you can see how the numbers start to play in so if i look at index zero again i think we already looked at this there are five sub-arrays that start there are five sub-arrays that start there are five sub-arrays that start with index zero there's one that ends with it for a total of five looking at index one there are four that start with it i'm getting four by plugging one into our formula of five minus i the end would just be two for a total of eight for index two i would get three subarrays that start three sub-arrays that end that start three sub-arrays that end that start three sub-arrays that end and nine total sub-arrays including and nine total sub-arrays including and nine total sub-arrays including that include the value two for index three i would have five minus three which is two that start with it and i would have four that end with it for a total of eight subarrays including index three and for index four i would get one sub-array that starts with it get one sub-array that starts with it get one sub-array that starts with it five that end with it for a total of five and to calculate how many odd sub-arrays and to calculate how many odd sub-arrays and to calculate how many odd sub-arrays i divide by 2 and if it's if my total is odd i add 1 if it's even i leave it so 5 divided by 2 in java would be 2 but because 5 was odd i add 1 for 3. 8 divided by 2 is 4 and that's even so i can leave it 9 divided by 2 would also be 4 but because 9 was odd i add one to get five i already did eight and i knew that was four and i already did five and i knew that was three and if you look at these numbers down here they exactly match what was up here when we brute forced it and just listed all of the sub-arrays so this is a all of the sub-arrays so this is a all of the sub-arrays so this is a very fast way to look at how many times a particular index appears in all odd length sub-arrays once we know this odd length sub-arrays once we know this odd length sub-arrays once we know this we just multiply this odd value however many odd sub-arrays contain the however many odd sub-arrays contain the however many odd sub-arrays contain the value by the value itself and keep track of that sum now let's take a look at the code for how this can work first thing i want to do for the code is create a variable to hold on to the sum and that at the end here i'll make sure to return that i also want to have a variable to keep track of the length of the array just this is going to make the code look cleaner later on now what i want to do is iterate through every index of this array and i want to keep track of how many end here and start here so remember the formula for how many sub-arrays end at this index sub-arrays end at this index sub-arrays end at this index it was i plus 1 and then how many start here is n minus i for the total it's just the multiplication of the start and the end and then finally the odd are going to be the total divided by two and then there's a quick check i got to do because if the total was odd then i have to add one to the odd sub-arrays that this value appears in sub-arrays that this value appears in sub-arrays that this value appears in finally i can add to my result the multiplication of how many odd sub arrays this value is and times the value itself and if i go ahead and do that let's see what the answer gives us here 58 just like we expected and if i submit then we get a successful run if we look at the runtime complexity real quick for time and space if we look at just time first here there is one for loop which will run n times and all these operations inside of the for loop are constant time meaning this is o of n time and space complexity we're just using variables we don't declare any extra memory so the space is constant space thank you for watching the video if you have any questions please comment and if you have any video suggestions please let me know and i'd be happy to make one thank you | Sum of All Odd Length Subarrays | sum-of-all-odd-length-subarrays | Given an array of positive integers `arr`, return _the sum of all possible **odd-length subarrays** of_ `arr`.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** arr = \[1,4,2,5,3\]
**Output:** 58
**Explanation:** The odd-length subarrays of arr and their sums are:
\[1\] = 1
\[4\] = 4
\[2\] = 2
\[5\] = 5
\[3\] = 3
\[1,4,2\] = 7
\[4,2,5\] = 11
\[2,5,3\] = 10
\[1,4,2,5,3\] = 15
If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58
**Example 2:**
**Input:** arr = \[1,2\]
**Output:** 3
**Explanation:** There are only 2 subarrays of odd length, \[1\] and \[2\]. Their sum is 3.
**Example 3:**
**Input:** arr = \[10,11,12\]
**Output:** 66
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= 1000`
**Follow up:**
Could you solve this problem in O(n) time complexity? | null | null | Easy | null |
791 | Hello everyone welcome back today we will solve another new problem which is the daily problem of lead code the problem is very interesting you will get to learn a lot here so let's start let's understand what the problem statement is saying to us ok and its So we go to the white board, so what the problem statement is saying is that you are given two strings, okay, we have two strings, and s, okay, we have one s, right, one is like this, all the Characters for order are unique means one order is given to us like for example this is ok one order is given one order right one order is given and one s is given then all the characters in this order are unique ok And this s is our input array, the question is saying that we have to sort this input array which is AB CD in such a way that the order given is maintained, okay for example if we We have A B C D Right A B C D And what is the order given to us Order is equal to c B C B A So when we sort then among the first of these characters C should come first then B should come right Have given a should come and the rest of the characters should come ok so this is what the question demands right then you will see the output is yours this is the second also let's see what is the order saying order is our b ca a Edge is ok, what is the edge and output string? Our A B C D is again the same. A B C D. Right, so what we will do first is that we will first look at A which is the input array which is the ordered array. Okay, so b should come first. There is b in our string. If there is b, then we have put b first. After that, c should come. If there is c in our string, then we have put c on the second position. If there is a in our string, then we have put a on the third position. Given and finally f is not in our g is not there so we have put whatever is left so b c ad and this is the output Right this is the output So we will see two methods Right we will see two methods First method which is inbuilt sort function in it We will try to solve this by passing a Comparator and second, which we just did here when we were doing the dry run. Basically, we saw a pattern. We will solve this question with the help of that pattern. Okay, so let's start. First of all what we will do is like we know STL gives a function t e sort ok sort gives a function what we have to pass inside it is array right array start and array end and one more third parameter along with it Also we can pass That is the Comparator Function Okay, so what we will do today is we will try to create a new Comparator Function Create a new Comparator Function which will sort as we want according to the logic that we have written in this comparison. We are seeing this right that if I put this map, whatever unique elements are there in this map, right, they will always be unique elements, keep their positions, right and tell the compiler to put the one whose position is less first, you and whose position is later. It is coming, keep it last, then our question will be solved. Correct, let's try like we have made a map. Right, we have made a map. A is ok, what is there in it? What is the position of B? Right? B's position has become zero. Then what is the second m off cc What is the position of C Also became zero right after that m of A Its position will be Sorry Its position and its position has become Two Correct And then m of last What Tha F and G Right its FA's position is done Tha and FG Okay FG what will be its position done Then tomorrow now what will we say to the Comparator that sort our array so array what is our A B C D Right this is our A B C D This is our input er A B C D So when it goes to sort right, you know that always two characters or two elements are compared so first of all it will go to sort A. When it goes to sort A then What we will say is that first of all look at the position of a. We have found the position of a from our map. Okay, so what will be the position of a? This will be your position. What will be this position of yours? We have seen that this is the position of 2. Okay, so this is the position of yours. Then we gave it. Said, look at the position of B's position is fine. We have seen how much is the position of B. The position of B is zero right. So whose position is coming first in this, that of B. So we will return our function from our basic Comparator, what is a? Lesson B is right: Is a smaller than Lesson B is right: Is a smaller than Lesson B is right: Is a smaller than b? If a is smaller than b then a will come first otherwise b will come first and based on this our entire function becomes ready, ok just by doing this we can solve this question. Let's go tomorrow and see the answer to the question. How is your night? If I do CPSPS then basically I have solved this question, I just did it now. If you want to see, then you did it today itself. 11 is okay, 657, so basically. Question: 11 is okay, 657, so basically. Question: 11 is okay, 657, so basically. Question: Whatever we saw on the white board, we placed the same thing here, then first iterated an order, we kept the position of the order in the map, okay, then we sorted and in the sort, we put the Comparator function. What does the Comparator function say? By default, give a value to A position and B position. Right after that, find the position of A. Find the position of B. And in the end, what do you do? In the end, check whether A position is B position or not. Just to check this. This question of yours will be solved, okay, let's run it and see, basically it will pass because I have done it in the morning itself, okay, so that's all, right, that's all and I hope you have understood this problem, one more second The approach is what I was seeing in the solution section right, I was seeing it in the solution section and I also found it very interesting right so let me explain this to you too so basically when we were doing this dry run right when we were doing this dry run How were we making this order, were we following the map in the map, what is the position of B, what is the position of C, what is the position of A for example let's say right what is this order what is B C A as right A & G This is what is B C A as right A & G This is what is B C A as right A & G This is our order and this is our string A B CD Correct This A B CD So what we will do is make a map Let's say A Okay and the input array will keep their positions Basically we will keep their counts Positions otherwise A How many A came once, okay, so it's counted, one more from Let's, here's one more A from Let's, here's P, okay, m of B, what happened m of B, your one right m of B is also done. Your one write is done then m off s done your one write then m off what is f m off f done your one write sorry m off f no what was d my bat ok input array we are taking m d = 1 and in the last One more a we m d = 1 and in the last One more a we m d = 1 and in the last One more a we added by ourselves so m a now it's done ok cool now what we will do is add it to whatever input whatever order is the array we will delete it right so if I put a for loop okay then what is the first character? If there is B, then I will see if there is B in my map. Right in my map, B is m of B E 1. If it is there, then I can clearly see how much is it once. So I, the answer is one, for example, let's make one answer. Equal to mt string is ok one answer equal to mt string is done right if now I will append as many times as b in the answer then see the first character for example aa equal to two is now zero aa equal to what is zero right then Answer: Now what to what is zero right then Answer: Now what to what is zero right then Answer: Now what happened? We have appended here as many times as there was B in the answer, so the answer is now, your B was there only once, then I became one second character. We saw what CC is, what do we say, whatever is the input. Hey, yes, C is there once, as many times as C is there, append it in the answer. Fine, now I have come, your two are fine, I have come, now two have been seen. We have seen the second character of C. Sorry, we have seen the second character. We have completed the order of A. If you want to see that, okay, then A, we saw what A is in our map, yes, how many times is it there, twice, get A appended twice, okay here and add I plus, then this is done, Thr, then we saw the third character, what? A is there, we don't have A, then there will be nothing here. Is G not in our input array, G is also not there, then nothing will happen. Okay, B C A, we have missed something. Yes, correct then finally what is left in the map. So, we have done this process, okay, we have done this process, now whatever is left in the map, you append it here and this will be your answer, okay, so this was also a good approach, so I am the same. I was looking in the solution section and this guy did the same, created an order map, okay, storing the frequency of the string in math, whatever was the input array, okay, kept its frequency, then iterated over the order, and as orders are being received, he Took out the count, kept on adding plus to that count on the answer and finally, whatever was left in the map in the end, it is ok, kept on adding plus on it here, that was it, ok, so this is also a good approach, you guys can try this too. I have not tried this right but you can do it, this will be homework for you, okay, so that's all for today and I hope you have understood this solution, if you have any problem with this then please let us know in the comment section. I will tell you and then keep solving at least one problem in the next video thank you so much | Custom Sort String | split-bst | You are given two strings order and s. All the characters of `order` are **unique** and were sorted in some custom order previously.
Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string.
Return _any permutation of_ `s` _that satisfies this property_.
**Example 1:**
**Input:** order = "cba ", s = "abcd "
**Output:** "cbad "
**Explanation:**
"a ", "b ", "c " appear in order, so the order of "a ", "b ", "c " should be "c ", "b ", and "a ".
Since "d " does not appear in order, it can be at any position in the returned string. "dcba ", "cdba ", "cbda " are also valid outputs.
**Example 2:**
**Input:** order = "cbafg ", s = "abcd "
**Output:** "cbad "
**Constraints:**
* `1 <= order.length <= 26`
* `1 <= s.length <= 200`
* `order` and `s` consist of lowercase English letters.
* All the characters of `order` are **unique**. | Use recursion. If root.val <= V, you split root.right into two halves, then join it's left half back on root.right. | Tree,Binary Search Tree,Recursion,Binary Tree | Medium | 450 |
207 | what is going on everyone so today we are going to be looking at lead code number 207 it is called course schedule and i have to say this one is a pretty tricky one it's working off of some patterns and i think the key to this question is really recognizing the patterns that are that this question is asking and once you understand that it's actually not too bad it i see how this can be solved very quickly in like a matter of minutes just by understanding what this question is really asking so let's go through it we'll go through it step by step okay so the prompt there are a total of num courses you have to take labeled from zero to num courses minus one some courses may have prerequisites for example if you take course zero you have to first take course one which is expressed as a pair zero one given the total number of courses and a list of prerequisite pairs is it possible for you to finish all courses okay so example one we have an input of num courses two and prerequisites of one and zero the output is true there are two total of two courses to take if you take course one you should have finished course zero so it is possible okay so basically what it's saying is that to take course one we have to take course zero but because there is nothing in here that says anything about course zero we can assume that we can take course zero without any prerequisites here we have the example number two we have two courses and we have a prerequisites to take course one we have to take a prerequisite for course of course zero but to take course zero we have to take a prerequisite of course one and so this is impossible to take because essentially we're getting a cycle to take one we have to be able to take zero and to take zero we have to be able to take one so there's no way to enter into this graph really and that is really the key to this is understanding that this is a graph problem and what it's really asking is there a cycle in the graph for this there's no cycle because there's nothing that we have to take in course zero and so we can take course zero and we can get to course one by going through zero but here there's no way because there is a cycle that's happening here and the other thing that they kind of tripped me up was is it undirected or directed and it is a directed graph and once that was understood that this is asking that we have a directed graph and we want to figure out is there a cycle in this directed graph once that connection is made this problem can be solved very quickly and again if uh if you're not clear on how directed undirected graphs work i highly recommend checking out introduction to algorithms it's a really thick book um but the graph section is quite comprehensive and there's a lot of patterns in there that i think are really important to just to have down pat that way when you see these types of problems you can just pull from those patterns and you don't have to think too much about it's really the only thinking that really needs to be done is what pattern is this question asking underneath so if we're dealing with a graph problem and we are trying to detect a cycle then we want to use a depth first search traversal and we want to turn this input first thing we want to do is basically turn this input into an adjacency list so let's go and do that we can do const build adjacency list and again this is it's good to just kind of have these helper functions memorized that way you don't have to think too much about it so with the building adjacency list we're going to have n which is the length and then the edges okay and then what we're going to do is we're going to create our adjacency list so we can do adjacency list and then this will just be an array of length n and what we're going to do is set every single one of those edges to an empty array okay so all we're doing is we're creating an empty array of size n and each element in that array we're putting in a brand new array it's not the same array it's a totally new array that's linked to a different part in memory and it's important that the array is that because if you put the same array in every element you'll get a lot of bugs okay so what we're going to do now is we're just going to iterate over the edges so we'll do let edge in edges okay and then what we want to do is we want to pull out our source and destination out of the edge okay and now what we want to do is because this is a directed graph we just want to set the source to the destination now if it was undirected then we would mirror this we would have an adjacency list and we would put in our destination to the source but we don't want to do that because this is a directed graph and so for this we just return our adjacency list okay so that will essentially convert this list of edges into an adjacency list it'll just go ahead and build that in adjacent list adjacency list and if we look here we can see when we pull out this edge we're going to basically pull out this one and this zero the one here is going to be the source and the destination is going to be this zero so in the index of one of our adjacency list we're going to go ahead and push in that zero but the index of zero is going to be an empty array and so again we're looking for cycles so let's just take a look here we have an input of n equals 2 and then our pre-rex 2 and then our pre-rex 2 and then our pre-rex is going to be let's take a look here it's 1 and 0. okay and so what we're doing here is we're creating an array of length two so zero one those will be the indices and what we're doing is we're going and taking one and we're pushing in zero and then in zero there's nothing there to push in so we just have an empty array and if we look at this as a graph we can see that there's no cycle because 0 goes to nowhere and 1 goes to 0 but 0 doesn't go anywhere else so you can see that there's no cycle and that's really important for example the second input here we see that it's 1 and 0 and 1. so let's just go ahead and refresh this okay so we have n equals two and we have an input of prereqs of zero and one and 0. okay and so what all this is we have edges here and we want to create an adjacency list out of this so here we have our key essentially or the index so we can have 0 and 1 and what this is going to map to is the value so 0 is going to map to 1 and 1 here is going to map to 0. and so you can see here we have a cycle if we go to 0 then this is going to go to 1 and if we go to 1 this is going to go back to 0 and there's no way to enter into this and so we can't finish all the courses because there's a cycle okay so we build our adjacency list now what we want to do is we just want to do a depth first search traversal so we'll just call this has cycle and we'll do depth first search and again this is a pattern so we take in the node take in the list we take in visited and then this is a way to check for cycles with depth first search directed graphs it's uh it's something that you wanna make sure you understand beforehand and it's uh it's basically edge classifications is what you wanna look at and you wanna check if there's a back edge if there is a back edge in a directed graph that means that there's a cycle it means that there's a cycle in there if you have a back edge and so you want to have basically a variable that stores the arrival and departure and this is a time stamp so every time we implement we hit this depth first search function we want to increment the arrival so arrive at node increment that we want to set visited to true of node true okay and then when we go through the entire we traverse the entire graph from that particular node we want to depart we want to increment the depart and again if you're not familiar with this it's good to check out introduction algorithms they go really in depth on edge classifications directed versus undirected graphs and how to check for cycles and just common things that you see that a lot of these questions kind of are asking underneath the hood and i think it's really important because once you understand how to detect these patterns then a lot of these questions aren't really that difficult you can just apply a very basic template that you can have somewhat memorized okay and we just return we want to if we go through all of this we want to return false okay and now we are just we're just basically implementing a very classic depth first search so we'll do let neighbor of adjacency list node okay if not visited neighbor then we're going to set visitative neighbor to true okay and what we want to do now is we want to basically call our recursive call but we want to check is there a cycle search and we'll put in our neighbor we're traversing from the neighbor visited arrive depart and if it has a cycle we return true okay now if we have not visited we have to check is the departure did it depart okay so if the part at neighbor equals zero then we also want to return true what we're basically checking here is if there's a back edge okay and now we just write our main function so first again this is following a very basic template and we're just going to build our graph so const adjacency list is going to be build list and we're going to put in our number courses prerequisites and then we want to create our visited object and we want to have our arrive it's going to be an array courses and our and we're going to set each one of these to zero okay whoops and we're going to do the same exact thing for depart and now we again we just do a very common pattern here of doing a depth first search algorithm graph traversal we do let vertex equals zero adjacency where vertex is less than jsonc list.length is less than jsonc list.length is less than jsonc list.length plus and we're going to check if this is visited at vertex if it's not visited then we're going to go ahead and check if this if we traverse from this node from this vertex node uh is there a cycle as cycle that first search and we're going to start with our vertex our adjacency list are visited arrive and depart and if there's a cycle then that means it's false that means we cannot finish all those courses and if there's not a cycle then return true okay and that's it's not too bad i mean one all we gotta really figure out with this question is there a cycle and if there's a cycle then that means we cannot finish all these courses and if there's not a cycle that means we can and we have to also recognize that we're dealing with a directed graph and we're just checking for cycles okay so let's run this oh i need to sign in let's see here let's see i can do that okay let's go ahead and run this and yeah and we have success and so that's it's not too bad it's a good question to know you can see that it's asked at amazon facebook bike dance bloomberg and i had trouble with this question when i first encountered it even when i looked at the solution i still had a lot of issues getting my head around this and i think if you're not familiar with breadth first search depth first search cyclic versus acyclic graphs this can be a tricky one and i think one of the things that is really important is when you're solving these lead code problems to really find the pattern solving these problems just as an island or independently can really be exhaustive because there's so many of these problems but many of them are following the same underlying pattern and so once those patterns can be recognized you don't have to think too much you can just solve these really quickly and quite effectively so that is lead code 207 i hope you liked it and i'll see you on the next one | Course Schedule | course-schedule | There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return `true` if you can finish all courses. Otherwise, return `false`.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** true
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= 5000`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* All the pairs prerequisites\[i\] are **unique**. | This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS. | Depth-First Search,Breadth-First Search,Graph,Topological Sort | Medium | 210,261,310,630 |
1,572 | That aapke ajay ko hua hai Hello hello everyone welcome to new video in this video marriage ko * Discuss another video marriage ko * Discuss another video marriage ko * Discuss another problem from code problem life more return primary element not primary ok problem said that we are a matriculation -Matriculation will go and those who will subscribe us for Rs 500, 600, 800 to 1000, what will be the limits on the use of its primary dialogue, OnePlus 5 Plus 90, how long is it to subscribe to the channel, how long is it, we are fine with both of these. If this is getting repeated then this war was ours, subscribe our channel and subscribe and what is the problem, if we see examples in China, if we see, then in China, if we give examples, 123 45678910 sure. That if we see here subscribe scan center 66 this is our primary element primary six then this is the final of this subscribe to withdrawal forces and 3417 and subscribe jhal if we see here these two said but rich then our how much of this is our 16 Which is our actual group why because any of our repeat first number off daily or if our we have to take both in this village and after that it will be ours subscribe it - if you give it would be best to appoint them number of columns for this Bluetooth off He will be our answer to Dangal, so how should we approach this position? First of all, we, the people who will watch New 2020, will not use it, will keep subscribing, then we will keep our festival, now our Ghaghra Aai means zero, after that, life will be like that, so subscribe to us. Use our I, that is, whatever is our matrix M.Ed. Please forgive our I. matrix M.Ed. Please forgive our I. matrix M.Ed. Please forgive our I. This is our primary diner, all will be covered in it. Now talking about us, here we have this our - this our - this our - - - - So here we have to do ours today. This is our first for what we should read on our channel here - - - - - If it works then we will get the full limit from this side also and we will get the full limit from the stress, so after this, if we get these elements at the time. What we have to do is after that we have to check whether our Android is there or not so as soon as this follow is over we will get it, now we have to see if our society if our Ghaghra 200 if it is ours then we will cut it and return it to us Okay and if it is not so then return our - - - subscribe to appoint ka yaara milan hai our matrix that accused points 152 in this lineage then this is what we will get 151 if our mind is appointed as a cover with attachment element then it happens here. It goes, let's go here, we get this here, we have to subscribe 0210, first of all, we have to hydrate and finish both through our lips and lastly on Thursday, we will make our return, this trick is only and if it is raw. Before we solve our problem, what would be our time complexity of free space complexity? Complexity is what will it become and our number of days so we have also subscribed our channel for space, first of all we will do 2012 quarter then we will get this which will be the number of problems of the matrix because both are equal this is what we And make a big village, let's chat here, subscribe equal to and we will add this trick and its element - - - element - - - element - - - Okay, we will add this, let's put it in the village and like to finish, now we have to see that our The time which is our matrix and the number of columns contains the content, still those number off, so what will we do, we will look at it here, so now what will we do, we will check whether our number off element Ghr divides, then what will we do. We will add them in this and what else will we do if there is such a person who subscribes to us like it will be found here, so let's first of all subscribe for the school and then submit it and come to see the result and this is our submission. Which is faster than more, we used less space, so we just subscribe and see plus, so we can copy paste this thing, subscribe control plus, what is the difference here that whenever we calculate our length. Used to do here we put parents after length function after that is equal to zero i labs we submit hmm result pathetic and saiya subscribe if now we see world cup final with inches now it is doing ours then instead of length we have We had to size the accused result and this we did not have anything, converted it into subscribe, ran Shubhendu as we saw here, after that we set, if that discussion, then summing up two varna system - million tonne tax 25 solution You must have understood, system - million tonne tax 25 solution You must have understood, system - million tonne tax 25 solution You must have understood, if you have any question then you can post it in the comment section below and we will reply to it. If you subscribe then you can join our channel, the link of which is in the description. Thank you | Matrix Diagonal Sum | subrectangle-queries | Given a square matrix `mat`, return the sum of the matrix diagonals.
Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.
**Example 1:**
**Input:** mat = \[\[**1**,2,**3**\],
\[4,**5**,6\],
\[**7**,8,**9**\]\]
**Output:** 25
**Explanation:** Diagonals sum: 1 + 5 + 9 + 3 + 7 = 25
Notice that element mat\[1\]\[1\] = 5 is counted only once.
**Example 2:**
**Input:** mat = \[\[**1**,1,1,**1**\],
\[1,**1**,**1**,1\],
\[1,**1**,**1**,1\],
\[**1**,1,1,**1**\]\]
**Output:** 8
**Example 3:**
**Input:** mat = \[\[**5**\]\]
**Output:** 5
**Constraints:**
* `n == mat.length == mat[i].length`
* `1 <= n <= 100`
* `1 <= mat[i][j] <= 100` | Use brute force to update a rectangle and, response to the queries in O(1). | Array,Design,Matrix | Medium | null |
203 | hey Haleh let's talk about the Leslie coding challenge question removed linked list elements given a linked list we want to remove the nodes of a given value looking at the first example we have a linked list of seven notes and we want to remove those nodes with value 6 that is to say if we exam this input linked list for every node we check its value if it's Mario is not 6 we will definitely keep it in the outputting linked list and after that we want to make sure the next pointer in the next pointer for this node is pointing to a node that's not 6 so if we're looking at the node 2 here the next pointer is pointing to a node of value 6 so we want to short it and we want to find the first node of whose value is not 6 in the subsequent linked list we can use another pointer to find this and make sure that no 2 is actually pointing to that so it's very clear that we can solve this by two pointers so let's just demonstrate what the two pointers Bureaus it is rows are one of the pointer is pointing to the previous node that has the value that's not 6 then the next pointer should as the job for this next pointer is to find the first no that's not this given value in the subsequent linked list and once we find those two the operation we do is to make sure that these two are connected together that is to rewire this link so no two will no longer points to note this value 6 but rather pointing to this first node in the subsequent linked list that has a value that's no 6 so that's pretty much the two pointer and while special cases that if they know if the linked list starts with this note value that we want to delete then well we should use a sentinel node for this papers so the previous starts with the sentinel so the next pointer will identify the first node in the linked list that's not a value that we wanted to lead and establish a link like this as a result in the return statement we want to return the note that this sentinel node is pointing to so that's the idea so we initialize a sentinel node the bottle doesn't really matter and the next pointer should points to head in the beginning issue points to the given hetner and the previous is initially pointing out that sentinel and the next node is initially pointing at hand and we just kind of do keep traversing until this next pointer is it's pointing up it's no longer valid node that means the you know the we will terminate while this next pointer is pointing it's a no pointer so every iteration the job for the next pointer is to identify the first subsequent node that's not of this given value so if they notice a note that we want to delete we will advance it so after this while loop we should position the next note into the next pointer pointing out to the first a subsequent note that's of a value that we don't want to delete that's the time we want to rewire this so this comment the step here after that we want to move the move those to alter or move them forward the situation here is that we could potentially have this next pointer pointing to a null pointer in that case we don't admit what we don't want to advance it otherwise we will also move it forward as well so let's say that we rewire the two pointing to three we want to move previous to 3 and we want to move next to four so that in the next generation we will still try to find the next possible node from this new location in the end we return the node without the sentinel it's pointing out so that's the code for this problem the in terms of time and space complexity even though it looks like a nested loop it's a linear time because the next is just moving to the next position so in total it would just run exam all the nodes inside this linked list exactly once so it's a linear time and for time complexity all we have is a few pointers so that's constant space yeah | Remove Linked List Elements | remove-linked-list-elements | Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_.
**Example 1:**
**Input:** head = \[1,2,6,3,4,5,6\], val = 6
**Output:** \[1,2,3,4,5\]
**Example 2:**
**Input:** head = \[\], val = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[7,7,7,7\], val = 7
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 104]`.
* `1 <= Node.val <= 50`
* `0 <= val <= 50` | null | Linked List,Recursion | Easy | 27,237,2216 |
433 | hello everyone so in this video let us talk about a medium level problem from lead code the problem name is minimum genetic mutation so problem statement goes like this that a gene string can be represented by a eight character long string which has a choice of characters of atgc so these are the nucleotides if you know a little bit about biology that in a DNA these are the nucleotides and a gene string they can they are telling us that it will be eight character long now suppose that UI investigation a mutation in mutation any nucleotide will change to any other nucleotide so what you can see is that in this investigation of mutation you start from a given Gene let's say from this and you end up to another Gene okay let's see this and now what you can see is that in each mutation you are telling that in each mutation only one character is changing okay it is changing from one cat to another character so in this you can see that uh a is same a same c the last T is changed to a okay so this is one mutation now what you can see is that there is a gene Bank okay there's a gene bank which stores the record of all valid gene mutations okay which means that it stores out what all are the possible gene mutations that can occur okay now what you can see is that you are given a gene Bank also now you are given a starting Gene and an ending Gene okay now you have to tell that what is the minimum number of mutations data required to convert from a starting Gene to an ending Gene given that all the intermediate positions like all the steps that you have to go through to reach from the start till the end should be in the gene bank because though those also like those genes that are intermediately on the end should be valid like they should be present in the gene bank because invalid genes or like uh invalid mutations we do not care about that you only care about the mutations or the genes that are valid so that are stored in the gene bank and if there is a possible part from the start till the end such that all the genes are present in the gene bank then it is a good uh like you can see that you just have to counter how many number of steps are required else you have to return minus one that's a real problem statement now you can see that from this to this you are going from this to this state now in this the last state is changed like the last character is changed and this last Gene is also present in the gene bank so every step that you do from the start till the end should be present inside the gene map now that's the overall problem statement so that you can see again from here to here you want to go now all the different genes that are possible pressure in the gene Bank you just have to tell that whether it is possible to do that now what you can directly observe from the statement is that you have a particular Gene bank and you have to only do the iteration on that Gene bank so you have to somewhat make a graph out of that because you from so what you can write you also understand is that from every position you can go to another position by doing one rotation okay so what you can directly understand from here as well is that what you can do is let's say that you have a static position of a I'm just talking about four characters okay I will only talk about four cat test but you can extrapolate this information to four characters or eight characters or any number of characters which is in the prompt statement it has only eight but for a simple understanding let us take out four aatt now from this you can go to a state that is a TTT if all of these genes are present inside a gene bank so I am building this type of graph which tells us from which Gene I can go to which Gene given that only one character is changed okay now uh from this also I can go to one more Gene State let's say this person in the gene Bank a t g now from this let's say there's one more position that I can go to is a g t g so only one character should be changed okay so all of this is some sort of a graph now let's see that you want you start with a t 80 and then okay not a C this is the position that you want to start to so what you can do is that from this position what is the intervention like uh so you have to first understand that from this state what all are the genes that are present in gene bank that is just one step ahead or like ahead of this particular uh Gene because this is the starting date I want to go to any other Gene we have to present that it should be present inside the gene bank so the other cases can made a this kind of flipped this kind of flip this can flip this kind of flip so these are different positions and the first one I can actually say that I can go to this state okay then I can I cannot go to this state because uh okay I can also go from this to this state as well because only like G is changed can I go to the state directly I can kind of go to this state by just one change now so these two I can connect to the starting uh like the starting Gene and then you can directly do a BFS because it's just a minimum distance between two given nodes inside a graph which is just a BFF so you just have to do a BFS from this node to the node whatever node you want to reach to so you just do a BFS at any point you just check that whether the ending node I want to go to is present here then you can write blue because these genes are pretty small you can actually do a complete comparison of a Ted uh like characters like whether they're completely matched to the gene I am on I want to go to so you can actually do that and that's it you will just do a DFS we first make a map from the gene bank then you insert the gene I want to start from then do a BFS over that and you will keep on doing the BFS counting out how many number of steps you are doing to reach the end State the end mutation and if it is possible and return the number of steps that you have taken if it is not possible to turn the Mind saw that's the overall problem statement and the solution part let us moved on to the code part to how we will do this so it will start from here the minimum number mutations this is n this is the adjacency Matrix that is the essential list I can say sorry uh which is used to build this whole graph so this is the identity list which is a particular string is mapped to how many different strings from upper level how many different nodes I can go to so what I'll do is I will iterate over every possible pair of nodes and uh so I and I plus one okay so this is just iterating whatever possible nodes to just bake the essential list that from which node I can go to which node so I can go particular node to different nodes like if I'm on node a I can go to node B if and only if there's only one number of mutations okay so this is the difference this is a difference function that will literate over both of these strings and just check that the number of different number of characters between these two strings okay so this is a and b and if the number of difference is only one then it is a possible mutation I can go from that but we'll note to another note so I will just check out that if it is possible then I will just make a let's get a edge between these two nodes of this particular strand let's say the is node to the jth node and 0 to 8 node so it's a bi-directional okay uh path so it's a bi-directional okay uh path so it's a bi-directional okay uh path so that's why I've created isnc list like this manner now what you have to do is that from the starting node again you have to check that what all nodes you can go to so what you can do is again you will take the starting node that is the start from which I want to start my mutation and it deliver all the other nodes again those endnotes and just check that whether this starting node is connected to all the node like which all nodes I can connect the starting node two because that's the starting node and what I'll do is that I'll again iterate over all the nodes check with this difference function that will just check that whether these two nodes are compatible to be called a mutation by mutation that means that this should be only having one character change and this function is just doing that just check that if it is possible then we'll just again make a edge between the starting node and the given nodes in the gene bank now we have the complete map with us so we will just do a BFS from the starting node filmmaker queue of strings push the starting node okay the starting you can say the starting uh Gene and then we'll and to store that whatever Gene strap it rated we don't double it over all them because we have been making a bi-directional graph have been making a bi-directional graph have been making a bi-directional graph that is where set comes into play so we'll also insert all the nodes that we have iterated to push inside the set so that we have to know key which genes we have a data which we genes we have noted over and we have inserted that also this is the total number of steps it will take from going from start till the end that is answer and just the standard BFS keep on doing this uh iteration over this queue until it is not empty uh find out the size of the queue it over all the particular level or the traversal so overall the nodes that we have seen till now okay uh then what we'll do then it will all the edges or all the connected nodes to a given node again okay and what we'll do is that whatever node I am on I have two things I have to push that inside the you and the set given that it is not already iterated over so if the count of that puts a node I'm on if it is zero which means that it is not iterated over eventually like previously then only I will do this operation if it is already fitted over I will not do that and then I will keep on doing this and increment the answer for every level and the end if at any state I find out the like the final node a final State I want to reach to if I insert that inside the you can say set which means that I have already edited over that particular node and return the answer which means the total number of steps that I've taken at the end if I am not able to reach that particular state or maybe uh that is not present inside the whole Gene bank or in the whole graph the answer is minus one that's it that's your logic and the cool part for this particular problem if you still have any doubts you can match now in the comment box of this particular video I will see you in the next one till the recording and bye | Minimum Genetic Mutation | minimum-genetic-mutation | A gene string can be represented by an 8-character long string, with choices from `'A'`, `'C'`, `'G'`, and `'T'`.
Suppose we need to investigate a mutation from a gene string `startGene` to a gene string `endGene` where one mutation is defined as one single character changed in the gene string.
* For example, `"AACCGGTT " --> "AACCGGTA "` is one mutation.
There is also a gene bank `bank` that records all the valid gene mutations. A gene must be in `bank` to make it a valid gene string.
Given the two gene strings `startGene` and `endGene` and the gene bank `bank`, return _the minimum number of mutations needed to mutate from_ `startGene` _to_ `endGene`. If there is no such a mutation, return `-1`.
Note that the starting point is assumed to be valid, so it might not be included in the bank.
**Example 1:**
**Input:** startGene = "AACCGGTT ", endGene = "AACCGGTA ", bank = \[ "AACCGGTA "\]
**Output:** 1
**Example 2:**
**Input:** startGene = "AACCGGTT ", endGene = "AAACGGTA ", bank = \[ "AACCGGTA ", "AACCGCTA ", "AAACGGTA "\]
**Output:** 2
**Constraints:**
* `0 <= bank.length <= 10`
* `startGene.length == endGene.length == bank[i].length == 8`
* `startGene`, `endGene`, and `bank[i]` consist of only the characters `['A', 'C', 'G', 'T']`. | null | Hash Table,String,Breadth-First Search | Medium | 127 |
138 | hey guys guess you wonder a problem at Lee code copy this will send a boy on a linked list is given such that each node contains additional random pointer which could point to any node in the list almost returned a deep copy of the list so basically we have to copy Alice rehab who each node has a random pointer so we are going to do this in OPM without any extra space let's get right to rely on it let me create a current variable that point to head now what I'm going to do is I'm going to go through the necklace and each time when I am going to create a temp variable this is going to point to current next now with the current next I'm going to do something I'm going to create a new node which will be which will have the value of current label so basically I am I'm creating a copy of the current pointer current node and I am assigning it to my current next now it might here is the next point is a copy of the previous not mode that's the end idea actually okay and then I simply the are to do anything at this end of youth and dot next will point to temp and current is equal to ten yes I think this should do it then I am going to reset my current to head this one current to head once that is done I am going to value with the same Nadi the culture because in love and go inside blue and the logic of my loop will be you know if now so if current dot random is not equal to null then let's create a menu which will happen next save some writing for me the temp dot next or so temp dot random that current dot random dot next and current is equal to 10 dot next that's it then for the third iteration alpha together note let's call it new head new minus 1 and cursor the current cursor is equal to at new head and then my current initial a student now while current not equal to null till then uh why need to do is kick the current next will be equal to currents next and I'm sorry current Carson is equal to the current cursor not next okay then current dot next is equal to cursor dot next and concern is equal to MU for dot next I have to put a condition that because current cursor is not equal to Ma Dan do this adds don't and once this is over returning unit let's sum with this code 9:32 okay now it should work but it does 9:32 okay now it should work but it does 9:32 okay now it should work but it does Oh dot next sorry yes okay guys that's it thanks for watching | Copy List with Random Pointer | copy-list-with-random-pointer | A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`.
Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**.
For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`.
Return _the head of the copied linked list_.
The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where:
* `val`: an integer representing `Node.val`
* `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node.
Your code will **only** be given the `head` of the original linked list.
**Example 1:**
**Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Example 2:**
**Input:** head = \[\[1,1\],\[2,1\]\]
**Output:** \[\[1,1\],\[2,1\]\]
**Example 3:**
**Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\]
**Output:** \[\[3,null\],\[3,0\],\[3,null\]\]
**Constraints:**
* `0 <= n <= 1000`
* `-104 <= Node.val <= 104`
* `Node.random` is `null` or is pointing to some node in the linked list. | Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list.
For e.g.
Old List: A --> B --> C --> D
InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers. | Hash Table,Linked List | Medium | 133,1624,1634 |
1,187 | hello guys welcome to deep codes and in today's video we will discuss liquid question 1187 that says make error strictly increasing so guys although this question is very easy to understand and the question description is very clear but the question is slightly a tougher level where we have to use our mind and try to derive the different test cases that can be possible in order to build the intuition so yeah guys stick with that and watch the complete video so here you would be given to array 1 and array 2 and you need to perform some operation on array1 in order to make it strictly increasing okay so what operation you need to perform is you can select any index I from the error one and replace that value with any element of the array two so what you can do is you can select one area of I and then replace it with any array 2 of J and you need to perform such operation in order to make error strictly increasing okay so in a sorted order you need to sort it in strictly increasing and you need to return minimum number of such operation to make array one uh strictly increasing okay so yeah here the patient suggests us to find the optimal answer that is the minimum number of operation so guys now let's try to look at the examples for better understanding so in the first example here we have added one five three six seven so you can see that this one then um this is uh then it's from 5 so 5 is greater than 1 then comes three now this condition is violated here at three then for six it is okay for seven it is okay so the condition is violated we at three so now do we have any elements between 5 and 6 no that can be there is no possible elements between five and six that can be inserted here right so what we did here is VD plus five with two then the array becomes something like this one two three six seven so guys although the condition of strictly increasing was violated at uh index two that is for the element three but we didn't replace this and replace the Phi with a 2 and now the array is strictly increasing in a sorted manner so this is how we solve the first example now in the second example what we did here is see initially we replace this 5 with 3 and this 3 with 4. so the final array becomes something like this one three four six seven and yeah this is uh sorted and in a strictly increasing order so yeah guys we perform two replace operation here replace with this 4 and these three so yeah we written two as our answer now in the third example here let's say we have fine now these three we need something that is greater than 5 and less than six but anything is possible no nothing is possible here so let's try to replace five with something so okay so if you replace five with one then this is not strictly increasing so this can be done so my first element of one now let's try to replace five with three so if you replace it with three it's okay till here but the next element three now this three is not greater than the previous we need strictly increasing so we again have to replace this then let's say we replace it with six so now the array because something like this one three six the next element is six okay now this 6 is not um in the strictly increasing to previous so we need to replace it with something but do we have any other option there is greater than six no we don't have any options so yeah we return minus one here so whenever we find it is impossible to sort the error in strictly increasing order we simply return minus one so yeah guys got this clear till here so you can see that uh for each element of the area one there are some options like we can either replace that element or not to replace yeah so based on the option we try to find the best or optimal solution in return uh the minimum number of operation right so guys let's take one more example and try to understand how these things can work so let's say you have arable like this one two three seven six and ten so up till here everything was sorted now at this point the strictly increasing uh condition of array 1 is violated so we have to do something right got it and in the error 2 we have numbers like 14 15 and 5. so one option is what we can do is we can do one two three seven then replace the six with let's say with 14 we replace it with 14 okay now then we also have to replace 10 so let's say we replace it with 15. now this array is sorted okay how many operations we perform we operation perform twice so the answer is to here okay now guys what another way we could solve this question let's see so we have one two three enough uh let's say we have replaced the seven with five so we have replaced and placed here five then six okay the condition is not satisfied till here and 10 is also satisfied so by performing only one replace operation at 7 means at an uh index 3 with a value 7 we can get the array 1 in assorted in a strictly increasing certain manner so guys we have to identify that what is the best approach to solve this question that means we have multiple approaches or multiple choices or you can say options so one option is this that we have it this is the second option so guys whenever we have multiple options to solve this so to solve the question what we can think of is we can think of recursion right because in recursion what we do is we try to take one of the option and try to find thumbs up if we don't get we try to take a step back and try to find different answer with a different approach or different choice so this is a typical recursion plus memorization question where we first perform the recursion and then memorize the recursive solution and guys building up the intuition for this type of question is in easy because by the test case that I have shown you that either if we have replace six uh six and then ten they need to result 2 but if you have replace seven then it would result one so we have different options or different choices in uh to replace what element and with what right so yeah whenever we have this type of situation when we where we have to make uh different choices and choose the most optimal Choice then we can perform recursion plus memorization also one thing if you note the constraints for this question is uh the size of the array both added one and error 2 is up to two thousand so this is a very good indication that yeah we can perform n Square solution but if this type of situation if you have size of the array up to 10 to the power 5 then you must be clear that big of n Square solution won't work recursion plus memorization won't work and in that case we have to perform some n log n solution so guys uh observing the different test cases as well as observing the constraint can help us to get the idea uh to build the intuition okay now let's move ahead in this question so here what was our observation state that if array of I is greater than add of I minus 1 that means the current element this is the current element is greater than previous element so if this is the case then we have two options right we can replace it or not to replace it okay so uh if already it is solid then also we can replace it as we have seen here that up till 7 the array was ordered then also if we perform replace operation it was beneficial for us so if in this condition we have two choices we can replace and not to replace and in this condition let's say add of I is less than equal to the previous that means the current is less than equal to previous in this situation we have only one choice that is to replace right to perform replace operation because this will violate the condition of add a 1 being strictly increasing so if this is the case then we definitely have to perform the replace operation and yeah based on these two observation uh we will derive the approach okay but guys wait a minute so this intuition part is very much Clear we have choices to perform replace and not to perform replace operation So based on that we uh can decrease the solution and then memorize it now one question I would like to ask you is whenever you perform a replace operation that is to replace any nums uh any integer from array 1 with array two then what would be the best possible choice of replace so that would be nothing but a smallest number greater than the uh previous so let's say if you are performing replace on array one or five so if you want to perform replace operation on this so for that you have to check the value of the previous element and you need to find the smallest number greater than previous inside added to option so we need to find smallest number greater than previous inside added two of J okay why so if we don't do this thing what will happen so let's say in the same example above so we have one two three seven six and ten and array 2 has 14 15 and 5. so what if we have replaced the 6 with 15 okay so that then that would result in 1 2 3 7 15 and the last remaining element would be 10 now there is no way possible to replace 10 with any numbers from the erectum that is greater than 15 yeah so this array can never be sorted okay right so this array if we have replaced the 6 with 15 then the adder would never be sorted so this is not the best way to get the answer right so whenever you are performing replace operation try to replace it with the element that is uh greater than previous but it is smallest right so here if you want to replace the six point any element then we have option of 14 as well as 15. so we need to choose the element that is greater than the previous but it is smallest so that is 14. so if you have uh choose here 14 and the array would be something like this one two three seven Fourteen and for 10 we would have still have the option to replace 10 with 15. so in this case at least we have some result instead of -1 result instead of -1 result instead of -1 so yeah whenever you perform replace operation try to replace it with the smallest number greater than the previous okay things are created here now the next thing so if you go and try to search what is the best possible replace number from the edit two then you travel the complete editor then that will result in big of uh because M time complexity let's say array two sizes M and you need to search this number there is smallest number greater than the previous then that will take big of M time compensating so one thing we can do here is we can sort error to object because the any indexing whenever we are performing replace operation whatever may be the index of the J uh add a two of J it doesn't matter we can perform it with any index number so yeah what we can do is we can sort the array 2 of J and then use binary search to find this number which number smallest number greater than the previous so this can be done in big of log of M time complexity if we sort array 2 of Gene and then we perform binary search so to find additive of J that is the best possible candidate for replacement what we can do is we can first sort array 2 of J and then apply binary search binary Searcher offered wrong they both will take off long end time upper one will Implement binary search internally yeah this is the htl statement and this will use binary search internally so yeah guys combining all these things let's code it okay I know there would be a few more doubts in your mind but we will try to solve them with the help of uh four only okay so the first step here is uh let me try this so first step here is to sort the sort added to option then call this answer uh solve function that will store the answer now inside the solve function think of this is nothing but a base condition so whenever we have process all the elements of the arrayment we would stop and return zero that means by return zero because no more replace operation are required now so yeah we will return 0. okay then skip this for right now we have two choices operation one and operation two so operation one that means make simply consider this is make replace operation so this is our option one and this is not to make okay so we have two options right either we make the replace operation or not to make now if we have some condition like this with if error if I is greater than 0 okay and the current element is less than equal to previous element so this is the case where we definitely have to make replace operation if the current element is less than or equal to previous element then we have to make replace operation now how we will make replace operation for that we will choose the smallest number that is greater than the previous so we applied here upper bound so upper bound will find us the smallest number greater than the previous so we uh perform upper bound from the added two of begin until added to offend to find the number that is greater than this add a 1o that is this is nothing but the previous so this is previous element and we say subtracted at the beginning so that we get the index okay now if this index lies inside the range of array 2 what we can do is uh and also it is greater than the previous then we can simply replace it replace array 105 with edit workshe and then perform this recursive call okay why we added one because we already performed one replace operation here so we added one and then call recursive function to get the answer from the remaining and F1 right so uh pass this I plus one and yeah and for further solving I will also replace it with the previous num so whatever number was present in the previous week also we again change that area of I this is like a backtracking state okay so this is one thing now the second thing here is if the number if the current number say current and this is previous the current is already greater than the previous so in this case we have two choices right either to make replace operation or not too many so the first thing we did the same thing here this code is the same that is we are performing the replace operation so the same thing we are finding the upper bound and then performing the replace recursively calling this solve function and storing in option one and you are then again changing the value also we have second choice right to us or the second option that is not to perform the plus operation so in that case don't add this one because we are not performing anything and simply call solve function correct with height plus one and in the third case here both the time we check if the I is greater than zero but there might be a case where we have to perform the place at the zeroth index right just think if you want to make a replace operation at the zeroth index with what element you will replace you will surely try to replace it with the smallest number right if because we don't have to compare if it is a zeroth index element then that can be the smallest number right so what we would do is we would simply check the zeroth index element of array 1 because zeroth index element of array 2 error 2 is already sorted so now we don't have to go and find upper bound we have we want to make error zeroth index as small as possible so we will choose the smallest element I if it is already small then we won't perform replace operation as we would perform right so if so this Thing Remains the Same inside this so this if condition Remains the Same in the second option we already have that yeah don't perform any operation so simply go and find the answer for I plus 1 okay the minimum of both option one and option two Choice One and choice two right now guys one thing I forgot here why 2001 buy this so if you go and look at the constraint the size of array is error one size is uh is less than equal to two thousand okay so the maximum replace operation you can perform is 2000 because the size of adamant is itself two thousand then you won't perform more uh replace operation than this number so yeah we have to return some inch Max right in order to handle the situation when we when the strictly increasing array is not possible so if you have seen this in the third example so here strictly increasing add a was not possible in order to handle this case what we did is we simply returned some maximum number that will state that yeah it is not possible see instead of this if you written -1 then perform this mean written -1 then perform this mean written -1 then perform this mean operation then minus 1 would be minimum but in our case minus 1 means answer is not possible so we have handled it in this way that instead of minus 1 we took some maximum number and if the answer is greater than 2000 okay they're greater than the size of the maximum size of the idea we can have in the input that in that case simply return minus one else the answer okay got it clearly no now count this question that how we can perform memorization if you do until recursion then it will surely give you time limit exceeded now guys in order to perform memorization we have to find what are the changing variables or Changing State of our recursion dream so if you to take a look at this function called the parameters so one is one parameter that is I or the index of the array one we know yeah it is changing but for another thing is changing is array one the values of the different indexes of the error is changing because whenever we perform t plus operation at a one values change right so these two things are change now one thing more to note here is let's say you are checking for any current element you only check uh this current element if it's greater than equal to or less then based on the previous element that means you only perform comparison of the ith element with the previous element right so guys what we would do is we would store two things one this index that is changing and second to keep track of the current state of ID 1 we would store the previous element because on the previous element only we are making some changes making the replace operation to handle so whenever if whenever you see this I minus 1 I minus in they both are previous element so yeah we would store two things one is the index sign and second is the previous element okay so we took a map a pair of map uh a map with a pad as a key and Inked as a value so in this pair we will store the I as well as the value of the previous element now if I is 0 then we will simply take minus 1 as the value of the previous element right if I is a 0 then there is no previous element so yeah that's why and here also we store um on memo is it the answer in the same way that is the I as well as the with previous element and yeah and here to perform to reduce the number of sub problems we perform this memorization step where we find that whether we are actually calculated the answer for the current step in some previously right so if you calculated the answer previously for the current state then we simply return the answer okay so I hope you guys have now somewhat understanding of what we are trying to do in the code if you guys have still any doubts then do try to write The Code by yourself you try to make different test cases by yourself so that you can get better understanding okay now talking about the complex videos so here the complexity let's talk about the time complexity first so for one is let's say sort so for an example let's say the size of added one is a size of added 2 is m now the sort function will take M log of M time complexity in the first case then we are calling the solve function okay now guys talking about the time complexity for the solve function so let's say the size of added one is n and size of added 2 is M now here what we are storing is inside the map we are storing the index I as well as the previous element so let's say so time probability M log of M based on this sort now adding how many different values are possible for I so that is M different uh not M it's n different possible values okay so n multiplied how many different values possible for the previous so we are storing a previous element right how many different values possible for the previous M different values are possible because the previous element can be replaced by m different elements of the array2 so for each index M different possible values are there for the previous element so these many number of states are possible in a recursion tree also for each time for each state what we are doing we are trying to find the upper bound and it will take log of M time complexity so these upper bound will take log of M time complex setting so this is our overall time complexity for the solution and talking about the space complexity is also the same as this is a workspace complexity right plus some recursive stack will be occupied right 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 this video And subscribe to our Channel thank you | Make Array Strictly Increasing | print-foobar-alternately | Given two integer arrays `arr1` and `arr2`, return the minimum number of operations (possibly zero) needed to make `arr1` strictly increasing.
In one operation, you can choose two indices `0 <= i < arr1.length` and `0 <= j < arr2.length` and do the assignment `arr1[i] = arr2[j]`.
If there is no way to make `arr1` strictly increasing, return `-1`.
**Example 1:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,3,2,4\]
**Output:** 1
**Explanation:** Replace `5` with `2`, then `arr1 = [1, 2, 3, 6, 7]`.
**Example 2:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[4,3,1\]
**Output:** 2
**Explanation:** Replace `5` with `3` and then replace `3` with `4`. `arr1 = [1, 3, 4, 6, 7]`.
**Example 3:**
**Input:** arr1 = \[1,5,3,6,7\], arr2 = \[1,6,3,3\]
**Output:** -1
**Explanation:** You can't make `arr1` strictly increasing.
**Constraints:**
* `1 <= arr1.length, arr2.length <= 2000`
* `0 <= arr1[i], arr2[i] <= 10^9` | null | Concurrency | Medium | 1203,1216 |
1,260 | Hello hello everyone welcome back to my channel listen to today's events two problems shipped to degrade show in this problem yagya na today grade of size ambros and when unit to shift grade of time in the operation element subscription will go to columns and elements vich Will give an example of a day after operation Times of the giver Person's time A&M to restore the kid with this A&M to restore the kid with this A&M to restore the kid with this form Find out the shipping like Times of water Final merit is that minute written on ok so let's understand with example so basically Lipstick example to here I am college student effective two times to butter shifting means let's take now the position judgment aa the book is position and introduction starting for unlimited dictionary app the right choice is dam ko amardas grade five walk rent a position to very nice Yaar tu shift shifting one time means the thing which position which will be seen in role same but column will increase first to low medium to solve this will be the true one and column to go ok only a sorry waste 1090 problems create vitamin E ok sona need your support way swift welcome hai torch light similarly for example the again happy shivdaspur sunavai nasai hai precepts current position in one kumawat grade one ko - it's position dena ya 250 grade one ko - it's position dena ya 250 grade one ko - it's position dena ya 250 against tobacco cessation broken and light show water witch failed position grade simro Mother Column Will Increase Bye Oh And Listen Will Come From This Year To This A's Rank Morning Bud From Debate How To Shift Get Meaning Of How To Move It Damini Column Bread Member Real Position Now Welcome Aware Of How To Times Leadership Okay So Basically 1727 triad meaning of something is increase column so you might be thinking what will happen in a flexay the element who is the first the right place element which was talking about is back i and let se withdrawal tweet current position s grade of that This Current Position This Red Wine Might Be Morning Shift This Position Vikram Grade One End This Column Increase One To That Is It Will Come Here That Aapke Naav Again Later You Listen To-Do List This That Aapke Naav Again Later You Listen To-Do List This 515 Welcome To The Meaning It Will Go To The Next The process was right but here call me too right two plus one will be 3 your loved ones other dozens of columns that rights will model set with the problems 380 Enfield has 200 columns on is but will not Govind Singh Rohit will go through the next9 the right Thing to Connect with Design Plus Minus A Ruk Sudarshan Have Left To Shift and Subah Sacrifice Procreation Like This Will Go to the Next Row Main Office Call Rate Similarly Dushman Free Will Go to the Next Rot This Position On That Aapke ₹100 Anurag Vyas 208 Which How That Aapke ₹100 Anurag Vyas 208 Which How That Aapke ₹100 Anurag Vyas 208 Which How They Can Not Protect oo 180 Take Care Expert 12123 Learn Today Research 3456789 Se Puck So Let Me To Election 2012 Tomorrow Morning See What We Have To Basically Shifting Means Cheating Year Means Digestive Volume Head One Column Hydrate Hai Tu Sappoch late se this period are want to three letters for 2nd year 45678910 have to shift that from me how to shivdaspur how to times in this very easily debit the sentence is worshiped vitamin for welcome bhaiya very simple i just because the same thing rate explanation specific View Greed and Disadvantages of Exile for Example of it Share Other Side Effects Lipika 100 Beds Reserved One Position for It's a Comment Or Leave Your Comment for Us That Police Cheating Writing Grade It's Kind of Similar Scored of Similar to Shipping in the World in a Wonderland Pandey Devendra Yadav Shift Same On The Water Of Wick Convert Basically First Formal Wear Converted Into Something Like This One Day Are Worshiped In The World In The Great Ho Okay Sochati Elective With The Wind To Example To Let Me Please Remove This I Will Show You What I'll be doing your wrist latest one vehicle related 500 attacks done tech juice 5.5 writing for her attacks done tech juice 5.5 writing for her attacks done tech juice 5.5 writing for her 123 45678910 festival is 2002 x345 68 that came from her calligraphy tips disposition and climate grade one to maven were write stances five disposition and worshiped on torch Light Bill 16 Two Times You Indulge 202 Hawa Will Do It A Hello How I Will Do It I Will Find Out The Corresponding To Give One Right Corresponding To This Position What Will Be The Index Here Demanded A Okay What Within Ther Soul Can Find It Difficult for visiting decided today speech on that this weapon is a torch light distic basically index is this one how they can find your index in theory induction one-dayer index in theory induction one-dayer index in theory induction one-dayer how they can find which can find your secrets who is the current row water level controller is multiply rouse and the number of columns the total number of columns so let's take details in aa rahi to total number of columns sachiv and hai a plus tak current column what is the current column strong system induction pandey c how to control is vansh multiplied by total Number of Columns Guest Column Ship Is A Plus Current Columbus What One Two's Formula Into One Plus One Four To Index In Theory For This Position To Mount Will Be Points Statistics That Your Ayub Artist That Sufia The Forest Walking See Basically Hadith And Math Tricks To Here this was coming year and skimming share this please come in heading support will be coming ok subah 510 total number of water dharohar so dat paneer position feature plus seat Vivo and what is the number of column that was held on ok so let's know Vinod And a position of justice for element if index in theory hear tips for plus how many types to times dot in the new position with six that coastal so I don't know of platforms 750 less decide on that without hear communication is six new index the this sex That various you need and hear Big Guide New Index But Know How Will Convert This Index Back to the Question Read Them Into a Temple New A Vaikuntha to Convert Right That Person's * That Person's * That Person's * Indexes See Duty Concept You Have Any Questions or Just Remember This Website Will Never See They Have Tried To 1282 Roll Number And Column Number To Havaldar Tis Born In Six Divided By Total Number Of Columns Will Give The Roll Number This Book Is Divided By Total Number Of Columns Watan Ai The Statistics 222 A Subject Uprising Number And A Column No. 15 Small Dealers and Statistics Model Ras Teen Which Will Be 0f Hua Tha Reminder Right to Day Two Zero No. 0 Column No. 2 Ko Manzilon Here This Will Come After Shifting To Time and Time Again for This Side Tomorrow Morning Yasmin And change invited as great which gives any problem will not change this year will begin you matrix light of in size and wearing 1550 place in which a position in five wickets left was new position for a day main tu kya machine on ki rahit similarly when To Lucknow Distance Between Father And Ethos Element Difficulty What They Are Doing Bihar Currency Row And Column Number From Dead Be Converted Into Index In Mind They Are This That Ritual Behavior Of Inquiry Shift's Times The Next Position In The Convert Dost Back Which Index Back To Dhronic Column Width Neuron Column that is intermediate in the matrix, it is systematic, the output is improved, handed over to the industry, if the industry takes the approach, then code lineage center code volume and care, which one, what are they doing, the fifth number and the number of India every day, follow them. The benefits of view of creative stamp emotion eyes of various districts and India going to key element in tomato side view of finding out with evidence in sector index in the plus to ok tu shifted and white widow in models ramp roshan because total seat mighty bayah top Boundary The Indices New Updated Daily Point Is My Gautam Sunil To Do It Agro Center Embraced With Total Number Of Elements In The Year E In The Work Done What They Are Doing Fine You Coordinator From This Volume 10 Index In 2ND Year The Indian wear update shifting diet value always ready to the new values new coordinator you are you see in the temple improve and find to time to death for this will be president love we tullu so am process with time complexity a specific tubewell also TVR but gift A B Coming Distance Factor Attempt Factor For Basically Choose Out Here Its Time Space Complex Will Not Be Counted But E Feel Contents Should Be Victorious And Tricks Are Naturally But This Basis Of Food Recipes Not Counted And Vedic Contexts On Ka Pehla Phanda Problem And Approach But they need information please like it to my channel thank you for giving advance. | Shift 2D Grid | day-of-the-year | Given a 2D `grid` of size `m x n` and an integer `k`. You need to shift the `grid` `k` times.
In one shift operation:
* Element at `grid[i][j]` moves to `grid[i][j + 1]`.
* Element at `grid[i][n - 1]` moves to `grid[i + 1][0]`.
* Element at `grid[m - 1][n - 1]` moves to `grid[0][0]`.
Return the _2D grid_ after applying shift operation `k` times.
**Example 1:**
**Input:** `grid` = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 1
**Output:** \[\[9,1,2\],\[3,4,5\],\[6,7,8\]\]
**Example 2:**
**Input:** `grid` = \[\[3,8,1,9\],\[19,7,2,5\],\[4,6,11,10\],\[12,0,21,13\]\], k = 4
**Output:** \[\[12,0,21,13\],\[3,8,1,9\],\[19,7,2,5\],\[4,6,11,10\]\]
**Example 3:**
**Input:** `grid` = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\], k = 9
**Output:** \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m <= 50`
* `1 <= n <= 50`
* `-1000 <= grid[i][j] <= 1000`
* `0 <= k <= 100` | Have a integer array of how many days there are per month. February gets one extra day if its a leap year. Then, we can manually count the ordinal as day + (number of days in months before this one). | Math,String | Easy | null |
445 | hey guys welcome back to another video and today we're going to be solving the lee code question add two numbers of part two all right so in this question we're given two non-empty linked lists representing two non-empty linked lists representing two non-empty linked lists representing two non-negative integers so non-negative integers so non-negative integers so for example let's just look at the input over here so we have 7 2 4 3 and 5 6 and 4. so both of them represent a set of numbers so the most significant digit comes first and each of their notes contains a single digit add the two numbers and return it as a linked list okay so we have 7 2 4 and 3. so in this case 7 over here would be the most significant digit and three would be the least significant digit so what does that mean so in simple words that means that the number here is going to be seven two four three well in other words seven thousand two hundred and forty three and this over here is going to be 564. okay so you may assume that the two numbers do not contain any leading zeros except for the number zero itself okay so let's just look at this uh input over here so like i said earlier we have 7243 and we have 564. so when you add those two numbers you get an output of 7807. now how do we actually end up outputting this so what we want to do is we want to output this as a linked list and it's going to follow the same rules with the largest or the most significant value coming first so seven eight zero seven thousand eight hundred and seven all right so now let's see how we can actually do this kind of step by step and yeah all right so the first step is we're given two linked lists so linked list one linked list two and we need to convert that into a number so let's convert this into a number so how are you gonna do it so it's pretty simple uh i'll just show you how we do it for l1 so we will have a value and let's just call this our number so this value is going to start off at zero so this over here is an integer and another way to kind of say that is that it's a base 10 value what that means is that the zeroth place is 10 to the power of zero multiplied by whatever value we have the tens place is 10 to the power of one the hundredths place is 10 to the power of 2 and so on and so forth so kind of using that what we're going to be doing is we're going to take our zero and each time we're going to multi sorry not zero the num each time we're going to multiply num by 10 and then we're going to add whatever value we're on so now we're going to zero multiply by 10 which is both zero and we're gonna add seven so far our number is seven so now we're gonna do seven multiplied by ten which gives us seventy and to that we're going to add two so giving us seventy two so hopefully you understand how this is gonna work so then by the end of it you're gonna get to get 7243 and for this you're going to end up getting 564. all right so these are our two numbers so now what we need to do is we need to find the sum of it and well finding the sum is pretty simple we're just going to end up adding them so since we're just adding them this over here is actually going to have a value seven thousand eight hundred and seven so seven thousand eight hundred and seven all right so here it gets a little bit tricky so now the question is how do we actually end up uh outputting this so in simple words it's just going to be seven pointing to h pointing to zero pointing to seven right in a linked list but how exactly do you do that so now we wanna get each of these numbers so one thing that we could do is uh we can kind of separate these numbers and get each of the number itself how do you do that so what you would do is you would each time you would divide it or you would do perform the modulo operation by 10. so what that does so 7807 mod 10 would give us the number seven and after we get the number seven that gives us the first digit so now what we're going to do is we're going to divide 7 8 0 7 divided by 10 and take only the integer value we're gonna uh kind of skip or not talk about or ignore the decimal values so now we have 7807 divided by 10 which is 780.7 780.7 780.7 and we're just going to take it as 780. okay so now again we're going to 780 mod 10 so this gives us the next digit which is zero then we're going to end up with 78 and that's going to give us 8 and then we're going to get 7 and that's how we end up getting all our numbers but now the problem with this is how exactly do you add it to our linked list so uh we have seven zero eight seven and if you add in uh if you end up adding it in that order you get seven pointing to zero pointing to eight pointing to seven and the number that we end up getting is seven zero eight seven but the actual number that we're looking for is seven eight zero seven so obviously these are not the same thing so what we're going to end up doing uh one thing that we could do pretty simply is over here we have seven zero eight seven and we're just going to end up reversing it so in other words uh the 7 0 8 7 is now going to be 7 pointing to 8 pointing to 0.27 pointing to 0.27 pointing to 0.27 we just reverse it and that actually ends up giving us our answer which is eight hundred and seven okay and we will see one more way which i actually found uh and it's pretty clever uh how they did it so i'll just show you that method as well but for now let's just stick with this okay so let's see how we can do this in code and yeah all right so we're gonna start off by finding out the two numbers so let's just define them as number one and number two they're both going to start off with the value of zero and let's just start off with finding the first number so to do that what i'll do is i'll go inside of the first linked list which is l1 and we're going to do while l1 what that means is we're going to stay inside of this linked list as long as we're not on the very ending and we're going to stop at that point because the very ending is going to have a value of none okay so over here we're going to change our num1 value so num1 is now going to be equal to num1 multiplied by 10 and after that we're going to add it with whatever value we're currently on and to do that we can just do l1 dot val all right now each time we need to kind of move our pointer to the right by one bit so to do that we can just do l1 is equal to l1 dot next so you can just imagine that we're starting off at the head and then each time we're moving to the right and once we reach the very ending we're not going to go inside of the statement because while l1 is not going to be true so now we have the first number and all we need to do is we need to do the same thing but instead we want to do it for the second number so i'll just be changing all of the ones over here so instead of while l1 we'll do while l2 and instead of l1 we'll be referring to l2 right so just change all of that to two basically okay so we have that and now we have the two numbers ready so now let's find out the sum and to do that as well pretty simple you do just do num1 plus num2 all right perfect okay so we got our sum right now and now the goal or what we really need to be doing is we want to uh convert it into a linked list so this linked list over here is going to be the reverse of what we need the leftmost value or the head node over here is going to be the smallest the least significant value and the other side is going to be the most significant value so we just need to reverse that later on so we're going to start off by actually creating a dummy head okay so let's just call this our head for now and this over here is going to be well an object of the list node class and it's going to have a value of zero all right so why exactly uh are we doing this so the reason we have a dummy head is because we can just add everything to be the next of it and it's just gonna make it a lot easier and when we're returning it we're just gonna do return head dot next okay so kind of keeping that in mind we need to uh store the head value so to do that i'll be storing it in a value called current okay and the reason we're doing that is just so that we can refer to it later now one more thing is that we're giving it a value of zero so why are we giving it to value of zero so the reason to that is right over here so over here we're going to check if the sum is equal to zero so if the sum is zero then we can just directly return the head that we have so in that case we're just gonna be returning head list node zero so yeah we're done okay but if that's not the case well we need to do some stuff and we need to add uh on to our linked list so uh i'll just be copying it over because i think it's kind of repetitive so um this is what we have so while the sum is greater than zero each time we do that we're going to keep going inside in simple words uh until so in this case uh we have 78 then we have 7 and then when you do 7 divided by 10 you get 0.7 and well 0.7 when you round it get 0.7 and well 0.7 when you round it get 0.7 and well 0.7 when you round it down because that's what we're doing it's going to give us a value of 0 and well 0 is not greater than 0 obviously so yeah so in that case we would not go into the while loop so now we have head dot next is equal to list node okay so we're creating a list node object and the value of it is going to be our sum mod 10 okay and i went over how we're getting that value and now what we need to do is we need to change the head pointer so head is equal to hat dot next and simultaneously we're going to change our sum value so we're going to be doing integer division by 10 and the reason we're doing integer division is well we want an integer value and basically what it does it's always going to be rounding it down okay so we have this and uh now we have a linked list but now what we need to do is we need to reverse it so i'll just be copying over the code for how to do that and then we'll explain uh okay and then i'll go over how we can do that all right so over here we're going to start off with a previous pointer because while we're reversing it what we're really doing is we're storing what the previous pointer is so in the very beginning the previous pointer over here is going to be none and the head value is going to be current.next current.next current.next so now the question is why is it current.next current.next current.next so if you go up over here remember that current is just kind of like a pointer to tell us what the starting of the list node is and like i said earlier the starting is going to be a value of zero and that's just going to be a dummy head so everything to the next of it is actually what is being counted so that's what we're actually going to have head is going to be equal to current dot next so now we're going to go inside of this uh as long as our head value head has a value and it's not equal to none so over here we have a next node and this over here is going to store the head dot next and over here what we're going to do is we're going to have head dot next equal to the previous value so it's just pointing to its reverse and after we do that the previous pointer is going to uh equal to the head and the head is going to be equal to the next value so literally all we're doing is reversing it step by step so 0 over here is going to be pointing to 7 the 8 is going to point to 0 and the 7 is going to end up pointing to 8 and writing this like this is the same as writing it as it is like this so 7 then 8 then 0 then 7 okay so yeah um so this is one way you can do it and if you submit it should get accepted okay so the submission was accepted so another way i actually found this uh online so what they did was pretty clever and uh let's just kind of go to that directly so how they did it was basically head dot next is over here right so head dot next equals to list node sum mod 10. so we went over why that works and how that works but one more thing that they ended up doing is they made the self.next value doing is they made the self.next value doing is they made the self.next value equal to whatever the current node over here is so it is kind of confusing so i'll just kind of draw it out to better explain it so in this case uh we have 7807 right so the first thing we're doing is where we have a node uh which is zero all right let's just get rid of this so seven eight zero seven and we're gonna have a dummy node with the value of zero so now what we're gonna do is we're gonna point this value over here to uh the number seven so while we are pointing it to the number seven this over here is going to store the head dot next value and it is also going to have the head dot next value so how exactly does this make sense so basically what's gonna happen now we have seven and now when we're about to add zero what's going to happen is head dot next already points to zero so in this case uh what we're doing is head dot next for zero is going to end up being the number zero itself so we now have zero and actually don't think of this as a zero but just think of it as a dummy head so we're pointing this to zero and now this zero is automatically going to point to seven because head dot next equals zero and we already defined the head dot next is equal to seven so that points over to seven so now we have eight and it's going to do the same thing instead what's going to happen is that head dot next over here is now going to be at zero and so is head dot next all right so basically all we did is head dot next equals to list node sum and we want to tell it what the next value is and well in this case the next value is just head dot next okay uh and now let's submit this oh actually we need to return a value as well so the value we're going to return is going to be our current dot next and one more thing that we would need to be doing is will you get rid of uh head equals to head dot next because basically we're not going to be moving the pointer each time the pointer is going to stay at the same value or at the dummy head the entire time right so we're not changing the pointer we're not moving it so we can just get rid of this over here so let's submit this and this should also get accepted and as you can see both the solutions were accepted so yeah thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you | Add Two Numbers II | add-two-numbers-ii | You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
**Example 1:**
**Input:** l1 = \[7,2,4,3\], l2 = \[5,6,4\]
**Output:** \[7,8,0,7\]
**Example 2:**
**Input:** l1 = \[2,4,3\], l2 = \[5,6,4\]
**Output:** \[8,0,7\]
**Example 3:**
**Input:** l1 = \[0\], l2 = \[0\]
**Output:** \[0\]
**Constraints:**
* The number of nodes in each linked list is in the range `[1, 100]`.
* `0 <= Node.val <= 9`
* It is guaranteed that the list represents a number that does not have leading zeros.
**Follow up:** Could you solve it without reversing the input lists? | null | Linked List,Math,Stack | Medium | 2,1774 |
1,779 | hey everybody this is larry this is me going with q1 of the buy weekly contest 47. find nearest point that's the same x y coordinates um to be honest hit the like button to subscribe on drumming discord if you're here thanks for your support because i don't really think this is a hard problem you can look at my code but it's just basically implementing what they tell you to do um you just have a for loop to kind of look at what's closest to x and which goes to i and then you just keep track of it um i don't know if there's anything complex about this uh this is all one space of end time for reasons that you can kind of look at it's a for loop and it has only constant number of items i'm not going to dig into this that much after that so let me know what you think if you have any questions then just ask in the comments and you can watch me solve it live during the contest next one go slow on the clicking button huh oh and same x or y all right whoops hey uh thanks for watching uh hit the like button subscribe and join me on discord let me know what you how you did this contest and how you doing each of the problems um yeah have a good day have a great weekend you know to good health to good mental health and i'll see you next time bye | Find Nearest Point That Has the Same X or Y Coordinate | hopper-company-queries-i | You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each `points[i] = [ai, bi]` represents that a point exists at `(ai, bi)`. A point is **valid** if it shares the same x-coordinate or the same y-coordinate as your location.
Return _the index **(0-indexed)** of the **valid** point with the smallest **Manhattan distance** from your current location_. If there are multiple, return _the valid point with the **smallest** index_. If there are no valid points, return `-1`.
The **Manhattan distance** between two points `(x1, y1)` and `(x2, y2)` is `abs(x1 - x2) + abs(y1 - y2)`.
**Example 1:**
**Input:** x = 3, y = 4, points = \[\[1,2\],\[3,1\],\[2,4\],\[2,3\],\[4,4\]\]
**Output:** 2
**Explanation:** Of all the points, only \[3,1\], \[2,4\] and \[4,4\] are valid. Of the valid points, \[2,4\] and \[4,4\] have the smallest Manhattan distance from your current location, with a distance of 1. \[2,4\] has the smallest index, so return 2.
**Example 2:**
**Input:** x = 3, y = 4, points = \[\[3,4\]\]
**Output:** 0
**Explanation:** The answer is allowed to be on the same location as your current location.
**Example 3:**
**Input:** x = 3, y = 4, points = \[\[2,3\]\]
**Output:** -1
**Explanation:** There are no valid points.
**Constraints:**
* `1 <= points.length <= 104`
* `points[i].length == 2`
* `1 <= x, y, ai, bi <= 104` | null | Database | Hard | 262,1785,1795,2376 |
59 | what's up guys today we're gonna talking about electrical problem named spiral matrix 2. this is a medium category problem the problem is asked by several giant companies like facebook microsoft linkedin oracle etc uh the problem is pretty straightforward and here is the estimate is given a positive integer n generate and n cross n matrix field with elements from 1 to n square in spiral order if you guys don't know about the experiment then please google it we'll first discuss about the problem and then we'll go through the code we must fill up a 2d array from 1 to n square just like this 1 2 3 4 5 6 7 8 9 let's go through another example guys this is a two-day array and guys this is a two-day array and guys this is a two-day array and for this example n is equal to four and we have to build an array like this one two three four 5 6 7 8 9 10 11 12 13 14 15 and 16 and this is the end point and this is our starting point so what we have to do first we have to print this line in increasing order from starting column to ending column after that we have to print uh from starting row plus one to uh till ending row after that we will print the left side from column end minus 1 uh till column starting point and then we'll paint on this side after that this side and this side finally we can use a counter variable to restore uh every grid's value like if we start from this grid and we will set this counter to on after every iteration we will increment the value of the counter uh so what we uh next iteration it will be two then three then four then five in this order and we have to keep every time our range uh just like this arrange is formed is starting column to ending column and this range is formed starting row to ending row if you consider this those two grid those are from starting column plus one uh till ending column minus one we have to for uh we have to store four values strictly uh row start row end column start and column end okay now let's see what will be the code for c plus so we need a big 2d vector we declare the vector and we need a size n which will in uh every contain also inverse which means every uh here we declare a vector size n which means the vector will contain n rows and every row has n elements right vector size n so we declared a n cross n vector after that we need four fixed variable which are row start row in column start column end as we add zero and ending as n minus one so we need a counter variable for counting every time the grid which value we will store in the grid okay now what we have to do we have to uh use loops for storing the values into the grid okay while row now what we will do guys uh first we will fill up this row first for column start column and plus and we can extra values in the answer i mean 2d vector array counter plus because every time we need a increment value from the previous grid okay so here is the tricky point what we will do here is the for the first row our row is fixed right so we'll use here row start and we will use our i so every time this will ester values in the first row grid like one two three after that we have to go on this portion from top to bottom okay but for this we have to uh already we start first row so we'll start from uh second row to row in okay so we'll increment the value of row start so we will use another loop but this loop will start from row start identical row in plus and the value will be our answer counter plus this fixed right and this is the in column okay so this is column end and this will be i after this done we have to decrease the value of column 8 because we done this column right so now again we have to check that we are still in this conditions or not if the condition not fulfilled yet then we can use another loops if row start row 8 then we will use another loop for column start i managements and here the values will be answer counter plus class so what will uh the index hello okay we are using for this row right here the row is the ending row okay after the iteration finished we will uh decrease the value of row end if the column is the is within the range or not so we are doing this for this line right and this will start from uh row in till row start after this we have to run a loop row end start i minus answer i call on start counter plus after this we have to increase the value of the column instead okay and this will work to redone the answer we have to start the counter from on okay because the first grid is one let's run this code those works fine let's submit it accept it thanks guys for watching this video | 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 |
871 | hey everybody this is larry this is june 12th the 12th day of the june nico daddy challenge i feel like i've said this before but anyway uh yeah today's problem is minimum number of refueling stops i usually solve this live so this is my disclaimer so if it's a little bit slow just fast forward and all that stuff um yeah so i know that you come here just for the weather report in new york and right now is back to 66 degrees which in a reasonable um temperature uh what you may call it like in a metric system it's like what did 15 or something so it's much chillier so uh now i have a shirt on again uh thanks for caring i still have to fix my ac though anyway okay so cars traveling from a starting destination target which is used up to okay what each station has a gas and each station has this little gas to get a car because stuff uh what man maybe i have trouble reading maybe that's why i've been doing struggling lately what's the least number of reviewing stops that needs to do okay so the things are big enough that you wouldn't even think about dynamic programming uh at least on pseudodynamic form pseudopolynomial dynamic programming anyway but there are only 500 stations so let's see so the target is one what was target again so you're trying to get out guys so you're trying to go to see because they don't okay so yeah so they try to get to this distance there are stops along the way and the start view is one uses one liter of gas when transferring all the gas from the station to the car all the gas from the station that's a lot of gas thing but okay huh so i mean so this is a it's gonna be essentially a breath first search problem this is the shortest path uh the way that you kind of think about the shortest path is well it is uh where did i see it there yeah the least number of refueling stops so the shortest path in that each the cost of each path is just stopping once um and the key thing to note is that what we talked about earlier with respect to n is equal to 500 meaning that the graph is at most n squared or v squared if you want to go by graph rhetorics um and we square bring or we bring 500 and edges will be being five squared if you want to build a complete graph will be fast enough um especially for breakfast search which is which has a low constant overhead so that's probably what i'm going to end up doing uh yeah and basically you just add each location is that good enough is it um let me think a little bit for a second i think so it still may be breakfast search but the tricky thing is that there's an additional dimension with respect to the state so hmm oh but i think that's okay i see because the tricky part about this problem is that you have this concept of fear right and you can run out of feel um well that's the that's actually the easy part is running out for you but the hard part is that you may want to stop or you may have extra feel from a previous stop that um yeah let's see yeah so what i wanted to say is that so you may have extra feel from previous stop that you may want to make multiple stops and then accumulate those few to get to the longer place right for example i don't know if this is a good example but you can imagine like if this one is 50 or some number you can imagine that you take three gas states you need to go to all three gas stations to get to the last gas station um in total but the observation here and it might not be easy i don't know if it is uh and it's kind of greedy so i don't know if it's correct which is why i don't know if this is easy which um which is that for each station that you arrive at they're only and for each station k i don't know if this is sorted if not that's fine we could sort it uh okay it does seem like that the distances are short sorted um so we can just go in one direction but otherwise we can sort it anyway so that's not the limiting factor but the thing is that you know let's say we're at this station right so we have only n possible or k possible states where uh and the states are the current station and the number of stops we've made before um and then we can greedily take because we're doing refresh search so with essentially doing it in order and you can kind of there's a little bit of corollary with dynamic programming in the sense that you have to do this in order and maybe it is maybe you could think of it as dynamic programming as well um because the core part of dynamic programming is doing it in order if you're not doing it and um if you're not doing it with um top down say or you're doing bottoms up so yeah and you can still do it tops down but i think it's really convoluted uh with respect to dynamic programming because ajit station but yeah but at each station so the states are each um the station that we're at and the numbers of stops that we've made previously and those two things gives you um a number of a maximum number of gas that you can have in a greedy way you always want you know given these two parameters if you want to go at that um giving these two components to a state you always want to choose the one that gives you the maximal um the maximal gas or fuel um because the max because there's in a greedy way it doesn't make sense to choose one that's fuel with gas or less gas actually i guess but yeah okay so i think that's enough for me to get started it's still tricky though but let's see what's uh let's see what the code will take us okay so yeah so we will get to okay so usually i try to teach dynamic forum top style and instead this time i'm gonna do bottoms up but i might not even trying to think but uh which way is better but for search of dynamic programming i mean i think they're actually very similar in construct it's just a slightly different way of thinking but let's kind of go over dp real quick maybe um so yeah so dp will be the number of field that you get to at this point so okay so the first thing and i don't usually do my streams with bottoms up because i think it's easier to explain stuff tops down your mileage may vary but i think this one is more bottoms up so let's actually um be very clear on how i do it uh with respect to defining the states right so dp i sub j is equal to um let's see we're at the i've stationed ticking chase stops straight previous stops the amount of fuel we have and actually what i want to do is maybe just add the target and view at the end so then now we can just go all the way to the end maybe a little bit weird but then now that means that we put in one of the states so that we don't have the special case and that's the basic idea um so now we're going to start by putting the amount of view we have as the base case so what is the base case the base cases we have is i mean you could define the base states in a couple of ways you can also start by having a station of zero or something or zero and the starting field so maybe that's two um so you can do something like um what is it uh zero starting field that's the equivalent state um maybe that's a little bit awkward i don't know if it is but it depends on your preference but as long as you're consistent about defining your boundaries is okay so what i want to do here is that for i in range of n and this is the new n so dp of i with zero and this is of course as we use the definition here to taking zero previous stops meaning that everything is going to be from the starting field um and actually in this case we should actually have let's just do negative infinity for impossible um right instead of zero because maybe zero implies that we could get there but with zero fuels so having negative makes sense here a little bit um okay so that means that this is basically our starting field because we start from zero right just making sure yeah we um uh yes okay use of the starting location which i guess is there so starting feel minus station sub i of 0 because that's just the distance that we have to move and that's the starting field so that's our base case right and then now after we have the base case set and of course as i mentioned earlier this could be negative um maybe that's fine in that we that denotes that it is impossible um yeah do i think we have to be a little bit careful i mean i think for the starting state is fine but i think we have to be a little bit careful because sometimes you do a math in a way such that the negative could become positive for example you have a gas station later that has like a million gas then that's an error so that's actually um let's actually make that a case so that we're at least consistent about it because otherwise this would still be negative uh infinity so then now um that one do i or j loop so the transition what is the transition we might we i'm not sure about the loop ordering uh i think it might not matter i think that's why i do the loop ordering this way but now the way that i'm doing it i'm making it an n cube dp so now it becomes a little bit sketch i think i did the math a little bit long on this one to be honest my bad this 500 cube is going to be 125 million which is going to be slow because what i realized now is that i needed another loop um to make this n cube um or i think we have the states but then we do have to have another loop to get the graph um which makes it end cube i think i when i created a new state i today i wasn't thinking about it um let's see so how can we exploit this a little bit better okay i think i have and i do yeah i think i have an idea is to spray no okay i think i have another way of doing it i think i messed up here sorry friends if you're watching live or you know um hopefully i didn't lead you to the wrong direction so let's just finish off the dot and then um i'll show you why this is incorrect or this is too slow just in case uh basically this is the this is going to be max over dpi some previous k so for k and it is in range to i um so it is from or maybe some sort of push but the idea is that okay so now we have some you know this is the maximum view that we so we have to do push dp maybe so we actually want it this way so we this is if dpli is greater than i guess maybe strictly i don't know so this is the amount of fuel we have and then here we can go okay right now we go for k is in range sub n uh starting from i plus one say um yeah then you can do if so this is the amount of fuel that we have that means that we can check whether we can get from here to deep um yeah so from stations sub you know a few needed is equal to the stations uh you know so we're going from station sub i to stations k right and so we have something like this so then dp sub uh k sub j plus 1 because we're making an additional stop is equal to dp of i j uh confu minus view needed uh and then max of this because it you know you just always want to get the max uh if current view is greater than of you if you need it so that's basically the dynamic programming uh a solution and then you just go for the loop but the problem is that in this case it is going to be n cube uh which i to be honest is my bad i'm sloppy about it but that's basically the idea and this would be done if n is say a hundred this would be pretty much done and we don't have to worry about it um yeah and then there's only one minor loop that you have to do to yeah there's only one minor loop to uh see at the last station um how you know how many or what's reachable and the fewest number of stops right so basically you check d p sub n minus one of zero then dp sub n minus one of one and so forth um that's gonna so again this is gonna be n cube which is too slow so let's start over a little bit but it is a good practice in dynamic programming um i guess anything is good practice and i don't do it bottoms up enough so hopefully this was at least some word illustrative but i think i have another way of doing it uh well i have to because otherwise this doesn't solve the problem um so the thing to notice is that going from left to right um we can actually exploit the order a little bit more right because going from left to right we basically have a march of time that happens um you can think about it as a scanline e algorithm right uh in that okay you know it we take a concept that is taken here but in here um yeah in here we basically i don't know how i made the same type of tries but in here it's dynamic programming with respect to the state but here but how we i want to solve it now is actually through a scan line algorithm and the idea is that okay we arrive at every station let's take the same states that we have for dynamic programming but same logic anyway i mean it's not quite the same stage and then put up okay let's say i arrive at um and actually maybe it's the same maybe i mean i think you think about a scanline but here instead of doing this loop of going forward we can actually update we can update um we can update it in a smarter way such that we don't keep we don't need this loop so let's eliminate this loop maybe that's the better way of thinking about it um yeah okay so let's we think how we want to structure this so actually i retract what a little bit of i said it's still going to be dynamic programming but with but you can also think about it as not dynamic programming if you just think about it as a scan line going from left to right okay let's say i'm at the station but i don't have to use a stop how much gas do i have left right so now we have this state of um yeah man that is yeah that is a trickier problem but it's still doable obviously but okay so how do we want to think about this so yeah so i think this loop is correct but instead of push let's think about how we want to structure it so then now let's just say we are now at station i and we want to loop for how many stops we made and then now what does that mean right so dp of i sub j is equal to the max of so what are our states so we want to update this and the only two place so the question from a previous state is whether we are taking a stop or not right so we are so it has to be a function of dp of i minus one which is that okay so not stopping so that means this minus so this is the field that we had before and then we minus this delta and distance which is you know what the fuel needed right uh if you need it so again if you need it is just to go to station of um j sub 0 minus oops i sub 0 minus stations of i minus 1 0 right so that's a few needed let's put it outside um yeah so this is not stopping and then if we do stop then um if we do stop then it's something like j minus one minus few needed plus station sub um i plus one because this is now this is the field we added right so yeah and we could maybe add that here as well if you want just this is just obviously for readability in a very minor way uh for it you know you could see what i'm doing here i mean i'm just doing for obviously learning um but yeah um and of course this is actually the max of these two i mean in this way um yeah the of course the problem is that it might be infinity so uh so let's actually bump this up a little bit more so that we don't yeah uh so at some point it impedes a performance so let's just actually say um yeah because we want to make sure that this is the part that i'm always a little bit awkward about but and the base case is also a little different now i have to we just set the base case is dp of zero is eq is equal to um store start field my minus station sub zero yeah the distance right because that's also the few needed as we uh know this is basically it i have to handle some i think maybe let's actually write it up if you need it is greater than uh yeah we have more fuel than fuel needed then we can do this thing and then also if or still has to be yeah and this one is actually a little bit more critical because uh even though this entire expression could be greater than zero this could be negative and that would be a that would not be a right answer because that's negative even though you it comes up to be greater than zero afterwards so yeah um oops and then now we have this a sort of a scanline dynamic programming we can just go through the loop again as we said which is that four i is in range of um from zero to n uh if dp sub uh n minus 1 i is greater or equal than 0 then we return i otherwise return negative 1. oops how did that was a bad typo but yeah um that's at least one the examples and these examples are annoying to type oops a few needles not defined did i just have a typo feuded needed well that's a little bit of a sadness hmm do i have all my indexes correctly okay that's a little bit accurate all right let's print out dp oh yikes okay let's make the infinity slightly smaller so we can slightly read more okay so for this problem we have negative infinity the entire way why is that so yeah so the base case is we get to oh no this i messed up this should be i think that's this is the part that in the beginning i was saying uh yeah because this phase case is wrong so that's a short answer because yeah this base case as well um this is the base case for the first one but yeah okay so actually we want an additional base case of and this is actually what we had before so i think i messed up in removing that one to be honest uh but yeah still negative one but at least a slightly better negative one maybe let me do if start feel great and oops why am i so bad why is this one well j has to be starting from one because zero is already taken care of but that is still very wrong huh that is awkward so from feel like i've been really bad at an implementation lady i think this is roughly right but i'm off by a little bit which is you know pretty binary and being wrong but uh how much storing field we have so we have ten yeah so then here oh i see okay i forgot one base case of um i think this is the part where as i was saying earlier we had created a fake station that would have been uh much better but yeah but we had to do this of um yeah plus station so that's basically the base case of us refueling from the first stop and i guess we have to do it here as well which is very awkward oh wait because i mean this is fine maybe wait what is this swamp in this uh whoops this should be is now this is the right syntax right uh why is this wrong oh i see now it's not just that this is wrong this is that this is wrong because now you can have end stop inclusively that which makes sense okay i don't know what to tell your friends yuck i guess let's see if this oh i think when i rewrote this i left out something okay there you go because you have to still remove the fuel that is needed like i said really sloppy these days with the implementation um okay so this is expected and it's impossible but why tell me why oh because this case is very sloppy um on my part to be honest um because i think for i think we said this before which is that what i should have done is to create a send no stop station and that would have been okay um now that we look a little bit better and kind of auditing real quick um yeah it looks okay make sure that we don't put anything one more time and then let's give it a submit how do we get time limit exceeded for an n square solution that's awkward and they don't even tell you the case okay well i guess so the good thing is that we're correct but the bad thing is that we're too slow which is kind of weird because as you see i don't really do anything that fancy but i don't know why they make things such uh such pain but okay hmm mean there are things to do to optimize the space but this is just silly though to be honest um so i think at this point uh let's go with complexity real quick um and this should be straightforward in terms of complexity because this is just n square right we have two for loops it's pretty straightforward we do all of one operations each and then at the very end we do an oven loop but that's pretty much it so n squared for n is equal to 500 i don't know why this is too slow uh this is kind of annoying me trivial to be honest um i mean i know that there are a couple things i can do i could stop calling max but it's not even that many operations unless i'm doing something really weird but i passed all the cases it seems like it's just that the total time is a little bit slow for their taste and you can also optimize the speed but even at 500 squares not that much so i don't even know well like for example you can do this here and this is greater than dpi just json oops so you can do something like this because i think max function is a little bit slow but that's like really awkward right and also i would also say that uh for the for those of you who are always jealous of oh man i have to do this again uh those of you who are jealous of python uh well this is a reason not to be and also for those of you who uh who are still watching and didn't skip forward leave a comment in the comment section i want to give you props for kind of sticking with me uh though maybe i like to think that it's very informative even the wrong things that i'm doing um because i think i spend a couple of time on wrong things but i spent some time on doing things incorrectly but um ah man is still linear time solution i don't know at this point it's kind of really annoying because at n square um as this is something that i complain about right n square at n is equal to 500 for most languages this should be good um and then um but the thing is that you never know the number of test cases that they're going to give you in this case it's 198. um i mean let's say we optimize our code two times faster right well what if it fails for 400 test cases right and they don't tell you the number of test cases so that's always going to be a little bit awkward um hmm can i do a little can i be a little bit smarter i mean the thing is that these i don't do anything that computationally expensive i think python is just a little bit awkward and slow perhaps yeah i don't know that i can optimize i mean and that's just a linear time solution that i don't know about like is there linear greedy i mean if there's a greedy i don't know how to prove it so i think that's the part that i'm skeptical about and i would say that even if i like if i did uh breakfast search like i said earlier i don't think this would be um i don't think it'll be much faster so i think for cheating i'm gonna change this to another language for today um and then we'll go over other people's solutions um just to see maybe i missed something really obvious but i think like for me you know the code is i feel like it is um it's straightforward enough right so yeah how do i add something to an interview in python or in java actually i don't think that you can but maybe i'm i just want to see if i missed something let's create a newer way okay fine i mean it's fine we can just use uh we'll have to do it in um in a silly way but that's fine so yeah so basically now what i'm doing just literally translating this code to java um i do have a little bit of a java background i used to do competitive in java back in the top code of days so i'm not you know but it is also i'm really out of shape so yeah let's see so if you have any comments about my java uh let me know because can also improve on it not you know yeah oops but this is what i always say right which is that you know languages is just a tool and obviously you still have to get your tools in good place but once you learn it uh you know the hard part is always going to be the algorithms because it you know it is what it is you can probably i mean at this point i give you a lot of permission to uh fast forward through uh because this is pretty senseless and it might be boring for a little while i don't really have much to say since i'm literally just copying and pasting code uh in it in a non-cheating kind of way but it is in a non-cheating kind of way but it is in a non-cheating kind of way but it is essentially what i'm doing right like i don't like if you look at the bottom and i'm what you see on the screen is what i'm doing we look at the bottom part this is literally what i'm doing so i don't really so i hope that this isn't um you know i'm not there's no higher level thinking this code is pretty straightforward to i can actually just copy and paste even i'm going to do this for now also i have to set this up i forgot what i said today oh i see uh wait i messed this up if you need it is almost messed that up so even in uh copy and pasting i almost messed up i just needed to copy the view add input and again as i was saying um i don't know maybe there's something really fundamental i'm missing but it at a certain level this is all going to be about grind and what i mean by that is that you know you can always there are multiple routes to uh to a prom solution and you know don't give up keep going it might not be the optimal it might not be cool it might be messy but uh you know it is what is this oh yeah because now we don't add oh i messed this up because i said that i would uh handle the logic but i didn't i don't want to change what i wrote just now so but basically what you would do is just do an do a loop from the end i guess yeah let's do it that way instead um okay so this is the number of gas we have uh where are we trying to go again target if this um minus station uh target minus station n minus one sub zero so this is the few needed going from the here is greater than zero all right so this is the field that is needed so if the few that we have is squared and few that's needed okay maybe that's enough oh i mean that just this is fine but it doesn't address the part that we're here um so okay and minus if n is oops okay so this is mostly right but that's just actually if n is c well let's just special cases but yeah uh what you see me now is doing a lot of special case which is why um which is why i did the thing that i did in python so that i don't have to worry about all these weird edge cases with n is equal to zero for example so um so that's basically what i'm hacking around um okay advantage is your zero if start if the star view is greater than you go to target then we can return zero otherwise with a negative one um but yeah but you can see that these cases are not needed if i had did what i did before um and yeah let's give it a submit hopefully this time it should be good uh all correct i think i have it off by one okay so maybe this part is wrong let's see so our few is 50. so what does that mean that means that which one is target again target is 100 it's time 50 so this should be good oh i think now this has to be yeah because the end before doesn't include the last stop and now i have to include the last stop whoops like i said a lot of things change when you change some stuff so uh oh uh i this is what happens when you this is why i did it in python the way that i did it with respect to adding a number because now i have so many weird edge cases okay let's go back to that um let's just create another copy i this is such a mess uh yeah this is such a mess of what i had to do um let's just do uh ah what a annoying day um cowbooks sometimes coding is pain and this is one of those times mostly because i bring all this on lead code of course because really we should have been done 20 minutes ago but now i'm debugging silly things in uh in java and if there's a cleaner way to do this let me know in java if you're a java expert i'm doing it obviously in a way whatever kind of way but what am i doing wrong now i should use another language maybe is that not the right syntax all this time i forget new is that right okay i've just said that compiler you're so smart what i am really bad at java clearly oh no point of exception oh i see i am really bad today okay most of this looks good except for this negative one thing what why how what tell me what how did this get worse okay so i have one starting feel and it's just not going here so this should all be negative one what uh i'm really tired right now this was not supposed to take an hour i don't know what i blame it's only code this is a half hour or more that i want to get back i know that took longer under half an hour but i think the beginning i had a good time in this beginning with this problem but now that i have to change the different languages and go for all these things um it's a little bit just like silly okay my why'd i put two isn't even oh i see because the n is no longer right so i don't think that should be that shouldn't why does that matter how did that change the result why this dp sub oh it's because i don't initialize it so it just defaults to zero that's why okay a lot of silly things let's give this a minute and hope it's good what a silly thing that we had to do and this is my java solution um i'm going to go over my python solution i don't know let's see this is my python solution uh which is the same except for i just had to convert it to java um yeah let me know what you think i think we went over it a little bit um the states here kind of hopefully makes sense i'm really tired so i my apologies if i'm missing something because i don't even remember what i explained what i haven't anymore um so yeah you just have to go back to about maybe the 30 minutes mark if you missed it or whatever um that's all i have is n squared like i said sometimes this is going to be a grind uh and it could be on silly things it could be related to the judge and stuff like that it is what it is uh let's actually i was going to end it here but let's see if there's any obvious solutions that i've missed clearly uh maybe just agree because i don't know why that pipeline doesn't work dynamic programming so that's basically what we did oh there's a heap solution i guess the heap solution would i don't um but i would say they should still make it so that um this works i mean i don't i'm curious whether this actually runs quickly enough uh because for some reason um because this is literally exactly the same as my code right give a tick yeah this is pretty much exactly the same as my code so i mean maybe it's a little bit shorter but the idea is still the same so i don't yeah it's very weird i mean maybe i should have came up with the heap solution but it but given i think i was very stuck on n squared because n is 500 so there's no way that i should fail but it is what it is and then the max heap okay that makes sense i suppose i don't know i need to think about it a little bit um oh that said let me know what you think i don't know today was a little bit weird uh yeah let me know what you think hit the like button and subscribe and join me in discord hopefully this is not a uh this is not a preview of what's gonna happen during the contest later in a couple of hours we'll see what happens uh stay good stay healthy have a great weekend everybody enjoy your weekend and i'll see you later uh and to good mental health bye | Minimum Number of Refueling Stops | keys-and-rooms | A car travels from a starting position to a destination which is `target` miles east of the starting position.
There are gas stations along the way. The gas stations are represented as an array `stations` where `stations[i] = [positioni, fueli]` indicates that the `ith` gas station is `positioni` miles east of the starting position and has `fueli` liters of gas.
The car starts with an infinite tank of gas, which initially has `startFuel` liters of fuel in it. It uses one liter of gas per one mile that it drives. When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.
Return _the minimum number of refueling stops the car must make in order to reach its destination_. If it cannot reach the destination, return `-1`.
Note that if the car reaches a gas station with `0` fuel left, the car can still refuel there. If the car reaches the destination with `0` fuel left, it is still considered to have arrived.
**Example 1:**
**Input:** target = 1, startFuel = 1, stations = \[\]
**Output:** 0
**Explanation:** We can reach the target without refueling.
**Example 2:**
**Input:** target = 100, startFuel = 1, stations = \[\[10,100\]\]
**Output:** -1
**Explanation:** We can not reach the target (or even the first gas station).
**Example 3:**
**Input:** target = 100, startFuel = 10, stations = \[\[10,60\],\[20,30\],\[30,30\],\[60,40\]\]
**Output:** 2
**Explanation:** We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel. We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas. We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.
**Constraints:**
* `1 <= target, startFuel <= 109`
* `0 <= stations.length <= 500`
* `1 <= positioni < positioni+1 < target`
* `1 <= fueli < 109` | null | Depth-First Search,Breadth-First Search,Graph | Medium | 261 |
399 | Hello Everyone Welcome Tension Quiet Days Ago In Dishaon Birthday 27th September List Ko Challenge Today's Problem Missile Edison Electronic Provident Fund Should Be Placid List In The Amazing And Give The Number To Computer Classes The Video then subscribe to the Page So Let's try to understand which gives an example for its ok software can see the question raised upwards subscribe and subscribe now to subscribe my life is the question in new delhi so this video is at the end and this is by civil bittu into three idiots ok end minute handed him over loudly z1000 fluoride subscribe button - 10500 subscribe 2019 acid - 01 button - 10500 subscribe 2019 acid - 01 button - 10500 subscribe 2019 acid - 01 sir dabi suvidha express transfer for the giver example1 ok so tomorrow morning style-19 to check if left tomorrow morning style-19 to check if left tomorrow morning style-19 to check if left untreated properly 19 virgin lifting happened and real 5th same find the same Number and The Number Exist in Adheen 21.05 The Number 90 The Number Exist in Adheen 21.05 The Number 90 The Number Exist in Adheen 21.05 The Number 90 - 119 Hua Tha - 119 Hua Tha - 119 Hua Tha and Classification is the Understanding Monk Body What Like This Computer Returns The Video then subscribe to the Page if you liked The Video then subscribe to be lit quick and they can take note of just in zu ki 2.0 ki similari it can see the 2.0 ki similari it can see the 2.0 ki similari it can see the question is equal to one officer da ki i will be seen in the cases subscribe this Video give web 2.0 subscribe 10 Subscribe subscribe this Video not 25000 Notification friends subscribe quote hai allu dena hai karenge ek-ek pehlu between the quote hai allu dena hai karenge ek-ek pehlu between the quote hai allu dena hai karenge ek-ek pehlu between the two si software ko in the bab.la bab.la bab.la ki sukma electronic pollution ok so now identify the apps rights under 1751 aap us jor Android Apps on Vijay Ayush were also certified as which can easily identify this point and then you can calculate the Nehru Youth Center destroyed by multiplying brother Hello using this app lets you can always talk to Luthra to see the scene more details Jhunke Subscribe now to receive new updates Reviews and take off but subscribe to the subscribe similarly for b ki mujhe to-do sabse zor sorry bittu hai ki mujhe to-do sabse zor sorry bittu hai ki mujhe to-do sabse zor sorry bittu hai is 120 b c v n c b s c list play list listen this channel subscribe The Channel ko subscribe this committee The twist of Vijay starts from being informed and then Dr to where not to wish not to go to people displeased Returns The Video then subscribe to the Page if you liked The Video then subscribe to subscribe hai ki values wich stream end and bhairu ki values wich stream end and bhairu ki values wich stream end and bhairu humble in Maths Video give Subscribe for latest video This morning and fasting Apart from a peon Calculate Decoration Light Indication Measurements should always need 1000 villages Twitter The Video then subscribe to subscribe our related tweets subscribe in use size poll related tweets subscribe in use size poll related tweets subscribe in use size poll Me Sure Status subscribe to the Page if you liked The Video then subscribe to the Video then that and hold to internet is ok now we can deposit build or function something like this then I will define function later subscribe screen's light list free 200 purification questions Dot right side edifice the value of the question ok to ise miding subscribe this Video subscribe boys pe hua hai nivesh ke sunavai fikar rich person Delhi stuffing slide reddy will be latest limited equation only but andar hum ise pass inter result double default subscribe this Video not support to subscribe our It's Something Like This That And Will Be Absolutely Equation Bluetooth Dot 10 Wickets In The Worst Position subscribe this Hair Faster Pimple And Valuable In The Sun Dot That Video New Year 2069 That I Will Call Map Sometimes Scholar In Witch Method 40% A special guest of With Particular Start In Witch Method 40% A special guest of With Particular Start In Witch Method 40% A special guest of With Particular Start Pimple New Mahal Samay Price Will Reduce Number Five Lines App Kholo Hai To Way Can Avoid Samay Strife And Content Me Something Like Friend Mukesh Soni Polish 40% Subscribe To Stop This Not Avoid You 40% Subscribe To Stop This Not Avoid You 40% Subscribe To Stop This Not Avoid You Have A Point And Half Hours Update The Key Right So Let's Get Benefits And Updates Video The Depend Subscribe Button On I India Server Key Will Be A B Less And Key Delicious 200 It Is Not Exist In Amazon New Said A Point Now Being Written Update of Fluoride Map Don't Get End Against Hate Discus and Key Will Be Stopped and Went for the Thing subscribe The Video then subscribe to the Page if you liked The Video then subscribe to subscribe and subscribe that no-12 updates and double 1620 e Like ur that no-12 updates and double 1620 e Like ur that no-12 updates and double 1620 e Like ur right method using which you can calculate and he will return w and he can update in more jis brothers ib so e will define third calculate result my tablet diesel something like this and but thursday must subscribe research 182 should be someone s Dot Net A I N V 2.5 Ft Get Hero Film Give Me A I N V 2.5 Ft Get Hero Film Give Me A I N V 2.5 Ft Get Hero Film Give Me The Starting Point To Zafar DMC Posts For Students In Softwares Daughter And Will Be 108 Youth To Do The Great subscribe The Channel subscribe comment and subscribe the Channel subscribe Video Subscribe 16 That Guddu's Trekking Note Switzerland's Setting Open Single Soon After Defeat Friends Talk Show Host Also President of New Administrative Academy 2512 Return Award Toe Will Contest All The Results For Giving Rise Toe Follow She Also Pandit Will Sleep After Calculate Video Hours Withdrawal Like it depends on the software and sleep patterns for things which seems that during value second will be OBC string and under last thing will be mother he bright so e will benefit of him officer stored in the notes sex free mode ok so let's Do Something Like This OK School Noida to subscribe to the Page if you liked The Video then पिचर गिफ्ट थे इफिजी एपिसोड़ 122 है कि स्टर्ट एंड विच दोस नहीं इस है कि स्टर्ट एंड विच दोस नहीं इस है कि स्टर्ट एंड विच दोस नहीं इस नॉट Want to listen with determination and नॉट Want to listen with determination and नॉट Want to listen with determination and similarly destroy and talk to oo that and end debate on news9 decision no tomorrow morning minutes not possible then why friend daw or returning -1.2 hai you friend daw or returning -1.2 hai you friend daw or returning -1.2 hai you start and ignoring and I ok sun first condition nou want to see the Quality of life by c-voter Hello how can they of life by c-voter Hello how can they of life by c-voter Hello how can they return 120 se subscribe kar do ho gaye ind 2nd feb 7 same din can they return 120 defensive and 120 b our map ok so now सित्छे इडली इडली सुस्क्रिबे subscribe and subscribe the Channel subscribe I just started the hotspot of my contact is that encephalitis vote then share according to going to determine it's written a map don't get started that chart get and focus on twitter real life to IDBI that subscribe 100 schools subscribe to That the way you tell about the last elections, more than 90 subscribe The Amazing Thursday Video Subscribe Now that boat circular diet that Ayodhya 9 and travels and the possibility of midnight fall for boys in two take miding were double Latest Name Tiles Entry Only And They Are Going To Take In The Map Don't Get Started Days Instant Map Scientific Entry Set Of The Movies Scene Setting Show The Map Election Banyan Tree Your Hair Right Now Right I Am You Through Which Everything Is E And Sunao I Will Check Only That I Entry's Body Engaged David Is Particular Knotted Virvar Citric Acid Set Contents Is This Entry Also Ko Start Get That Dry Vyas Twilight Its Contents Not Interested Not Wanted To Leave It Is Not Go Into Bill Hans Tell Me The Map Ok so it is not considered Sudhir Mishra of this particular notes to visit so I will take only temporary is absolutely double s declared double dip tell me I will my tab where hair oil this a middle class family should observe will calculate Video subscribe with 220 will do this Roti Ko Kah And Dar Indian Women Se Bigg Boss Minute Two Drops Steel 10 Se Zinc Shampoo According To Two Five Withdrawals Current Contents Only One Not Hidden From National Subscribe Button - Features - From National Subscribe Button - Features - From National Subscribe Button - Features - The Video then subscribe to the Page if you liked The Video then subscribe to the * In the Destroyed Household Vitamin E Store Vouchers Defiant Sports Ministry Done Something 1992 Because Divya Badminton Something Radhe Shyam Conflict and So They Can Return - Shyam Conflict and So They Can Return - Shyam Conflict and So They Can Return - 148 Singh Datas President She Results for Not a Good Sunhra Kapil Free Things on Time Is Trick Pawan Singh Is The First Woman President Seduction Hearing Result And Chronic And Subscribe To Ok Figure Services Accept So Let's Check The Midning Us Loud And Subscribe The Channel To Subscribe And Subscribe The Amazing Video Subscribe 200 In It Shikari Map And Key Cheese Pe Nishan Dedh Map And 118 Dars Id The Video then subscribe to the Page if you liked The Video then subscribe to subscribe our Channel subscribe and subscribe the Video then subscribe to the Ki Wah Diya Bisht and United of BSNL Rights 1.25 More than 120 options Have 1.25 More than 120 options Have 1.25 More than 120 options Have Video not support Were Fighting for a Two See Ride Soil and Will Have Two One Say ZuluTrade 2098 Setting of the Day Every Twelve Years Only One Will Be the That Wishes Paste Absolutely December Subscribe to Simply This Hair Mask Were Will Be See and You Will Be Amazed 10 Subscribe Incident Question Is The Meaning Of This Channel Subscribe | Evaluate Division | evaluate-division | You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits. | Do you recognize this as a graph problem? | Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path | Medium | null |
704 | hey what's up guys it's Nick white - hey what's up guys it's Nick white - hey what's up guys it's Nick white - tech encoding stuff on twitch and YouTube do all the leak out stuff so if you would do leak code check out my other videos this is just the explore page which helps you learn like everything you need to know pretty much it gives you like good tutorials so a binary search is one of the most easy and commonly used algorithms in like all these problems and interviews it might be one of the first things you're asked so one of the first things you learn in class so given a sorted in ascending order integer array gnomes and n elements in a target value are to function to search for targeted gnomes so yeah basically you're just given an array of numbers like this one and then you're given a number that you want to look for and you just return the index that it's at so zero one two three four would be nine and if you don't find it then you return negative one so it's pretty easy binary search is just searching the middle so it's like when you look for someone in a of a page in a book you open in the middle and then you know keep opening in the middle so let's just write this so if gnomes dot length is equal to zero we're just going to return negative one we're not gonna be able to find it because the array is like the length of it isn't zero so there's nothing in the array and then otherwise we're just gonna have our left bound zero go right down so beginning and ending in that seat indices then we're gonna have our main loop so I'll left is less than or equal to right we're just gonna do calculate our midpoints so the middle of the array was the left our left boundary plus our right minus left boundary to be accurate and then we have our conditions here so if our numbers of midpoints if the middle of our array is equal to the target so first place we're gonna search it directly in the middle if that's equal to what we're looking for then the great we're just gonna return let's actually in the midpoint will be the index so perfect else if numbers of midpoints it's greater than target that means that the target is gonna be on the left side it's binary search only works on sorted arrays guys so that means yeah numbers of midpoints greater than the target so we're gonna want to keep going on the left side so we're gonna get rid of the right side so to get rid of the right side we're gonna make our right bound equal the midpoint minus one that'll eliminate the whole right side of our search base it's basically just cutting the array the search base in half each loop through this while loop else we're gonna do left equals left is equal to midpoint plus one because that would mean that we're gonna go on the right side and that's pretty much it I'm gonna need just do return negative one if you can't figure out so submitted it accepted first try there we go really easy simple there's a lot of talking around me because there's I'm in a library but yeah that's binary search you're just searching the middle of the array eliminating the half that it won't be on each time because it's sorted so you know that when you search the middle if your target is less than the middle it's gonna be on the left side so you can just delete everything on the right and keep going on the left and in a sorted array that's gonna be a way faster way to find what you're looking for then you know a linear scan where you go through every element because instead of you know looking if you're looking for the number 10 in a 10 LM in an array and it's sorted binary search you're gonna go 5 you know 8 and then 10 or something like that 5 7 10 or something in a linear scan you're gonna go one two three cross 79 times so it's a lot faster in some cases thank you guys for watching and check out my other videos and I'll see | Binary Search | binary-search | Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to search `target` in `nums`. If `target` exists, then return its index. Otherwise, return `-1`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[-1,0,3,5,9,12\], target = 9
**Output:** 4
**Explanation:** 9 exists in nums and its index is 4
**Example 2:**
**Input:** nums = \[-1,0,3,5,9,12\], target = 2
**Output:** -1
**Explanation:** 2 does not exist in nums so return -1
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 < nums[i], target < 104`
* All the integers in `nums` are **unique**.
* `nums` is sorted in ascending order. | null | null | Easy | null |
928 | hi friends welcome back today we are going to solve one very interesting and hard coding question it's on lead code 928 minimize malware spread 2. so as you can see this is quite likeable problem from life dislike ratio so we will understand this problem uh we will uh with couple of examples in today's session um and i'll explain you the logic how we can solve this problem and we'll also go through the java solution for the same in today's session uh before we start uh just wanted to mention that this channel is to help people in their java jk and coding interviews on this channel you will find more than 400 different varieties of solved coding problems that can help you in your coding and java interview preparation so please subscribe to this channel now also whenever i solve any interesting and coding questions important uh problem i often create videos on this channel so that others can benefit by watching those videos they can also understand the logic behind the problem and they can also understand the java solution so make sure you click on the bell notification icon so you won't miss any important future videos so let's start with this problem 928 on lead code this is a hard coding problem minimize malware spread 2 so what they are saying here is uh basically uh is they are going to give us a adjacency graph right and there will be some initial nodes that are infected by malware right some initial nodes which are infected my malware so for example i created one sample graph here so we can use this graph uh for our uh explanation so you will understand it more this is a big graph so i uh specifically created so that i can easily explain this problem so this is what the input is given to us so graph input is given this is the adjacency matrix right so it means that which node is connected to each other nodes it is given here right so they are just saying that some nodes are initially infected by malware whenever two nodes are directly connected and at least one of those two nodes is infected by malware both nodes will be infected by malware this spread of malware will continue until no more nodes can be infected in this manner so what they are saying basically is for example let's just assume uh that um if let's say node 2 is infected basically let's say right so what they are saying is whatever is connected to node 2 will also get infected so it means that 1 will get infected from 1 0 will get infected on this side uh 2 will in fact 3 will in fact 4 will infect 5 five will infect six like this right so this is how the malware is spreading basically right so one infection will be spreading to the adjacent nodes and this is kind of a chain reaction basically right so that's what they are saying so suppose there are uh initial uh like final number of nodes which are infected with malware in the entire network after the spread of the malware stops we will remove exactly one node from this initial infected nodes completely removing it and any connections from this node to any other nodes so what they are saying is let's say for example in this case the two node is infected let's say for example right so they are saying that um we will let's say remove this node from this network so if we remove this node then what will happen in the network so i'll just erase something so you will easily understand how what happens right so um i don't know if there is a any eraser here uh yeah i think this one is the eraser maybe yeah this one is the eraser let me just erase this for example 2 is infected if we decided to remove this node 2 basically from this one right so now we don't have a node 2 because we removed it right then what they are saying is after this removal we want to find out how many nodes will be infected right so that's what they are saying and return the node if removed would minimize the m initial uh if multiple nodes could be removed to minimize m initial return such a node with smallest index so let me just put it back so basically what we are doing is this is the graph that is given to us as an input and initially they have given us what nodes are infected so in this case node two and node four are infected these no two nodes are infected basically right so um let's just first understand how the adjacency graph works right so this is important because this is the graphical representation i created using the input graph right so for example if we are looking at this 0 row 0 right so 0 is connected to 0 which is obvious right this node 0 is connected to 0 because each node is obviously connected to itself so 1 means it is connected right then we go to this point basically so 0 is connected to 1 so we put a h between 0 and 1 right then that's it 0 is not connected to anything else right now we go to the next one so we come here right now um this is node 1 basically right this is node 0 this is node 1 because we are start uh using it with zero based indices right so now node 1 is connected to node 0 that's why we put 1 here so you can see that node 1 is connected to node 0 and obviously node 1 is connected to itself because every node is connected to itself and apart from that node 1 is also connected to node 2 so as you can see node 1 is connected to node 2 right so like this we will go through this is the adjacency graph that is given to us this is for node two right this is for node two so node two is connected to node one as you can see node one right one is here so node two is connected to node one node two is connected to itself which is obvious that's why one is there and node 2 is also connected to node 3 right so node 2 is connected to node 3 and that's all for node 2 right there are no other connections for mode 2. so i just took this graph and i just graphically created this uh graph so you can understand uh the solution in a better way right so what the problem is saying is this is our network let's say and these are our nodes from 0 to 6 right and these are the connections that we have shown here so initially node 2 and node 4 they both are infected so if we remove the node 2 how many nodes will be infected so let's say if we remove node 2 from this one right so i'll just uh use the eraser to show you how the we will just kind of simulating that we are removing node 2 right so let's just remove this node 2 for a minute so node 2 is not there now right so now we have to find out how many nodes are infected so now node four will in fact basically node four will infect node three node four will infect node five will infect node six so total how many nodes are infected four nodes are infected if we remove node two right if we remove node 2 total 4 nodes are infected these nodes are outside so infection will not reach them because they are not connected now to this network right so now we will simulate removing node four now right now let's remove the node four so we removed node two we saw that there are total four nodes that will uh be infected if we remove node two now we will remove node four and see how many are infected basically after removing of node four right so let me show you that we removed node four right now let's take a look how many are infected now so now two will infect one will infect zero in fact 3 will infect 6 right and 6 will infect 5 so how many nodes got infected 1 2 3 4 5 and 6 total 6 nodes are infected if we remove 4 total number of infections are six right so you got this much actually right so you got this much idea so now let's put it back so let's just quickly write what happened actually right so removal right removal let's say removal of two how many nodes got infected if we remove two four not got infected what happened when we removed fourth sixth node got infected right if we remove four so basically what the problem is asking us to find out is we have to find out a node which will do the minimum infection right minimum infection that is what is important right minimum malware infection basically or malware spread right so minimum malware spread which one is giving minimum 2 is giving minimum right if we remove 2 we are getting only 4 nodes which are infected so this is the minimum so we have to return 2 as the answer basically for this problem right so we wanted to remove node 2 because that will create minimum number of infections right so this is what the problem is asking us to find out minimum malware spread right so um if multiple nodes now one there is one catch here right there is possibility that there will be multiple nodes which are causing the same number of infection spread right or malware spread same number so what should be written in that case then in that case we should return the node which has with minimum index right minimum index we should return in that case so uh so for example if let's say in one example let's say there are two nodes one and two which are causing minimum in uh in infections for it so which should we return we should return one because it is minimum index right so that's what they are saying actually so um i hope you got the return with the smallest index right so i hope that you are getting the idea uh what the problem is and uh that we are trying to solve in this decision this is a hard problem so um whenever there are hard problems it becomes easy when you actually plot a graph like this right when you create a graphical representation it becomes easy for you to understand when there are hard problems many times right so now we understood the problem so how we will solve this problem so what we will do is we will do we will use a very famous techniques called as dfs right depth first search or depth first traversal and how dfs works is uh it actually will use dfs on this adjacency graph so we will simulate that we are removing a node for example let's say we remove this node let's say right then what we will do is we will kind of removing this node and whatever nodes are remaining that are infected we will do dfs on them right so how the dfs will go now for example 4 is remaining node if we remove 2 and 4 are infected now we are kind of removing two so now we have to go through all the remaining infected nodes so for example in this case we will start doing dfs from node 4 and we will do like we will do dfs right so four to three then three two six and then six to five so all these nodes are connected they will get infected because four is infected and we will keep count of how many nodes are getting infected using this dfs right so now as you can see four node got infected once we do the dfs right so this one we applied dfs uh when we are removing node two now let's say that we are removing node four right we are removing this node four let's say right we are removing this node four so now we will have to do the dfs on the other infected nodes so other infected nodes is what two is other than infected node so we will do dfs on two how dfs will go so two will infect one will infect zero so again the call so because we are going in depth right going in depth that's why it is dfs so now we cannot go any further right we are at the end so the call goes back here and it explores other path now what is the other path 2 3 so 2 to 3 and then 3 to 6 and six to five right so this is how the dfs go again the dfs call now will go back from five to six and six two three and three two one and we will keep count of how many nodes got infected in this process right how many nodes so one two three four five six so six node got infected basically right because four we will not consider because four is now removed right so apart from that six node got infected right so six nodes so i'll just write six nodes so this is how we will use our dfs and we will keep track of the minimum number of nodes that gets infected right so now in this case the minimum number of nodes when we are removing node 2 correct because 4 is the minimum then 6 so we will consider whatever is the minimum right so this is the approach we will take to solve the problem this is the logic using bfs um so i hope you are clear on the logic uh how we will be implementing the logic right so we will actually take this in initially infected nodes for example two and four are infected nodes right we will simulate by removing uh one so we remove this one we go through the remaining and we will do the dfs then we re like we remove two then we remove 4 we will go through the remaining infected nodes we will do the dfs right so one other thing before we actually start looking the logic is if in this example you can just consider that let's say let's just uh consider for a sake of explanation that there is one more node for example which is infected let's say node six is also infected so we have now total three nodes which are infected two comma four comma six right these are three infected nodes which are initial right so this is initial so now how our approach will work we will first remove two we will go through this four and six both nodes which are infected right and we will try to see how many total node gets infected but with four and six right then we will calculate that now after that we will remove four we will take the remaining nodes which are infected what are remaining nodes now 2 and 6 we will take and we will calculate how many total nodes get infected after only removing 4 right with node 2 and 6 after that what we will do is we will remove six and we will go through the remaining infected nodes so remaining infected nodes is what two and four so we will go through them and we will calculate how many uh nodes are infected with two and four because of two and four right and then we will decide which node to remove actually right which will minimize the malware spread right so this is what our approach is actually so we are going through all the remaining nodes right all the remaining nodes so for example if we are removing things we are going through all these remaining nodes not just one mode right so you got the idea basically so now um this is the idea of our logic so we can just go ahead and i can show you the java code now so once you understand the logic then it's not very difficult the implementation so this is the big graph that i was just testing actually is the same test case that i shown you uh so let's take a look at the minimal marker spread so graph 2d matrix is given to us this is the adjacency graph right so um and initial is the nodes uh this is the array of initially infected nodes right so this is the adjacency graph as you can see this is the adjacency graph right so this is given to us and i already explained you how that adjacency graph we can use to plot this graph basically right so first thing we wanted to check if the initial has a length 1 then we will just return initial 0 basically because there is only one node which is there in the initially infected nodes so we can just directly written initial 0 in that case right then we will create a min value variable it is of integer.max value will it is of integer.max value will it is of integer.max value will initialize it and minimum index we will create it is 0 because that is what we wanted to return at the end right minimum index so that variable we created here after that we are going this is our main for loop which will go from the initial dot length right so initially whatever is infected this is this for loop ends here and this starts here right so initially we are going through like uh basically all these infected nodes one by one right we are going through one by one this infected nodes we will create a set of integers to capture what nodes are infected because of that node actually right so um after that what we are doing here in this for loop is we are actually so for example um i was just showing you this example right when we assume that there are three nodes initially infected right so let's just take that same example two comma four comma six so this is the initial nodes what are infected right so what we are our approach is doing is we are going through this initially infected nodes one by one so we are first we are going through this node right and now we are going through all these nodes which are actually remaining right so um as you can see 0 to initial dot length we are going again and if i is not equal to j means if that node is not we are considering what we are doing here is we are simulating that we are removing that node basically correct i is not equal to j means and then we are passing uh we are calling our dfs function right so what we will do is we have a dfs function let's say right so dfs function we will call on 4 and six right first we will call it and four then our dfs will get called on the other one right six basically right so we will not call it for two basically that's what we are doing right when next time when we are doing it for four next time our dfs will get called for two and six right two and six and a six right so this is what because we are trying to simulate that we are removing this node basically for example right and then we will try to calculate how many nodes are getting infected after that removal so that's what we are doing in this for loop right uh so once this dfs is done for all the remaining nodes in the initially infected list then we now know that how many nodes are infected by because our infected set will get populated with all the nodes that are infected because of this dfs right after the removal of that node so i'll just do a print out here to show you how it uh works in detail when we execute the code here what we are doing it we are checking the in infected set size now if we are seeing the infections are less than our minimum value it means that we are finding a node which is uh infecting less number of nodes basically then we wanted to take that node right because it is spreading less number of infections so in that case we will just update our mean value to infected set size correct and the mean index will be initial of i that we are actually looking at this i is the one that we are actually simulating that we are removing the i th node basically correct initial of ith node right so initial of i is the index of that we will update that minimum index now there is another case where we are actually seeing the uh infected site size it is equal to the same as the minimum value we had seen before it means that this node that we are actually processing is also infecting same number of nodes that we had previously seen so which one should we take then in that case we should take the one which has smaller index right so this is what we are doing here it will take the smaller index because math dot mean of initial of i and min of index will take the minimum right mean index here because this is given in the problem that if multiple nodes could be removed to minimize then we have to return the node with smallest index so this is what we are actually implementing there right so this is what we are implementing here so we will keep doing it uh in this for loop we will simulate that we are actually basically we are removing node four node two then we are removing node four then we are removing node six and we will at the end we will get the value a minimum index here that is the node that will cause the minimum number of infection spread right because of the logic that we have implemented correct now um this is the overall logic we will look details of our dfs method which is important method now right so this method returns void and it takes graph which is the which is input graph that is given to us then this is the infected set that we wanted to capture all the nodes that are infected after removal of the node right the current node is the current node that we are processing and remove node is the re the node that we are actually removing for this simulation right so for example what i am going to say is when we start we will start simulating that we are removing node 2 correct so this is that removed node right this remove node is that node 2. so here what we check is if infected does not contain the current node right means it the set already should not contain that node right and our current node is not should not be equal to remove node if this is the case then we will add this current node into our infected set correct because it will get infected so we'll add it to our infected set the current node and what this one we are doing is we are going through the um graph right which is now correct connected to the current node right the current node which are connected to the current node we are going and if there is an h between the current node and the node that we are looking it is equal to one means there is h means they are connected then we will recursively call our dfs on it right we will recursively call now the current node will be j basically right because j is the one that we are processing so current node we will pass this j here when we are recursively calling the dfs function right so what we are doing is when we are actually let's say we are um let's say we are uh removing node two basically right we are removing node two so we will go through node four let's say right and we will call uh we will go to from four to three and four to five because they are connected to four right again we will go from three to six because three is connected to six right so this is kind of a recursion right it's basically a chain reaction you can call or you can call it recursion right recursion so this is what we will keep calling whenever there is a h we will keep calling dfs right so this is how the dfs works so it will ultimately get all this infected set will get populated with all the infections uh infected nodes basically right at the end of the dfs and after the end of the dfs which will happen after this for loop we know by this infected size how many nodes got infected after we removed that initial of i node right so uh we will just print it out to show you how it works also so um and then this is our logic that i explained we will check the infected size with the minimum value right so i think this is pretty detailed explanation of how our dfs works and how we can solve this problem the malware spread problem so we should just go ahead and take a few test cases to execute the code so this is the test case that i was showing you so now here two and four nodes are getting infected correct so we'll take our original uh case so now we have seen that two if we remove two four nodes will be infected if we remove four six nodes will be infected so which one we should prefer number two right so let's go ahead and execute this code and make sure it works so as you can see 2 node 2 is the correct answer because it is also telling us what happens right after we remove 2 how many nodes are infected 4. if we remove 4 how many nodes are infected 6 right as we have seen here so let us also modify this example little bit and test the example with modify modified example let us say instead of 2 4 let's say we have um or we can just remove this edge right we can remove this edge so we are modifying this example little bit for our testing so we will remove this edge right so from this edge three to six we will remove okay so what we have to do is we have to go here uh we have to go to the third one zero one 2 3 and 3 2 6 edge is there right so this one we will put 0 here so now there is no edge between 3 to 6 and our initial we will put as let's say our initial we will modify this initial as uh two and three right so if we remove two what happens and if we remove three what happens right so let's uh update this to two and three and rerun this example so we'll check it out what happen oh actually once we remove the edge from 3 to 6 we have to also remove from 6 to 3 right so 6 2 3 also we have to put 0 here we forgot that so we will just put 0 here now right so let's rerun so now they are saying that after we remove node two we will get four nodes so we have seen that after removing node two we will get four nodes uh let's just quickly see that so you will know so let's simulate that we are removing node two right now how many we will get three is infected so three four five six so total four are infected right so total four are infected which is correct now let's remove node three so now if we remove node three how many gets infected two only two is infected now right so two will in fact two one and zero so total three are infected right so three are infected so we will take three basically which is because it is causing minimum number of infection spread so um so i think you are clear with this we can just go ahead and take a couple of examples from them uh their examples here so let's take the third one first so this is the third one so third one we are expecting one as the output so we are getting one which is the correct answer because one is causing only one node to be infected right and zero is causing three nodes to be infected so this is the example that actually we are looking at i think uh this one this is the example actually that we are looking at right so 0 and 1 are infected so if we remove node 0 then how many infections will happen if we not remove node 0 1 2 3 will happen right if we remove zero what if we remove node one how many infections will happen only one because zero will be infected two and three two it cannot reach because we removed one right so only one so we should remove one correct so that's what that's why we should remove one it is only causing one infection if we remove zero it will cause three infections right if we remove zero it will cause three infections because one will affect two and two will affect three right so um let's just go ahead and do a one go for all their examples so um as you can see we are putting 0 1 which are correct answers we will remove our system out it is not required it is just to show you uh the stack trace so now we are good to go we can just submit our solution so our solution got accepted by lead code it is uh almost 23 percent uh faster than other submissions which are done online and 24 percent better on the memory usage so this is the way we can solve this lead code heart problem 9 28 minimize malware spread 2 this is also quite likeable problem and this is also one of the hard problems on lead code so um as i recently solved this problem i found this problem quite interesting and i just thought that it's worthwhile to create a video to share the logic and the solution in java so others can see how to solve this problem and they can also learn from this uh video about this problem if you are new to my channel there is a dedicated playlist on my channel called as lead code and lean code solutions it has all sorts of different problems that includes breadth first search depth first search matrix problems graph problems binary search tree problems coding questions related to strings linked list optimization problems dynamic programming problems and lots of logical questions and those are the questions previously asked by big technical companies so if you are preparing for any coding rounds of interviews make sure you go through those videos that will definitely uh help you in your interview preparation to become more and more confident in your coding uh interviews try to practice different varieties of problems try to use different techniques so that will boost your confidence if you like this video if you find this video helpful and if you like the way the video has been created with this whiteboarding session examples and java code then please give it a thumbs up to this video give it a like to this video also subscribe to this channel your subscription to the channel is really important because that is the way the videos can reach to more people goal of the channel is to help as many people as possible in their coding interviews uh many people struggle in their coding uh interviews so i just wanted to help them by showing them how different problems can be solved using different techniques so they can also learn from these videos more about problem solving um they can also get confident in their solving uh interviews uh by looking at these different varieties of problems that typically appear in the coding rounds of interviews also one simple tip i wanted to share is when you are practicing for your coding rounds of interviews make sure you practice using some whiteboarding websites there are lots of whiteboarding websites nowadays you can choose one of them and you know practice your solutions a practice to explain your solution step by step and why it's important because in real interviews uh it's more about your communication skills how well you can communicate how well you can explain your solutions to a team of people to a group of people how well you can go step by step uh so you know the more you practice the more confident you will become and that will certainly help you in your interviews if this tip and if this videos are helping you then please comment about it on these videos that encourages us to create more such a good content of videos so others can benefit from it so uh do comment on these videos how the videos and how the tips are helping you whenever i solve any important and interesting coding questions i always create videos on this channel that i often create and post so make sure you click on the bell notification icon so you won't miss any important postings here keep coding keep learning keep practicing and thanks for watching these videos | Minimize Malware Spread II | surface-area-of-3d-shapes | You are given a network of `n` nodes represented as an `n x n` adjacency matrix `graph`, where the `ith` node is directly connected to the `jth` node if `graph[i][j] == 1`.
Some nodes `initial` are initially infected by malware. Whenever two nodes are directly connected, and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.
Suppose `M(initial)` is the final number of nodes infected with malware in the entire network after the spread of malware stops.
We will remove **exactly one node** from `initial`, **completely removing it and any connections from this node to any other node**.
Return the node that, if removed, would minimize `M(initial)`. If multiple nodes could be removed to minimize `M(initial)`, return such a node with **the smallest index**.
**Example 1:**
**Input:** graph = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\], initial = \[0,1\]
**Output:** 0
**Example 2:**
**Input:** graph = \[\[1,1,0\],\[1,1,1\],\[0,1,1\]\], initial = \[0,1\]
**Output:** 1
**Example 3:**
**Input:** graph = \[\[1,1,0,0\],\[1,1,1,0\],\[0,1,1,1\],\[0,0,1,1\]\], initial = \[0,1\]
**Output:** 1
**Constraints:**
* `n == graph.length`
* `n == graph[i].length`
* `2 <= n <= 300`
* `graph[i][j]` is `0` or `1`.
* `graph[i][j] == graph[j][i]`
* `graph[i][i] == 1`
* `1 <= initial.length < n`
* `0 <= initial[i] <= n - 1`
* All the integers in `initial` are **unique**. | null | Array,Math,Geometry,Matrix | Easy | null |
974 | hey what's up guys this is chung here so today uh let's take a look at this number 974 subarray sums divisible by k so basically you're given like array a of integers and you need to return like the sub array right which means the contiguous uh non empty list arrays that have a sum which uh divisible by k right so for example we have this uh this array a here and the k is five so we have seven sub-arrays in totals so we have seven sub-arrays in totals so we have seven sub-arrays in totals which is divisible by five right so this one yeah so remember zero is also divisible by k because right so zero divided by k is also equals to 0 that's why 0 is also like a another value right so here's the constraints right so the length of the two three thirty thousands right so for this kind of problem you know the uh you know every time when you see like this continue contiguous like sub arrays you know it's always it's very common to use a prefix solution for it you know so let's see how can we solve this kind of problem and assuming we have a running sum right so because you know it's very like i said it's very common to have maintained revenue sum right at the cardinal current location let's see we have the current random sum equals to x right and then let's say we have some numbers here right be before this current the first card number here say we have o here right so let's say the current running sum for this one is x so how can we know if for at the current at current locations let's say if there's any uh if there's any sub rate right that can basically that a sub rate end with the current number okay so how can we calculate that i mean the brutal force was that we basically we look through all the previously all the other presumps right all the presump in the previous location right and then if there's a location basically if the we have x and let's say for this kind of the previously uh pre-sum is so actually so this is some sum someone right let's say this is someone here so basically we need to loop through all the previously previous uh prisms right and then we need to know let's see we have a sum two here we need we want to check if the sum one minus sum two can be divided by k right so if we if it can then we know okay we have find like uh like a valid sub array right but as you guys can see so this is like a like o of n square time complexity even though we're using like this kind of prism we're maintaining like this kind of presump right in the hash table but still we have to look throughout all of the uh the previously present to get the subaru is that right ending with the current number so how can we do it in better uh in a more performant way right so let's try to draw some like numbers here let's say we have some pre-sums right let's say we have some pre-sums right let's say we have some pre-sums right let's say we have pre-sum two have pre-sum two have pre-sum two and then we have some pre-sum and then we have some pre-sum and then we have some pre-sum like let's say we have set 17 right and then we have pre-sum we have pre-sum we have pre-sum 20 26 and then we have pre-sum point 20 26 and then we have pre-sum point 20 26 and then we have pre-sum point 35. so as you guys can see here right i mean let's say oh and also the um assuming the k is equal to three in this case okay so when we're at when we are at the pre-sum two here right so these are the pre-sum two here right so these are the pre-sum two here right so these are the presump so of obviously two cannot be divided by three right so that's why we just skip that and then but when we add this uh pre-sum but when we add this uh pre-sum but when we add this uh pre-sum 17 here you know as you guys can see we have like a difference right sp basically 17 minus 2 equals to 5 to 15. right so we have a between the 2 and the 17 we have a 15 here so the 15 is divisible by 3 right so this is one of the sub array right that can be divided community visible is divisible by this k here now later on we have another like pre-sum like which is pre-sum like which is pre-sum like which is 20 26 right so between 17 to 26 this is what this is nine right so okay nine is also another one all right similarly for this one it's also a nine right so nine is also another like prefix sum but you know when we add when we are at 20 26 here so how many more sub arrays we have find out here not only this two here right we also find uh basically we find this night here and we also find an another one basically another sub array between 2 and 16 which is 24. so this one is all is also another sub array community is divisible by three right similarly at nine here so by having 35 as a new prefix here we have basically this is going to be one plus two plus three right because by having 26 here we have we find two more uh subarrays and when we're at 35 here actually we're finding three more basically this is the first one and then from 17 to 3 35 this is the second one right this is like the basically here's the 18 and then from 2 to 35 this is the third one this that's the third 33. right so then what's in common so what are the common thing with those force prefix right so if we do a prefix sum right divided uh do a modular with k here they are all end up with the same number which is two right so two uh dual modular with k which has two same thing for 17 26 and third and 35 and then it leads us to like two uh to another solution basically we can just use like a hash table or dictionary to store the uh the key basically to store the uh the values for each prism to uh after modular by k right and then every time we have like a new key here basically we increase that count of that dictionary right basically at the beginning that count is one right we have let's say we have dictionary right and the key is two right and the value at the beginning it will be it'll be zero so when we are two here we don't add anything but after processing two here that value becomes one right and then we are when we add 17 here basically the new answer will basically do an answer to a plus of this dictionary of key here key so when we add 17 here right so this basically we are increasing one and after that we also uh increase this dictionary of the key by one right you do this one do a plus one so that you know we had 26 here you know this one becomes a two right so that's why we can uh add two same thing for 35 we add three yeah so basically that's the idea here so let's use the dictionary to maintain the uh the frequencies the frequency basically how many times this key has appeared and then that's going to be the uh the values we're going to use to accumulate to the final result right oh and one more thing so when we define these hash tables these are like edge cases which means that you know the zero right so let's see the k is three and what if the first number is three so in this case right three modular by do a modular b3 we have zero right but three itself in this case it's also like array here right so which means that when we create this dictionaries here we need to initialize this at 0 and 1 in this dictionary so which means that you know at the beginning we assume that you know with zero of a zero as a key it appears once so that we can handle this uh corner case here uh yeah i think enough talk so actually after figuring out the pattern here the code is it's very pretty simple here so we have a running sum and then we have answer equals zero right now like i said we have dp i'm using dp here so uh i mean i initialized from zero uh with zero key is zero and the count is one so for num in a right so first we have running sum uh updated and then we have the key right so the key will be the running sum divided by k and then if key in the dictionary right which accumulate this answer by is the frequency of the current key right then after that it will dp k we increased by one else right if the key is not in this dp we simply insert this one right insert the key with one yep and then in the end we simply return the answer yep i think that's it so run the code okay accept it right and then submit yeah i mean so for this one as you guys can see the time complexity is obviously so often right because we only have a single for loop here and to maintain this dictionary it's just like the uh um o1 time right both the insert and updates one and space complexity of course is also often because we need to maintain uh basically the key for each of the well actually no actually the sorry the time the space complexity is not all of n is o of k in this case because we do a modular right with the k here so the key is bounded with the with how big the k is yeah so this is the time complexity right this is space time complexity here yeah i think that's pretty much i want to talk about for this problem and how to stop here thank you for watching this video guys stay tuned see you guys soon bye | Subarray Sums Divisible by K | reorder-data-in-log-files | Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible by k = 5:
\[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\]
**Example 2:**
**Input:** nums = \[5\], k = 9
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `2 <= k <= 104` | null | Array,String,Sorting | Easy | null |
10 | okay hi guys welcome to the channel this is vaca we are going to do another leech good question and the question in question is number 10 regular expression marching right uh pretty straightforward okay it's not pretty straightforward the number of edge cases you have to look at in this question are absolutely uh it's absolutely crazy the number of edge cases but um if you work through it's pretty simple and you can solve it with um recursion right so what we're going to do is um first let's go through every test case right or let's go through the instructions right so you're supposed to you're given an input string s and the pattern p you're supposed to match s and p and uh they're two uh wild wildcat there's the period character which can match any single character and the star character which can match zero or more of the preceding element right so the best thing to do is to go through every example so that you can understand every single case right so in this case if we have um let's come and copy this code essay and pa let's pick one of this rebels and um let's get our ripple started and uh this is for another question i was doing and so we have sa and pa and when you try to match sa and pa the answer is of course not right because you can't make uh you can't match the pattern from the string right in this case so in such a situation we can just get rid of this right but now we go to a situation where we have um we have uh a and p a basically that let's paste them now these two strings match because remember as we said um the star element can match either zero or more of this so the star character can essentially make p be a or it can be um a or it can be a aaa or it can be a you get the point right it can either match zero or more of the preceding character right let me just check it of the preceding element right so um the preceding character can be matched either zero or more times by this so these are all the possibilities um atc right so if you look at this situation the pattern at p and the pattern at s can match in such a situation right because of the fact that um the star character can do this right so we can get rid of this and go to the next example is going to be this right so this is going to be dot star right so in this situation return true because remember the dot can stand for any character so the possible universe of characters if you can put all the possible characters it could be a to z right could be a to z and then the star matches anything in the previous element by either zero times or either matches it zero times or the exact number of um whatever is zero times or an infinite number of times right so basically you could have a to z and um a to z right so from picking a to z you can create a b from that string right so from a b uh from a to z and a to z you can create a b so basically that one is um that one this should return true right and in another situation this one is pretty difficult right so we paste this one right so we have a b and c star a star b right so the first thing you need to know is that um we could um match a character zero times right so in such a situation like this we could just ignore matching the we could ignore matching the c right imagine there's an um there's a i pointer here right there's an i pointer here and there's a j pointer here right so uh we check and we see i and j are not alike so we could move the j to the next one and we could match the preceding element exactly zero times right so in such a situation let's make a possible universe of all our characters that can be matched from um b to a so we could in this situation ignore c we don't have to um copy c right so we could just have an empty string like so right and then um when we come to a and we move i up to i could remain there right a and a match so we have an a and then we move i to the next a and we move j to the next element which is going to be this right we'll move from a and if we look at j is going to be jesus the star character matches the previous element x number of times right or zero number of times as you can see from what it did to c right so another situation where you can return uh the previous element which is a and the a and then finally we have b if we move our i element up one i and we move j up one j we have a b right so we have matched we have potentially created a match for um the first element which is a b you can match it using this element right by moving to pointers so we go to uh description and um i've gone through the examples and the first thing we need to do is we could create um a function that will do this right we're just going to pass in the i and the j of the i pointer correlates or will work on the s point on the s string which is the input string and the p and the j pointer will correlate to the p string right so and remember what we're doing here if i could just go over it again we are ensuring that um we can match the input string in the pattern right so the person might still have some things as long as we match the input string that's all that is required in the button right so we could come here and we could call it maybe um i think we could call it is it a depth first search or a breadth first search okay let's just call it bfs like so right and it's going to take in the i and the j and i corresponds to s j corresponds to p i think we've gone over that and now um the first thing we need to check that the i pointer and the j pointer are both valid right so for that we just say if i is greater than um the length of s and j is greater than the length is greater than or equal right it's not just greater it could be out of bounds greater or equal to we could say the length um and the length of the pattern will return true right if both of them have crossed over because you're going to progressively move them over each letter right we're going to loop through our strings our pattern string and our input string right so if both of them have crossed uh greater than or equal to the length of s that means that we have gone through every character and we have similarly it has passed all the tests and it has also gone through every pattern character so in this situation what you're supposed to return is obviously true right now the next situation we um we check whether or not we have hit the out of bounds of the pattern string right if we run out of characters or elements in the pattern string and the i has not been exhausted that means that we can't match everything in i in p right it follows right so the next thing we just do is if j is greater than or equal to the length of the pattern string that means um we have gone through uh that means we have gone through s and we have not found everything we're looking for that can only mean one thing right we just have to return here false like so right so after that we check if the first characters match so we start at the very beginning right so we could put this in a variable because we're going to use check the match we're going to use this a couple of times right and to check the match is pretty straightforward right we first check that i is within bounds and um we say i is less than the length of s right and we check that the element at i is exactly the same as the element of j right in this case we have um let's say a right so let's just come here and say this is going to be a and p is maybe a right so in this situation check i is equal to p right so we say is exactly the same as p j or r or remember if it's a dot it matches any single character right because the dot is from any character from a to z right i'm guessing we're only using uh is it alpha numerical okay a matches anything right let's just agree a matches anything right so um if the element at j is exactly equal to the dot character the period character that can match any letter so if this matches we have a match if we have either the characters at s at position i and the character at p at position j or the character at p position j is a dot right in such a situation we have a match and we can continue from there the next thing we do is we move our um we check the next character we move we go to the next character and um there are a few things we have to check there right so we know that as you know uh if a star is the first character then um it should be ineffectual right so um astar can't be the first character because the star only works on uh the preceding element right so if i start the first character it's possibly useless so we don't have to consider start that's why i've only considered the dot here and not the star but now for so this will only work this will work quite possibly on the first element this is what is going to randomly get to our first element right and this two up here at our base cases right when we have exhausted everything and we've gone over it these are basically is the if the length checking the lens right so the next thing in the next line we have to consider the fact that we use a stop because the star will match either zero of the preceding element or possibly an infinite number right so we have to consider this when we're doing in the second when you're considering the second element right so how we do that is we say if j plus one is less than uh the length of p if we are still within bounds in our pattern right and um and p and let's just spell and correctly am i spelling this incorrectly and the p um and the character here is our is it a star whatever it's called um and the character here is a star if j plus one if j is within bounds and the character at j plus one is uh the p dot star uh we actually have two choices right we can either ignore it right in such a situation like when we came here and um we basically ignored c right we copied it zero times right so in this case you can either copy it and you remember i say there's zero or more proceeding right so we're going to consider both instances where we copied zero times or we copy it an infinite number of times as many as required right so what we do in such a situation is we um where they have d fs we call dfs on i and we move j by one in such a situation if we move j plus one by one it becomes j plus two right in this situation what we're doing is we're ignoring it right we leave i where it is but we move j because we're ignoring it right so we ignore j plus one right in the case and this worked for when we were doing the c this right so we can ignore it if we want right so we ignore it in the pattern string right or we match it right so we say match and if we match we call the depth first such on the on i plus 1 because you've moved i and j right so basically that this line does like i've explained is that it checks um if we're using it uh if we're using the star um you it has to match and in such a situation if it matches we move our eye to the next level and of course we can leave our j where it is and um if we don't use it we just move our j to the next character right so basically that's understood and the next thing we need to do is um we just need to call we need to check match right so um if we do have a match if we if match right we just need to recursively return the and we call this dfs instead of bfs right we should call it i think this is a breadth first such rather than the depth first starts right so what we do here is we return b fs and um we want to return um if we have a match we move to the next letters and we repeat the whole uh process right so it's i plus one j plus one so we move it up one level and if we move it up one level what we're supposed to do is we're supposed to come here and we say return false like so and afterwards what you're supposed to do is um we are supposed to return uh dfs and um bfs rather bfs and what we call it on uh s and p and we call it at position zero in each right so we call zero and zero like so right so basically that so this is our we could call this our naive solution we need to make sure that we check that j is equal to the length of p right and um that we return after we check our wildcard we need to return whether this is evaluated to true and finally we need to make sure that this if blocks match right this and if much so just correct your code like that and when you run your code it's hopefully going to be accepted and if we submit it's also hopefully going to be accepted so basically that is our code um our time complexity is going to be o of n our space complexity is going to be um we don't create any structures right so we're just going to have an o one space complexity right if i'm not wrong we do not create any structures yeah so this is going to have a time complexity of o of n and a space complexity of o one right um you could also use caching but i'm not going to go into that but you could use caching to make um our code move a bit faster but the space complexity calculating it is going to be exactly the same right it's not going it's going to be maybe a significant increase in our speed but it's not going to change it into it's not going to make it better than oven the time complexity thank you for watching subscribe to the channel and i'll see you in the next video | Regular Expression Matching | regular-expression-matching | Given an input string `s` and a pattern `p`, implement regular expression matching with support for `'.'` and `'*'` where:
* `'.'` Matches any single character.
* `'*'` Matches zero or more of the preceding element.
The matching should cover the **entire** input string (not partial).
**Example 1:**
**Input:** s = "aa ", p = "a "
**Output:** false
**Explanation:** "a " does not match the entire string "aa ".
**Example 2:**
**Input:** s = "aa ", p = "a\* "
**Output:** true
**Explanation:** '\*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa ".
**Example 3:**
**Input:** s = "ab ", p = ".\* "
**Output:** true
**Explanation:** ".\* " means "zero or more (\*) of any character (.) ".
**Constraints:**
* `1 <= s.length <= 20`
* `1 <= p.length <= 20`
* `s` contains only lowercase English letters.
* `p` contains only lowercase English letters, `'.'`, and `'*'`.
* It is guaranteed for each appearance of the character `'*'`, there will be a previous valid character to match. | null | String,Dynamic Programming,Recursion | Hard | 44 |
1,727 | let's do lead code cool largest sub matrix with three arrangements you're given a binary matrix of size n times n and you're allowed to rearrange columns of matrix in any order turn the area of the largest sub matrix with the matrix every element of the sub matrix is one after reordering the columns optimally up to ten to the power five elements okay so i had to look at the hint first hint for each column find the number of consecutive ones ending at each position so we go through each column and account number of consecutive ones when we reach a zero we restart the count from zero but then how does that help us find the answer okay so here we go the white board let's say um you have a bunch of columns and these are all consecutive ones down these columns and we've counted how many ones uh ending at the last position here we do this for each row of the matrix given this row for this row what's the maximum area well if we sort all of these numbers so let's say this is five three four two five two let's say we are sorting it in decreasing order so that means we get five four three two and to find the maximum area i could possibly get from this is something like uh let's say for example the indexes are zero one two three four five so that's the index these are the number of consecutive ones the answer would be well i would go through each of these then i'll do the min so far the mint so far is actually the item at the current position because it's decreasing so it's actually going to be whatever this value is let's call this a value array it's going to be a value of i times i plus one that's the area i'm gonna take the max out of all these or all i in the range is zero to five so in this case what's the max area well let's calculate one by one so we have um five times one that's going to be five or we could have five times two which is ten or we can have um four times three which is twelve we have three times four which is also twelve or we have 2 times 5 which is 10 or you can have 76 which is 12. and we take the max out of all these it's going to be 12. that's the answer for one row and we do this for all possible rows and then we'll have our answer let's give that a go so i want a bunch of vectors a vector of vectors let's call it ones number of rows would be matrix.size matrix.size matrix.size they want to go through each column one at a time and then go through each row at a time so matrix i j will give us the current value in the column we're looping through and keep track of let's call it dp0 uh if current value is equal to zero and on db equal to zero i also want plus db we just restart the count and then set ones at the current row and they'll push back the current dp value cool and then we can go through each of the rows and just sort the row i kind of want to sort it in reverse order so once i've done that i could go through each of the rows put an answer here and then we can go through j is equal to 0 j less than matrix at let's do actually one's not size and then we can do ones at i dot size plus j keep track of a row answer the row answer is equal to the maximum of the row answer and whatever ones at i j is times the current index plus one and then at the end i wanna do answers equal to max of the answer and the row answer and at the end just return the answer okay that's four let's try a different case that's working cool let's submit that and see if that works awesome that does work sweet um thanks for watching like and subscribe and i'll see you in the next one don't forget to keep eating the code | Largest Submatrix With Rearrangements | cat-and-mouse-ii | You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`. | Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing. | Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory | Hard | 805,949 |
73 | Hello friends welcome to coding First Youtube channel in this video I will explain you Elite code problem set Matrix zeros so in this question we will have a m into an integer Matrix and if an element is 0 then we have to set its entire row and column to zeros so you can see here in this example one this is our Matrix in which we have zero in the middle so this is our second column and this is our second row so in the second row and the second column we have to make all the elements as zero so this is our output Matrix same you can see here in this example 2 we have this Matrix so you can see here this is 0 is present in Faster row and First Column so this whole first row and First Column will become zero and this second zero is also present in first row but it is present in the last column so ball first row and last column will become zero so for this question I will explain you two approaches first is Brute Force approach and second is optimized approach but in this video I will only going to explain you the Brute Force approach but there is one limitation of that Brute Force approach you can see here the range of elements in this Matrix so it is starting from negative to positive so that Brute Force approach is only applicable for positive elements so that's why we cannot use that Brute Force approach to write the program for this question in the lead code but only for interview that if in the interview they will tell you that the Matrix will only have positive elements then you can apply that approach that's why I will explain you the Brute Force approach in this video so you can see here I have taken here some sample test cases so this is our test case one first we will see the approach and then we will write the program so what I will do is we already know how we can Traverse in a matrix so we know that we have to take two for Loops so first for Loop is for the rows and then inside this for Loop we have a another for Loop for the columns so using this for Loop we can easily Traverse in The Matrix to every element then what we are going to do so you can see this test case one we are traversing in The Matrix so this is 0 is present at index 1 comma one so what I will do is add this index we will call a function that Mark this row and column with zero so suppose if you find a zero and then you just mark this row and column with zero what will happen so when we are on the index one by one so we are calling a function to make this row and column as 0 so then this row and column will become 0 but you can see here we are not going to stop this for Loop because we don't know if we have more 0 in the Matrix or not so next time when this Loop will run again so we will reach at indexes 1 comma 2 so you can see here when we reach 1 comma 2 at this index so here it will again find element zero so then it will again call that method to make this row and column as 0 so you can see that because of that this column will also become zero so this is wrong so what we are going to do is initially we are not marking the row and column as 0 we will mark them as negative so we will mark them as minus one so you can see that suppose this was our Matrix and when we are finding 0 here so we are marking this wall row and column as a minus one so you can see here we also have to use a if statement when we are marking the row and column as 0 because at the index where we are finding the original zero we have to keep it as 0 we do not have to mark it as minus one when we reach on the last index and this nested for Loop will break then after that we will use a next message for Loops to check that if we find any minus one element we will make it as 0 so next time we will use next sheet for Loops again to make this negative ones to zero so this is our Brute Force approach so this is all our sample test case I will write the program in the IntelliJ IDEA and I will run all these test cases to check that if the Brute Force approach is working or not so now let's write the program so you can see that in the program this is our Matrix then we have to use nested for Loops so for end I equal to 0 and I less than a DOT length and I plus and inside this we have to use a next for Loop 4 into J equal to 0 and J less than a of 0 dot length and J plus so now we have to use a if statement here if array of I and J equal to 0 so when we are finding any element as zero so then we have to call a function so I will make a function here set Matrix minus so we know that initially we do not have to mark row and column is 0 we have to mark them negative so I will name this function as set a matrix minus and inside this function we will pass array and this I and J because this I and J will tell us that which row and which column we have to mark after that here I will make a function public static void so we do not have to return anything we only have to mark this original array with negative elements so that's why we will use here void return type method name is set Matrix minus so now in this method I will make this parameters array a and end column and int row so here you can see that one thing that is this I4 Loop is for rows and this j4 Loop is for column but you can see here when I am passing these values here I am storing this I in the column variable and I am storing this variable J in the row variable y so I will tell you later why we are doing this so now in this method we have to take two for Loops first for making the row as minus 1 and second four making in the column s minus 1 so 4 and I equal to 0 and I less than a DOT length and I plus so here I will use the if statement if a of I and rho not equal to 0 so we know that we do not have to make this original 0 as negative 1 so using this first folder we are marking that column as minus one so array of I and rho equal to minus 1 and after that we have to make a next for Loop to change the row to minus 1 4 into I equal to 0 and I less than array of 0 dot length and I plus so here you can see that in the starting we are taking a DOT length but here we have to take a is zero dot length for column we have to take a of 0 dot length you can see that we have to make some changes here in the if statement if so you can see that what we have to write here First Column or I suppose if we have to move in this world Row from this here to here so X actually what is changing here the value of this row will remain same only the value of column is changing here so actually this column variable which is changing this is our variable I and this row variable it is our column variable so that's how we have to write so if a of column and I not equal to 0 so then we have to make it as 0 so a of column and I equal to 0 so we have to make that column and I equal to minus 1 so you can see that what we are doing right now we have written this nested for Loop two Traverse in The Matrix so traversing Matrix then what we are doing is we are calling this set Matrix minus function to make that element row and column as negative one where we are finding zero so this is our method so this first for Loop is for making column as minus 1 and the second for Loop is for making the row as minus 1 you can see that we also have to make that negative 1 back to zero but before that we will see that if this method is working fine or not if it is making row and column as minus 1 or not so I will print the elements of our array and now let's run this program so you can see that this method is working fine we had 0 in the center so this wall column is minus 1 here and this row is also has become -1 here and this row is also has become -1 here and this row is also has become -1 so now only the one step remain is that we have to make this negative one back to zero so before printing this array I will use this nested for Loops here and inside this so here I will write if statement if array of I and J equal to minus 1 then array of I and J equal to 0 and we are using this next for Loop to print our Matrix so now let's say run this program so you can see that this program is working fine we are getting this second row and second column as 0 and 0. so I will show you a quick Dryden of this program so let's see how this program is working so you can see that in the question we have a matrix of 3 by 3 and in the second row and the second column at this index we have zero so we have to make this volt 11 row as zero so then what we are doing is we are traversing in The Matrix using the nested for Loops so this first folder will start from index I so I is zero inside it we have this next for Loop J so J will also start from index 0. so you can see that at index 0 and 0 it will check that if we have 0 you can see no at this index 0 and 0 we have one so then nothing will happen J Will increment so it will become one then it will check at index 0 and 1 do we have zero you can see at index 0 and 1 we have one so this if statement is false then J Will increment so it will become true you can see at this index 0 and 2 we have one again this if statement is false then you can see J will not increment because in the Matrix we only have three columns then this row will increment so I will become one so now again J will start from zero now it will check at index 1 and 0. now it will check if at index 1 and 0 do we have zero you can see at index 1 and 0 we have one again this if statement is false J will become one now you can see here at index one and one we have zero yes now this if statement will execute and it will call this set Matrix minus function so here we are passing this three parameters first is array then these two values I and J so in the column variable we will store I and I is 1 and in the row variable we will store J and J is also one so now what will happen you can see we have this first for Loop and in this first for Loop we have two values I end row so this I is starting from 0 so this is our I is starting from 0 but this row variable will remain as it is and row is one so index 0 and 1 so it will check that if at this index 2 we have 0 you can see no so this condition is right here we have one we will make it as minus 1 then I will increment so it will become 1 then it will check at this index one and one at this index we have zero so this if statement is not going to execute here then I will increment so it will become 2 you can see at index 2 and 1 we have one it will make this index element as minus one so here it will become minus 1 then index will become 3 so then this folder will break here so this follow will stop here then this next follow will start so this first for Loop has made our second column as minus one now this next four Loop will make this second row s minus one this folder will start from zero so this is our I which is starting from 0 and we have this column variable so here we have column variable which is one so it will check this first index 1 and 0 so at index 1 and 0 is the element not equal to 0 you can see yes here element is one so we will make it as minus one so it will become -1 then I will increment so will become -1 then I will increment so will become -1 then I will increment so it will become one you can see at index 1 and 1 we have zero so this if statement is false and it will not execute then I will increment so it will become 2 at index 1 and 2 we have one so this if statement is right and it will execute so we will make this element as minus one so after that I will increment you can see that in the Matrix we only have three column so then this folder will also break from here so then we will go back in this nested for Loops so in the last we were at this index one and one index will increment so J Will increment it will become two now it will check if at index 1 and 2 do we have zero so you can see that now this is our array we have modified our array by making the elements as -1 so now you can making the elements as -1 so now you can making the elements as -1 so now you can see here at index 1 and 2 element is 0 no here we have minus one so here nothing will happen but you can see here if initially we have made this volume row and column as 0 so next time this function will again make this column as 0 which will make our output force so this time nothing going to happen then J Will increment so it will become 3 and we know that then this J folder will break then I will increment so it will become 2 now from here J will again start from 0 at index 2 and 0 we have one so this if statement is false then J will become 1 at index two and one we have minus one again this if statement is false nothing going to happen then J will become 2 so at index 2 and 2 we have one again this if statement is false so in the last this both in a state four Loops will break so you can see that this next sheet for Loops will start it will start from index is zero so we are using this next Nesh it follows to making this minus one element as zero so you can see that I will start from 0 and J will also start from 0 so at index is 0 or 0 do we have minus one no nothing going to happen then J Will increment then it will check if at index 0 and 1 do we have minus one you can see yes so it will make this element as zero then J Will increment so it will become two so at index 0 and 2 do we have minus one no nothing going to happen then I will increment so it will become one again J will start from zero so at index one and zero do we have minus one you can see yes so we will make this element as zero then J Will increment so it will become one you can see at index one and one we have zero nothing going to happen then J Will increment so it will become two so at index 1 and 2 at 1 and 2 we have minus one yes so this if statement is right and then it will make this element as zero so after that I will increment so it will become 2 and J will start from 0 at index 2 and 0 we have one nothing going to happen then J Will increment so it will become one so at index two and one we have minus one yes so then it will make this element as zero then after that J will become 2 so at index 2 and 2 we have one and nothing going to happen and in the last this folds will also break and then we will print our Matrix so this is our final output this second row and second column has become zero so if you want to know the time and space complexity of this program so what is that we are using nested for Loops so because of that time complexity of this program will be bigger of n Square so you can see that we are only using these four Loops but we are not making the exact same array to make the changes so because of that phase complexity of this program will be big of one so in the next video I will explain you the optimize approach for this question thanks for watching | Set Matrix Zeroes | set-matrix-zeroes | Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s.
You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm).
**Example 1:**
**Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\]
**Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\]
**Example 2:**
**Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\]
**Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[0].length`
* `1 <= m, n <= 200`
* `-231 <= matrix[i][j] <= 231 - 1`
**Follow up:**
* A straightforward solution using `O(mn)` space is probably a bad idea.
* A simple improvement uses `O(m + n)` space, but still not the best solution.
* Could you devise a constant space solution? | If any cell of the matrix has a zero we can record its row and column number using additional memory.
But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker?
There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero. | Array,Hash Table,Matrix | Medium | 289,2244,2259,2314 |
1,029 | hey what's up guys babybear4812 coming at you one more time uh trying to get one more video in before the sun goes down so it's a bit dark uh today we got 10 29 two city scheduling and i think this will be relatively quick i'm going to keep peaking over there at the uh so i see the cn tower from here and i think the light show hasn't started yet so we're good so that's going to be like my proxy for if this video is going too long but this will be a quick one uh bloomberg likes this one a lot as of recent and the problem states is states the following a company is planning to interview two n people given the array costs where cost the bias equal to a cost and b cost the cost of flying the i person to city a is a cost and the cost applying to city b is b cost we need to return the minimum cost to fly every person to the city such that exactly n people arrive in each city so what we're told for sure is that before we dive into an example we're told that there are an even amount of people and there's at least two entries so we don't need to do any error checking and uh we have some positive uh cost between one and one thousand so if we had we have this array 10 20. so person one or person zero let's call them it would cost us ten dollars to fly them to or choose your favorite denomination cans of beans get ten cans of beans to fly person zero to city a and twenty cans of beans to fly into the city b or you know 30 and 200 for person one 450 per person too uh 30 and 20 per person three the output is 110 and the weight we'll figure out how to get to the 110 but that's composed of uh sending this person right over here uh to city a and the second so people zero and one will go to city a and then did i get that right yep and then uh people three and four will go to city b so city a city b so that cost will be 10 plus 30 is 40 plus 50 zero in a city b that's 90 plus another 20 is 110. we get a couple more examples but i think it's pretty self-explanatory i'm think it's pretty self-explanatory i'm think it's pretty self-explanatory i'm going to dive into this example a bit further just to see how we'd work it through so a couple ways that you could start thinking about this and this problem usually trips people up a bit at least right off the bat because one at least where my head went the first time that i tried to solve this was in taking a bit of a greedy approach and saying let me find the cheapest route per person so or rather by city and maybe this example would be um a bit better if i did something like this i'm going to change this to 40 just so the numbers work out a bit nicer let's pretend that i told myself okay let me figure out if i need to send half and a half so how many people city have my people to city b let me figure out who i want to send to city a and you know by looking at this list i can say hypothetically let's sort it um if we were to sort it in increasing order of cost the reason i maybe want to do that is to say well the cheapest cost to get people to city a whatever combination so the cheapest way to get people to city a will be in increasing order this way so it'd be like 10 30 40 400 imagine these two were swapped so these two were swapped if we were to have sorted this and if that's the case we would send this person city a this person to city a and that cost will be 10 and this will be 30. that's cool um then we would want to send i think that i may have messed up this example here um let me do this i'm going to change it up a bit more yeah sorry um let me see if i can i tried to erase this before let me do this i'm going to make this 150 i'm going to make this one 400 so the example can be a bit more illustrative if i was to tell myself what's the cheapest way to get people to city a this would still be it if we were to sort this list by city a and by it from lowest to highest cost we would grab these two then we're left with these two guys and gals and they would be sent to city b so these would be their relevant costs the issue is that this person would now cost 400 this person would cost 20 and overall the cost here would have been what is that 40 60 400 and 60 yikes 460. so this is what would have happened if we sorted people by the cost of city a and we said let's just let's get them out the city a as cheap as possible um and in this case you know there was a better answer here because maybe we could even do something like well let's send now let me think here maybe let's send uh this person sorry let's send these two people to city if we send these two people to city a we'd have a cost of 80 and then these two people would go to cdb and that would get us to 120. so all the you know all of a sudden we can tell by account for example that there's a way to do this that's better than just saying let me sort people by city a so i'm gonna unwind that now let's say i'm gonna undo this example here and i'll leave it back for the 450 how we had it before and let's say we said okay well what if we tried the same tactic but for city b and i somehow grabbed people to go to city b and i basically sorted by this half here and i said well by that methodology i'd have these two people to go to city b would only cost me 40 and that leaves these two to go to city a the problem is again now i've got this one's really expensive here for 400 so all of a sudden we're not doing what we optimally could have because this would cost us uh 470 whereas potentially what we could have done was we could have said let's take these guys for 40 and these guys were 70 and that only would have cost 110 so way less how then do we actually determine how to pick and choose who's one where well let's think about it this well light show is starting all right we'll get there quick um let's think about the following why is it that i think let's think about this last example we just had why did we oops why were we unhappy with our selection here so i think we sorted them and we said these two would go here and then these would go here what we failed to take into account is the following so we said sure city b is really cheap and we found it the cheapest possible city b combination um when we did the first example we found the cheapest possible city a combination what we didn't take into account is how these two cities um what the total cost is with respect to each other and that's the key to this question to really getting down to the bottom of it let's say that i wanted to drill in a bit deeper and i wanted to say how can i think about the cost to get to one city while taking into account let me get the light on um while taking into account uh the cost of the other city so namely how do i actually keep one city with respect to the other in mind when i'm going through this and it's the following way we can think about it in the following way it's a pretty simple trick but it's a neat one what if i ask myself what is the value of the differential from one to another for instance if i was to go to city a instead of city b for this person over here what benefit would i derive so if i was to fly this person to city a over city b i would save maybe oh i'd save 10 i'd say the cost of 10. so that's good it's cheaper for me to send this person to city a than the city b i don't know what it costs everybody else yet but just this person alone that's what they're going to cost me the next person over here well if i send them to city a instead of city b i would save 170 dollars cans of beans euros whatever your favorite denomination is goats um person c versus the third person if i was to send them to city b that's awful it's like that would set me back i would lose 350 bucks incremental um if i had sent the city instead of city okay so that's good to keep in mind and then with this one over here it would cost me an extra 20 bucks to send them to city a what now if we reframe the question is that it's it instead we said what is it instead of saying what does it cost me to go to city a versus what is the cost of city b and i ask myself what does it cost me to send somebody to city a with respect to how much it would have costed me to send this to city b okay and that's how we're going to reframe the question to actually make this work in this case we really if we think about this now if i just was to send everybody to city a where i would get the biggest delta like i would be happiest to send the city a because that's my best option when comparing the two cities then in fact i'm gonna get my optimal solution so imagine sorting this image imagine sorting this array now except we sorted it by the delta in terms of like the benefit that we get from going to city a versus city b of course you could do the same logic the other way around you can figure out what the benefit is to send city b instead of city a and sort it that way the two methodologies are completely synonymous i also sort this now well i noticed that at the top of my list are these two guys and these two tell me that i have the biggest benefit of going to city a with respect to city b i would save the most i would have the most positive benefit by setting the city a versus city b even if i was at a loss so let's say even let's imagine this was negative let's say it was more expensive for me to send everybody to city b instead of city a and so city a would cost me more i still need to split them 50. since these two would result in the lowest loss i would still go with these two maybe you know this would have to be a 30 this would have to be 217 for these numbers to work out um like with this example i just made them negative but regardless that would actually get us to our optimal solution what we then need to do is just say well let me sort this array based on how good my benefit is of sending the city a let's say and you know whatever that benefit is for cda i'm going to send the first half of the people there and the second half people are going to go to the other city again you can flip the order around if you know that tickles your fancy i'm uh i'm not going to push you either way but i hope that explanation made sense the code is going to be really short and the logic itself i think is quite manageable what we're going to do is we're going to do this we're going to sort this using a in python it's a lambda function uh in some other languages like javascript it would be an anonymous function you can use whatever your language offers but the way we're going to sort this is we're going to sort it by taking five some element um i'll call it i'm gonna take the benefit we're gonna get is gonna be i naught so this first entry minus i one okay so really i kind of i made these values positive here but really they should be the other way around where it costs me ten dollars less to go to city over city 170 less to go to city average city b for the second person it's an extra 350 to go to city a an extra 20 to go to city a for these two people that way when we sort it so if i kind of sort with um with this in mind i'm going to sort uh in an ascending order and the first half is going to be all the lowest numbers the most negative ones or the least positive ones which are going to be the ones uh where i derive the most net positive welfare or benefit with respect to the rest of the list when sorting it in this way so i hope that explanation uh made sense i think it's not too difficult to prop the grasp again the code is going to be super short so uh yeah let's dive in if you have any questions drop them down below as always we don't need to do any error checking like i mentioned because we've we're given a legitimate length here what we will need to do though of course is like i said sort first and foremost so we're going to sort this and we're going to use the lambda function so we're going to say p equals a lambda and for any arbitrary item x so this item x is one of these they're not tuples but one of these uh arrays array items within the bigger array and we said we want to sort them in ascending order by finding the benefit from city a from going to city a with respect to city b meaning that i'm just going to take i'm going to sort it by taking x naught minus x1 these numbers are going to go in increasing order and so the first half that we find is going to be like the city a the second is going to be going to city b all i really need to do is to say um i'll find some total cost variable not find it i'll declare it set it equal to zero and i'll say that for the first um i'll say for cost and costs uh we want to say or let me do this brian range in the length of cost so that's the entire length of the array and we're going to divide it by two non-inclusive so imagine this imagine non-inclusive so imagine this imagine non-inclusive so imagine this imagine that costs like right here is a length of four okay it's gonna give us the length of four divided by two will get us two since this is uh the upper bound of this range non-inclusive we'll we're gonna go up to non-inclusive we'll we're gonna go up to non-inclusive we'll we're gonna go up to index one meaning index zero and index one and that'll be the first two elements out of four and so when we do that we're gonna say that we wanna increase our total cost by costs at i and we want to go to city a for this first half that's how we sorted it so we're going to take the first cost right over here we're going to take the 10 and we're going to take i guess it'll be one of these 30s after it'll be this one here i'm then going to loop through the second half the array so for i and range from the length of costs divided by two so from index to all the way to the end uh so that will take us to the length of costs i'm going to say total cost plus equals cost of i one so you know the folks going to city b we're going to take the cost it takes to get them to city b this is one walk through one calculation we return total cost we run that i'm going to submit it and make sure that i haven't made it funny and there we go 85th percentile it's as quick as it's gonna get um i believe unless there's like a another hidden trick that i don't know about let me know down below if there is but yeah this will get you guys definitely across the line uh it's a cheeky solution but i think it's a good one for the two city scheduling problem that again bloomberg's been asking i think it's a decent problem uh if you liked it if you found it useful smash like button comment share subscribe uh share with everyone and i will see you guys in the next video peace | Two City Scheduling | vertical-order-traversal-of-a-binary-tree | A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`.
Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city.
**Example 1:**
**Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\]
**Output:** 110
**Explanation:**
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
**Example 2:**
**Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\]
**Output:** 1859
**Example 3:**
**Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\]
**Output:** 3086
**Constraints:**
* `2 * n == costs.length`
* `2 <= costs.length <= 100`
* `costs.length` is even.
* `1 <= aCosti, bCosti <= 1000` | null | Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree | Hard | null |
115 | lead code problem number 115 distinct subsequences so this problem gives us two string s and string T and the goal is to return the number of distinct subsequences of s which equals to T here's some information about the test cases and here's an example right so we have rabbit here with three Bs and for string T it'll be a rabbit with two BS so the output is three because we can create three rabbits by excluding any one of the BS right so here I have an example and the approach I'm going to use is by using dynamic programming to cach the previous result as we iterate through the string so DP will equals to m+ one m in this case would be the size m+ one m in this case would be the size m+ one m in this case would be the size of T which is four so we have four + 1 of T which is four so we have four + 1 of T which is four so we have four + 1 five zeros and here the first zero will be one right now I iterate through the two strings I have J which starts at one and increments as long as is smaller than the size of s which in this case is five next I have I which starts at the back of P so we have four as long as it's more than one you will keep on decrementing all right so now let me do a pointer so it's easier to follow so now here I have a e statement which basically checks J minus one right so this character is this character the same as I minus one right so I is four 0 1 2 3 4 minus one is T so if they are the same we increment by the previous result but since R and T are not the same so what happens is I will decrement inant so I decrements we're looking at B now still not the same decrement now when both I and J are one the characters matches right R and R so what happens here is DPI which is over here right 01 will plus equals to IUS one which is the previous result which is one then J Will increment I will reset back to four and we repeat the same thing again right so now for b does not equal to T so I decrements and now over here since this B is equal to this B so what happens is DPI I again is three 0 1 2 three right plus equals to the previous number which is zero right so 0 plus 0 is still zero nothing changes there t will decrement again not t but I will decrement again two now since they are the same we check again DPI plus one right on the previous calculated one this will give us one okay next I will decrement once more but since now we are targeting R which is not the same as B so we're going to skip it J Will reset not J reset J Will increment to three I will reset to four then we start from the back move on up then we start again right so we check TT not the same decrement move the pointer since now they are the same I for three 0 1 2 three this will plus one from the previous result decrement now for this B it's still the same so over here one plus this one will give us two decrement R is not the same as B so reset everything again save increment to four so again they don't match decrement now we're looking at this character they match right so I3 0 1 2 3 this will 0 1 2 3 minus two 0 1 2 3 this will plus this uh two here which will give us three decrement to this one since they're the same 0 one 2 + 2 + 2 + one give us three decrement again this will give us R which does not equals to B right so J increments one more time looking at this last character I will back to four and here since at the start they match so 0 + 3 since at the start they match so 0 + 3 since at the start they match so 0 + 3 this will give us three and we know what happens to the rest because none of this matches with P so we can basically skip this entire for Loop here meaning that what we' have done so far in this DP uh what we' have done so far in this DP uh what we' have done so far in this DP uh caching if we were to return the length of M so M if you remember is 4 0 1 2 3 4 which is the result we will get that we will get three which is the result we can generate rbb BT from the string s of r with three Bs one t basically the same thing with the example shown over here right when there's three Bs so here 3B and 2B I just shorten it to make the video not too long Yeah so basically that's what the code does that's what how that's how you can cach what you have done especially when you start from the back it makes it slightly more efficient and I think that's all I have to show thanks | Distinct Subsequences | distinct-subsequences | Given two strings `s` and `t`, return _the number of distinct_ **_subsequences_** _of_ `s` _which equals_ `t`.
The test cases are generated so that the answer fits on a 32-bit signed integer.
**Example 1:**
**Input:** s = "rabbbit ", t = "rabbit "
**Output:** 3
**Explanation:**
As shown below, there are 3 ways you can generate "rabbit " from s.
`**rabb**b**it**`
`**ra**b**bbit**`
`**rab**b**bit**`
**Example 2:**
**Input:** s = "babgbag ", t = "bag "
**Output:** 5
**Explanation:**
As shown below, there are 5 ways you can generate "bag " from s.
`**ba**b**g**bag`
`**ba**bgba**g**`
`**b**abgb**ag**`
`ba**b**gb**ag**`
`babg**bag**`
**Constraints:**
* `1 <= s.length, t.length <= 1000`
* `s` and `t` consist of English letters. | null | String,Dynamic Programming | Hard | 2115 |
139 | hello and welcome in today's video we are going to solve the word break which is a quite popular problem it was asked frequently by meda amazon microsoft and google let's look at the first example we are giving an input string s containing lead code and the list of the strings in the word dictionary the required function should return true because we can find a way to segment s into the parts that are present in the word dictionary and the same result also in the example 2 however in the third example send or and consumes d so the remainder will be string og which is not present in the dictionary therefore the answer will be false this problem can be solved by a variety of the techniques including a recursive function dynamic programming or graph traversal approaches basically we need to scan through the s and cut segment from its beginning so that those segments are in the given dictionary then we recursively search on the remainder part of the string this time from the letter after ending position to the end of the string this knife solution works but will not pass test cases in which the input size is very long because the timer complexity is order of the two power n to improve this knife approach we can use dynamic programming to avoid repetitive steps by reusing saved computation with dp the time complexity will be dropped to the order of the end power 3 which is good but we can do event better especially with the companies like meta they usually expect more non-dp they usually expect more non-dp they usually expect more non-dp solutions our approach is using a breath first search which requires the transfer problem into the tree's tree space let's consider the string s as a root note every note represents the remainder of the string after cutting some prefix segments which is in the dictionary two notes are connected if let me show this graph here as you can see in this graph two notes a and b are uh connected only if the prefix of the first node is a valid string present in the dictionary list of the words to implement this idea we start from the first letter of the input string s and look for every possible substring that is in the dictionary we push back the substring starting from the next letter after previous segment to the queue to use in the pfs process so for all nodes in the queue we apply this process if we reach the end of the given string and all segments found in the dictionary then we return true otherwise result gonna be false okay let's code up this idea initially we need to define that q and add given string s to the key and for avoid uh visiting nodes multiple times we use hashtag to remember them so while q is not empty we start popping from q rev reward in the given word dictionary if as starts with that word then we need to create a segment if we reach to the end of string s then this is our terminated condition so we just need to return true if not we need to check that if this new string is new we never we never visited before not in the that we need to add it to the queue and also add it to scene and if we haven't returned from the termination condition then we need to return files then let's run it okay there's a problem here false should be true let's check the code string f forward in the dictionary if s start with ss oh we need one more english tension here okay let's submit as you can is as you can see it's accepted and pretty efficient thank you for watching this video and i hope it was helpful thank you | Word Break | word-break | Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\]
**Output:** true
**Explanation:** Return true because "leetcode " can be segmented as "leet code ".
**Example 2:**
**Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\]
**Output:** true
**Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ".
Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** false
**Constraints:**
* `1 <= s.length <= 300`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 20`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**. | null | Hash Table,String,Dynamic Programming,Trie,Memoization | Medium | 140 |
1,026 | Hello everyone Welcome to my channel here they solve problems Lead code today task number 1026 maximum difference between node and parent level medium Yes the root of a binary tree we need to find the maximum value V so which is the difference between nodes so the difference between nodes A and B such that the difference in modules the absolute value of the difference a shaft minus B shaft where A is the order of b so the value is a bit of a description a little confusing but in general the point of the problem is that we need to return the maximum difference between the nodes and their parents, moreover, the parent can be not only immediate but also any parent above for example, in the example, one node is the parent of the one below. That is, for example, node 3 1 6 7 and so on. That is, you need to find the maximum absolute Difference between any two nodes that are in the same relationship as parent Descendant, that is, exactly in the first example such a maximum value is two nodes 1 and their maximum differs in the answer. What will we do? Well, firstly, we have a problem with binary trees, that is, accordingly, the easiest way to solve this is to use recursion. Next, we need to decide under what conditions we get the maximum the difference, that is, the maximum The difference between some current node and any of the parents above can be in two cases: this is if some parent two cases: this is if some parent two cases: this is if some parent has a minimum value relative to the current node. And the second option is when the parent has a maximum value, that is, in theory, this is the meaning that for each node we check the maximum and minimum values of the minimum values of the minimum values of the parents and as soon as some difference is greater than the previous one, we update this value, taking into account that we use recursion, this is described as simply as possible in the code, it will be more clear, that is, what do we need an auxiliary function that will just be a recursive lane What will be in the hepe there will be the current node itself and also two values These are the minimum and maximum I will call them min and max val this means the minimum and maximum value of the parents, that is, initially these values will be equal initially these values will be equal initially these values will be equal value of the root and then, when passing through each node, the value will be updated accordingly for each node, we will check this difference, so for now we will skip the implementation and immediately enter this function, that is, how we will call it. The first parameter is the root, then we pass the value of the root Now let's implement this function since this will be a recursive function We need a base case; in our function We need a base case; in our function We need a base case; in our case, the base case is the case when the node is empty. That is, if an empty node is passed, then we assume that the difference is zero. Next, we need to return the maximum possible difference, that is, we return the maximum to determine what options are possible, that is in some specific node For example, we have a current node, let’s say let’s say let’s say three Maxi the maximum minimum value of the parent is eight because we only have the root, that is, what we need, we compare the absolute value of the current node minus NBA one of the options could be like this that is, we compare the difference between the current node and the minimum. That is, this is the case when the current node is large; the second option, on the contrary, if we is large; the second option, on the contrary, if we is large; the second option, on the contrary, if we assume that the current node is small, then its difference with the maximum parent could potentially be Maxima; Maxima; Maxima; these are two options; the next option is a these are two options; the next option is a these are two options; the next option is a recursive call to the children of the child under tree That is, we have a recursive function, so we call the same function for left and right under the tree. Moreover, when calling a recursive function, we need to update the minimum maximum value of the parents, that is, in the same example with a triple, that is, for a triple, the maximum minimum value of the parent is - this is 8, but minimum value of the parent is - this is 8, but minimum value of the parent is - this is 8, but for example for the left under the tree the minimum value will be three since the current value of three is less than in and accordingly here the logic is like this, that is, we will take the minimum this is the minimum value and the value of the node is the same for the maximum makva Iva and do the same for right under the tree, so it may be that for the current node the difference may already be maximum, or this maximum difference will be somewhere in the child nodes. Let's try to run tests and see if this solution is suitable. The tests passed, we try to send it, so the decision is made and it is clear that it is not effective only in time, but also in memory, this problem is quite simple, that’s all for today, thanks simple, that’s all for today, thanks simple, that’s all for today, thanks for your attention, see you tomorrow 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 |
957 | all right let's talk about the prison cells after 10 days so you have a person's cells a rate and an integer n and for every single day you need to just follow the constraint so if a cell has to adjust neighbors they are both occupied or both vegan right it becomes occupied so uh what it means is like if there is a uh sorry give me one sec so if this is day zero right so at least at this day i mean at this index for the first day since the neighbor are the same so you need to just change the cell's value to occupy the occupied value is one and the basis value is actually zero so we know like what so imagine we don't know the value for the day one they just follow so since stay zero the first value is zero then we don't change anything and then now uh the day the index one for day zero the both are actually what are the same right the neighbor are the same so it's one and for these ones neighbors are the same and one this one neighbor another saying zero neighbor are not the same zero and zero right so uh they're just making sure my answer is correct so zero one and four zero right and then and i miss another zero which is at the end so this is going to be the exponential so uh what do i need to do so you want to return the state of the prison after and days okay so at this point right so at this point you have to know at some point uh day x a x might be repeatedly uh beforehand right so we need to know like we need to store all of the value into the set so we will be able to understand okay this uh this date is already happened before so we can actually just pull out the record out and then calculate the uh the state for the prisons and then so if there is a if there's a day we already use right we just have to calculate the risk so if there's a fun day right so if there is a day that we happen in previous so it's going to be x so we just have to minus x basically minus x be on this so we find out the y so we just have to traverse the y iteration and to find out if there is something um happening by the state updating then you just turn away and this is going to be pretty much it so uh it's definitely not a minus x it's going to be a mark on my x so i would i'll explain later but uh definitely i will just uh you know try to stop for it so i had i need a hashtag i need to have forward into a string you can say in the picking array doesn't matter but i would like to use a string just in case uh this is more easier to read and then i will have a cycle count right except for accounts starting from zero and now i'll say dates uh they're able to run and i need to have a boolean function to make sure there's a cycle so uh it's going to be false so i'll say i will say while this is actually work base is greater than zero right i was just making sure and then basic increment every single time i iterated you can use for loop doesn't matter so i have the next so next array represents uh the array half the array i calculate for the previous uh the current state so i'll have a helper function that's going to go next day i will pass in while passing the cells right and let me just quickly write my helper function next state and now let's say what uh cells right i need to create a temporary array which is going to be update version after i type it right so i'm going to say 10 click on the new games the lens is going to be the same all right and i'll continue right then i need to update it and then for every single time this is on viewer for india than ten thousands i plus over so temperature i tend the i right so do we have to take care about zero index no right because uh if you notice the zero index is always the same so if i didn't assign uh for the next iteration for the in array i would just basically just by default it's going to be zero and for the uh and also for the n right the first one is definitely one but i didn't assign the last index for the next phase right so you would just by default it's going to be zero right uh sorry yes if i didn't change anything it's one bit it's gonna be by default it's gonna be zero it's not one sorry i just have a um typo i mean not typo just a wrong statement right so i would just have to go through the cells for a neighbor so if they're starting from one right i need to know zero and two right so cell if the cell i minus one is equal to cells if i perform right if they are equal i'm gonna assign one if they are not i'm gonna assign zero right so okay so i have a heaven in the ring next i'm going to convert to the string so you can say eraser to string if passing the next or you can say what string uh it's a new frame right new string and then sounds right doesn't matter it doesn't matter how you use right but i will say okay do i have it in the set subset content data contains valve right if i don't have it i'm going to say that about right and i will just cheat chocolate flour comes and if i okay if i don't have it i into the same and i keep travel of the account so if i do have it i will have to make my cycle a little true right now bridge right operate and then so i would say if the cycle i will do something right but beforehand i need to update my cells for every single day right i will just update my cells and then cells you'll just need to set equal to an x for the next iteration and then we'll just stick them in my base all right if this is happening this cycle then we just have to calculate the n uh for the rest of the cycle contract and then traverse forwards of the uh updating right for the cells so cells equal to the next state itself and at the end you will just return cells right so i'm going to explain uh what happened so um i have a set i sorting i store into the string and i convert the inc array into the string later so i have a psycho count to choco flow count after every iteration right and i have a base temporary variable and then i have a cycle boolean just making sure i know uh there's a cycle so i'll create a temporary in array it's going to call next so i will i'll just have to generate a new in array based on the this helper function so this is checking the neighbor if they are the same then one not the same zero so it's going to be like this but the problem is i don't need to traverse anything right but you have to say one right so uh you don't need to traverse again you just have to traverse at this point right and then temp will just update it all right so uh this is a typo for sure all right and let's move on so i will convert to the string follow in a rate and then i check do i have it in the set if i don't have it i will add to the string and then i will just kick off to increment my tones if i do have there's a cycle for sure right and i'll break out the side a regular well loop and then for every single time i need to update my current cells to the latest you know rate uh latest cells right so if i saw this day zero i need to update to day one for next iteration right now i need to just making sure do i have a cycle if i do have a cycle which mean i didn't finish the iteration because i need to just finish until uh day seven right if i break out early break earlier then i need to traverse rest of the days uh if that's happening so i would just use in the mall will just give me like uh give me kick track of the racing uh for the rest of the days right so i'll just traverse the rest of the days for the next day and then i will return the final solution for sales and let me run it oh i do have a typo cycle pump right okay sorry and missiles no all right let me submit all right so let's talk about time and space so for the space this is space but uh this one is the most important they should be like how many iterations you can happening in the cells right so it's going to be uh all of um right uh times what the number of cells right so uh it's going to be all of m times c and for the time this is time it looks like this is always what always uh land of eight so loaf eight right but the problem is what the n right the sun could be larger right so uh this is all of n base all of n times uh all of seven i mean sorry all of h all over h right so uh so it's going to be all of n and it's full time again all of n and this older thing is definitely shorter because you use more so i'm going to ignore this time complexity i'm going to use the worst case all of n and represent this one and if you want to be more on detail you can say all of n times h right and then for the space this is a space how and you have to store how many time uh string you need to store the number of time for the cells right so it's going to be all of c times n right and this is a solution and i will see you next time | Prison Cells After N Days | minimum-add-to-make-parentheses-valid | There are `8` prison cells in a row and each cell is either occupied or vacant.
Each day, whether the cell is occupied or vacant changes according to the following rules:
* If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied.
* Otherwise, it becomes vacant.
**Note** that because the prison is a row, the first and the last cells in the row can't have two adjacent neighbors.
You are given an integer array `cells` where `cells[i] == 1` if the `ith` cell is occupied and `cells[i] == 0` if the `ith` cell is vacant, and you are given an integer `n`.
Return the state of the prison after `n` days (i.e., `n` such changes described above).
**Example 1:**
**Input:** cells = \[0,1,0,1,1,0,0,1\], n = 7
**Output:** \[0,0,1,1,0,0,0,0\]
**Explanation:** The following table summarizes the state of the prison on each day:
Day 0: \[0, 1, 0, 1, 1, 0, 0, 1\]
Day 1: \[0, 1, 1, 0, 0, 0, 0, 0\]
Day 2: \[0, 0, 0, 0, 1, 1, 1, 0\]
Day 3: \[0, 1, 1, 0, 0, 1, 0, 0\]
Day 4: \[0, 0, 0, 0, 0, 1, 0, 0\]
Day 5: \[0, 1, 1, 1, 0, 1, 0, 0\]
Day 6: \[0, 0, 1, 0, 1, 1, 0, 0\]
Day 7: \[0, 0, 1, 1, 0, 0, 0, 0\]
**Example 2:**
**Input:** cells = \[1,0,0,1,0,0,1,0\], n = 1000000000
**Output:** \[0,0,1,1,1,1,1,0\]
**Constraints:**
* `cells.length == 8`
* `cells[i]` is either `0` or `1`.
* `1 <= n <= 109` | null | String,Stack,Greedy | Medium | 2095 |
1,696 | That will be the morning to day to ask question is jump we six Soviet Union to Soham told by name came out if your initial futile effort heroine we here to Vijendra young adult most cases forward so and placid inside Sadher Lau example can go Vaastu study If for this we have to click the like share and subscribe button here we can go here but 101 - 2 - can go here but 101 - 2 - can go here but 101 - 2 - so I will do this here we will go from here now we can come like here If it was zero then it is zero - if it is 2070 plus 4 then zero then it is zero - if it is 2070 plus 4 then zero then it is zero - if it is 2070 plus 4 then maximum will get justice, after that we are here as we are, so we could go to the last, now we will not go to apply, we will go to Fida Dedar, if there will be margin of sleeper and four plus then this If it is going to be taken out, then basically if I understand then I can go in the hands of two options for those who have eggs, then they can go with the second option and basically we have to vitamin in some maximum then this cup is fixed figure Deepika Padukone If it seems like a one week solution, then what will we do, for this we will take this school, what should we do, we were also told that after this we will see here, let's try that - 509 have been done so see here, let's try that - 509 have been done so that you will get the fiber here. After that, if we count this volume then tension will be done here, we will have the option to go to the pipe, there will be international debit, then here the answer will be 8 app, for all this, it has to be flat like this, the duty person is like this, Meghna is here. Here and here fry luck will come to us here eighth if we give it a ball this hair if you have a group then it will be added either seven will be 100 this is our answer sheet for this no subscribe can't take subscribe Now let's do this, so we can say which ones, so here we can say that half a minute from now, there will be another 911, so this is what you see every day, let's look at this once, welcome back to the, to understand this. What is happening, how are you, basically we have this less, that is why we have found its maximum, if we look at the time for this, like if we go from equal to one to equal to k, then we will have to take one ruby for n and Debiting us for doing vitamins in the name of Vikram will be yours and the complexity of *K but here it will of *K but here it will of *K but here it will not be the head and asked for a difficult English, then if you will regret the problems, you must know that Tanglish to Bigg Boss for 9 months. Tennis 287 Chetak's are loud, competition is shown to a normal PCs in one second, because of this, our basic here is that bell * only approach that bell * only approach that bell * only approach will work, song will end and login, either we will have to think something like this, then what will we do to login. Reminder use max, maximum volume, then whey login in it will kill the bike, and then in doing Namaskar tower, if Mara and Pintu will give camera, then they can see the coat quickly in the process, so for that we will have to take a note first. So class node in this, what happened to you, this will be our indication, this is to do induction stove because we need to check thing, our basically what we will check is one to three, we set it only in the end position, if we are on the floor, then we pan. Ca n't take the maximum right five minutes to the value of the and also indicators so one by one will make the lower part of it these are Indian XXX So n Indian postal new mint namaskar lens ka dp koi abusi basically mi uie name wali ke zero so sad image complaint singh table hain now we have to make a CM in private max key we will use it because maybe not only to make We will use this for primary fuel soap opera here was the daughter she was Entries word max only question you are often positive why am I now that we have a servant Entries we need a note we have to compare according to the value of this note development of our maximum Index of note Our maximum should try the value of note of intestine So for this we will use function by keeping name So here we will take notes in lineage 9 end to end It will return us end against aluminum zinc wanted owner What should we do here When why do I like, the first one is of value, so if we have air to check, then for that, if we were to become the president, then what will we do? The channel of * key is there - if we do, then channel of * key is there - if we do, then channel of * key is there - if we do, then one of them is positive. Wali this will be mature example if and 210 is n 184 test minus plus two vagina tells positive trends that element small entry se and similarly you can be a great art for the second that when in 110 and this then Lakshmi pendant and * - click 110 and this then Lakshmi pendant and * - click 110 and this then Lakshmi pendant and * - click We will subscribe to the maximum, this was our ghagra, now we have to pay the payable bill, we were looted and with these efforts, Amazon Radhe and I 75 questions, first we will check Narayan that it will not be like you, that we will enter the valid key. Sibal has appointed as another person against that access Sibal has also seen from the social media that the mobile has been given by us as to why it is not there and our basic value which will come is at our maximum only which is the value of the topmost index. The maximum element is one of ours which we will use, so at least that is our come - how is it small or not, I will our come - how is it small or not, I will our come - how is it small or not, I will go to the maximum about it when we will do the boxing of the court, so if it is so then basically let us take out that black, ginger and that mileage. I am not sure that after this, we have to click on the Sacrifice table, Samaj Namaskar Lee, along with that, we have to add it, which will be at the top of the marksheet, that is, it will be the maximum one, and we have to add it. Will also have to do in our interest Should they be in the dark world Nude DP Aaye Earns That Solid Surandra Is Vansh Is An American Will See Lowest Glycemic Reach So That's Why We DP That Kalyan Singh Ne Theater Will Do The Day On YouTube Ishwar Allah And His Messenger Question Net is available and Kheda's obscene abuses of our robbers have been made nice. I have just compared them. Thank you, I have made it a how-to by posting it here, so we have already handled the zero-valued thing. handled the zero-valued thing. handled the zero-valued thing. Subscribe to the song. Can't do that yesterday in the office we have already done that point, we will do that point again there was a suicide note knotted resorting to admit scientist is talking about this so let me explain to one of the drops so basically what we did here is this Software of Planets has just become Asaf Khan, two basic aspects are there only this much are there, stand a product of Europe, Jai Hind, this orange which is Bollywood, apart from this all the rest are our or people's loot words which are your special mission Bhindi that he slept right now This is Lalu Yadav, so what are we doing now, we went to the high cost one, that is, we basically went to this volume, now what we have to do is here, we checked whether our person is an MP, he is not, 2010, we have to see that when our amnesty is on. Which is the maximum potato's link, how is the wireless small, what Dr. So, the age is 40 minutes, 512 - free is - 200 notes, minutes, 512 - free is - 200 notes, minutes, 512 - free is - 200 notes from very dangerous, so killed, made sure to put it in the dpi of the brothers, hello, volume plus, this which is on the maximum, which At the top of the volume maximum will be looted solid 20 plus minus five and night and the name of this church we came try is broken if we will check by going here that brother high cost for that they him but like that or not so if you here Our two is like this okay so here we have like subscribe now to check the volume maximum volume 98100 Noida two minus one not to where so we will make it - 28 so we will make it - 28 so we will make it - 28 200 this will work in 8 to Nobel price grocery light Switch first, how will we check, even now the navi chatting is not broken, dance and why is this indiscriminate correct order that we are justified in this to show's glory, Shri Mahima people, I am still at the same time, forced to go, Sukshma will go to high cost, this is ours. Because it is free but on high cost method, our mango will be checked that this is Jayesh Jain Free - 30 Aug 09 This is this is Jayesh Jain Free - 30 Aug 09 This is this is Jayesh Jain Free - 30 Aug 09 This is not Fruits Sexual So on this we will basically find out that we have set the maximum N plus minus On Eggs And Not Adding That In Correct Quantum Jatt Flying Instructor To So You Think This Expression Hair Treatment Maximum In Next Video Icon To 400 Witnesses In Snow Line This Zinc Noida Office - Before PIMS Is Equal To One Zinc Noida Office - Before PIMS Is Equal To One Zinc Noida Office - Before PIMS Is Equal To One So We Basically Have To Rally Which Till then we will not be able to do this will have to be removed here, basically it will be that A and Navami's relation is on five, now the maximum has been contacted that due to which Aalu * 90001 is two places in that due to which Aalu * 90001 is two places in that due to which Aalu * 90001 is two places in five. 93 not loose school so this belt is point to so we will check it that maximum okay here we had to debit one glass one that for this set we have to love index this form one so normal note 4 which retrieve from the kinnars Hoga word, both are necessary and both are belts, then for that we will check. Here, take out eight, one plus three, Lud 5911 Sir, subscribe to the channel here, I am not able to understand anything | Jump Game VI | strange-printer-ii | You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**.
You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array.
Return _the **maximum score** you can get_.
**Example 1:**
**Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2
**Output:** 7
**Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7.
**Example 2:**
**Input:** nums = \[10,-5,-2,4,0,3\], k = 3
**Output:** 17
**Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17.
**Example 3:**
**Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2
**Output:** 0
**Constraints:**
* `1 <= nums.length, k <= 105`
* `-104 <= nums[i] <= 104` | Try thinking in reverse. Given the grid, how can you tell if a colour was painted last? | Array,Graph,Topological Sort,Matrix | Hard | 664 |
409 | hey guys welcome back to another video and today we're going to be solving the lead code question longest palindrome so in this question we're given a string which consists of lowercase or uppercase letters and we need to find the length of the longest palindrome that we can build using those letters and note that this is case sensitive so capital a and small a is not considered a palindrome and assume the length of a given string cannot exceed this number thousand and ten okay so what exactly is a palindrome and how can we solve this question so let's just take a quick look at that so let's say that we're given these letters as our input so we have a b c d okay so what is a palindrome is let's say you have this over here a and a okay and when you read it from left to right you go a then you get n then you get a but when you read it from right from left so right to left you get a then n and then a again so a palindrome is when you read it from left to right or if you read it from right to left it's the same but in this case we need to make sure that the letters are case sensitive so for example if we had capital a big n and small a this is not a palindrome but this is so it is case sensitive in this case okay so now let's see how can we find the length of the longest palindrome given a string so to do this what we're going to do is we're going to count the frequency of each of our letters so i'm going to do this inside of a dictionary so first we have the letter a and it has a frequency of one it only appears one time then we have the letter b sorry which also has a frequency of one and we have the letter c and this has a frequency of one two three four so let's add that and finally we have the letter d which has a frequency of two so this is going to be our dictionary right where we're holding all of the frequencies actually for the purpose of this video i'm going to add one more d over here so i'm just going to change this value over here to three so instead of two we're going to have a value of three okay so we have a b c and d has a value of three so let me just add that here there's a third d okay so how can we find out what the length of this palindrome is going to be and the answer to that is pretty simple we're going to start off by looking at everything that is even so what is even over here c is even so let's just go to c and we're going to add c on each side so for every c we have on the left hand side we're going to have a c on the right hand side so as it is it's a palindrome cc so let's do it again so we have two more left so we add one over here so far we got four letters down and as it is it's a palindrome so we took care of c now let's go to d so d has three letters and the thing is uh we can't use all three letters but we could use some of it so what we're going to do is we're going to use how many ever possible to make it a valid palindrome and the answer to that is we can use two parts so we can only use two d's so we can use one d over here and one d over here so we're going to have c d and then d c over here now the remaining letters all have just a frequency of one and note that over here we used up two and d currently has a frequency of one so what we can do over here is these three on the left and these three are on the right are always going to be constant but we can have one letter over here it could be anything so we can have one letter over here this letter can either be a so if you check this is palindrome or this letter can be b or this letter can be d any of them work so the answer for this is we have a frequency of 1 2 3 4 which can be any letter over here and we have 5 6 7 and just to clarify when i say any letter it means any letter which has an odd frequency so in this case a b and d since it has a frequency of one since we used up two of its letters so the answer for this is going to be seven so the answer is seven and we're going to output that so let's see how we can write this in code it should be pretty simple to understand all right so we could do so all we need to do in the beginning is we need to find out some sort of way to store everything in a dictionary per se and we could use the counter from collections but instead we're just not we're not going to use any libraries and we're just going to do it using pure python so i'm going to create a dictionary called letters and it's going to store all the letters and what we're gonna do is we're gonna go through each character so for character in our string s and if i not in our if i not in letters so if it's not in our dictionary then in that case we're going to add it to our dictionary with the frequency of one so it's going to be letters i equals to one else so this is not the case that means that it is inside of our dictionary and we're just going to increase the count by one so we're going to go to letters i and we're going to increase its frequency by one so plus equals one so now we have our dictionary ready and over here i'm gonna uh set two variables so one is going to be our result and over here i'm going to have a variable called odd which is going to count the in the number of instances of odd values we have okay so now that we have that i'm also going to have a if statement so if the length of our letters is equal to one so what does this mean so whenever length of the letters is equal to one that means that there's only one letter and let's say there's only one letter and you have it repeated nine times or a thousand times how many of our times it's always going to be a palindrome since there's only one letter so in that case no matter what we're just gonna return the length of that so we're gonna return letters and the values so it's just going to be s0 okay so uh this is the key s0 is going to be the key and we're going to return whatever value that is so that's going to be our answer but if that is not the case if the length of our letters is more than one in that case we're going to iterate through all of the values so for i in letters dot values okay so this gives us all of our values and over here we're gonna have a if statement which checks whether this value is greater than one so if it's equal to two or more than that so if that is the case we're going to go into two if any of the two if conditions so if i mod 2 is equal to 0 so in this case it is an even number and in that case we're just going to add the value of i to our results so that's pretty straightforward but if the value of i mod 2 is not 0 so in this case it's an odd number and we can make it even by just subtracting it by 1. so we can add all of those numbers to our results so in this case all it's going to be results plus equals i minus 1 since we're going to remove one of its numbers one of its letters and what we're also going to do here since now since we've removed one of them it's going to be remaining with one odd character so we're going to add that to our odd list so odd we're going to increase its value by one and we're also going to do that one more time if our so if our value is not greater than one and in that case we're going to increase the odd value by one again and now finally for our last step so over here if our odd value is greater than zero right if it's greater than zero so that means that we do have an odd value remember that we can add one of the one of those values in between right so we're going to add that to our results the results plus equals one and then we're going to end up with uh returning our results so return result so this should be our answer so let's submit it and let's see what happens okay submit okay sorry i called it i over here this is supposed to be character so for character this is character again this character okay here we go okay submit all right and as you can see our submission did get accepted and finally do let me know if you have a better solution to solve this and thanks a lot for watching guys and don't forget to like and subscribe if this video helped you thank you bye | Longest Palindrome | longest-palindrome | Given a string `s` which consists of lowercase or uppercase letters, return _the length of the **longest palindrome**_ that can be built with those letters.
Letters are **case sensitive**, for example, `"Aa "` is not considered a palindrome here.
**Example 1:**
**Input:** s = "abccccdd "
**Output:** 7
**Explanation:** One longest palindrome that can be built is "dccaccd ", whose length is 7.
**Example 2:**
**Input:** s = "a "
**Output:** 1
**Explanation:** The longest palindrome that can be built is "a ", whose length is 1.
**Constraints:**
* `1 <= s.length <= 2000`
* `s` consists of lowercase **and/or** uppercase English letters only. | null | Hash Table,String,Greedy | Easy | 266,2237 |
1,920 | today we will try to solve lead code easy problem 1920 so we'll try to build array from permutation so let's see how is this problem okay so i'll try to do i will try to challenge this problem in javascript because that's my programming language which i like to code in so what we have to do so we have got here basically is the input which is 0 to 1 5 3 for its array of numbers and the output is this so they already say uh how this output we get it so what they're trying to do basically for each index so basically for num of zero you have to take again a index of that number so basically num of zero is zero right so then you again take an index of this zero so what's on the zero it's zero so you print zero here then you go on the num of two so when you do that num of two here what's number of two here so zero one two right so it's one so you print one so on you go with num of one then you again take one so that would be this so you print it like this and when you take number five and you again take the fifth element of this array which will be zero one two three four five which will be four so we'll print four here so that's how the array we get the output so how we'll gonna how we're gonna tackle this so we're gonna write our input and we're gonna write our output it's just gonna comment this and then now i'll make one more comment that how i'll tackle this so basically i'll have to run a for loop so run a for loop through nums array right and so that i can iterate over the all elements so i'll try to teach all of you guys from basics here right so basically for each i is basically all element inside that array we will be putting the new with putting the new value we'll get and replace it with i the new value and replace it with i right and we'll just return the output array or the error which you get in the beginning right okay so that's how i try to solve the problem so i just try to write it down before and then try to solve it so see how we're going to tackle it so what we want a fresh output error right so we'll create output array which is which will be empty so then what can we do so i'll create a for loop so i try to use classic for loop so for i equals zero i should be less than numps you want to look through nums right so nums.length we don't want to go right so nums.length we don't want to go right so nums.length we don't want to go over it i plus easy uh now so now what do i want is i want to go to that output array each index of it and i want to replace it with nums is what the array which we've got and what do i want the letter what letter i want to put that output at i is nums of i but then i want to put the letter then the integer which is on there so this one if you see and when i do this i don't need to do anything else that's it i can return the output so i'll return the output right so how it's working basically let me explain you from here when let's say i zero right so i zero so output at zero would be nums at num set 0 so num set 0 is 0 and then they ask okay what's at 0th index is 0 so we'll get 0 then when it goes to let's say when i is was the output.length one two three four the output.length one two three four the output.length one two three four five six so let's say the fifth element when i will be five right so when i will be five it will say okay num set five so num set five will be this thing fourth right and they say okay what's at the fourth element the fourth index so fourth index is zero one two three four three so then we got three at the end if you get what i'm trying to say then if you try to return the output and if you run the code see we got the answer because run 1067 and you can submit the solution as well so it should work yeah it passed all the use case test cases so our solution was faster than 33 percent and only 46 mb less than 26 percent solution so it was a good solution thank you so much come back on my channel for easy solutions like this | Build Array from Permutation | determine-color-of-a-chessboard-square | Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it.
A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**).
**Example 1:**
**Input:** nums = \[0,2,1,5,3,4\]
**Output:** \[0,1,2,4,5,3\]
**Explanation:** The array ans is built as follows:
ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\]
= \[nums\[0\], nums\[2\], nums\[1\], nums\[5\], nums\[3\], nums\[4\]\]
= \[0,1,2,4,5,3\]
**Example 2:**
**Input:** nums = \[5,0,1,2,3,4\]
**Output:** \[4,5,0,1,2,3\]
**Explanation:** The array ans is built as follows:
ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\]
= \[nums\[5\], nums\[0\], nums\[1\], nums\[2\], nums\[3\], nums\[4\]\]
= \[4,5,0,1,2,3\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] < nums.length`
* The elements in `nums` are **distinct**.
**Follow-up:** Can you solve it without using an extra space (i.e., `O(1)` memory)? | Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern. | Math,String | Easy | null |
208 | hello there so today's li coding challenge question is implementation of tri prefix tree yeah that's finish the question we have to support three operations insert which is memorize a word search is to find we do we have the word thirdly is the star Swit it's a do we have a partial March for the searched word so that's pretty much these three method that try data structure should support and if you don't know try it's basically a em wait trees so can contrast it to binary tree only have two children's in Tri can have n different arbitrary number of children's so if you look at the string API ohyeah you can think that they're gonna be rude to know the points that has a child with a character with a key value of character a and that node will have a bunch of child and one of the child there is going to be the character P and you were just you know you imagine there is this tree kind of structure from the root towards the leaf it's gonna be representing a path that reads like a PP le so I just draw this some kind of a like a picture they're gonna have if we insert Apple in here so it will be a the P Elle and finally II before you insert another word which is maybe something like a dog so it will be a child to the road with this which is carp to D and it will also be a reference to contain a pointer to the child node o and G so basically when we insert a word into this tri data structure we are populating a route to leave past if it's if the node are not there otherwise we're just traversal through this tree and you know creating nodes as necessary there is something that we need to indicate at the end of the world so for each node here beyond the reference to the next node there actually also have a termination flag to indicate that this is the end of word so you can imagine with a bunch of Fortran fours for every node here that's just indicating the way have a word at the ends here so to search for word we basically just traversal through this tri data structure character bar character from using the search term search word and once we reach the end we want to check do we have a flag in there so if we insert Apple and dog and search for a P this P here will have F flag which is false so there is no such word in there if we insert a P will be you know traversal through this tree and turn this flag to be true and if we do the starts with search partial marching it's also the traversal through the tree as long as we don't find a dead end somewhere in the middle of the search traversal then we can return true otherwise it will be false so that's how we support starts with so by using this data structure the insert search and starts with they all be the time complexity are all linear with respect to the number of characters in the tree in the word so it's basically rude to leave in the worst time was case and for space search and starts with they don't create anything so it's gonna be constant but the insert it's gonna be in the worst case every character we have to create a you know allocate some memories for that so it's gonna be linear respect to the lens of the word so that's the worst space requirements for insert and yeah that's pretty much the quick explanation about what is try and how it works so I'm just gonna start and code this up so the try structure is as a is holding this whole thing together but for each individual node in there it's a smaller data structure I'm just gonna have a separate one to make it a bit cleaner fundamentally this tri node here who holds two things one is the boolean flag indicating whether this is a end of award the other thing is this parent or child kind of relationship and you will be able to access the child by the character so you could it gonna be it would be a key value mapping with the key be the character and the value be the pointer to the actual child node object and you could use eraser as well because we are dealing with a fixed letters A to Z but in the case that if you have caronian vocabulary how this to be fixed that might not be a good idea so I'm gonna use a hash map for this purpose so we have two data items here where the first thing is the boolean flag and the second thing is the map which is character to the node mopping that's called a child children then we're going to have some popular message for accessing this okay first thing first this constructor which just set a flag to be false and the children to the empty then we need the setters to turn the FAC flag to be true when we reach the end of the word and we also need to be able to access the flux value so we have a getter and setter for the flag so this will just be returning the return the flag value setters of void just are just indicating this is the end of word therefore the children we need a setter to create a new character to node mapping and we also need a membership checking do we have a character a node with associated with this character so that if it's not there we can do the insert if it's in there we can just Traverse us through that node so we need not us not a getter but a membership checking let's call contains which takes a it character and you just check whether we have a character in the children so it's a children see greater than zero lastly is the Center for the children which takes a character and the actual node what it does is to create this association genes and that's pretty much the final class fundamentally it has the flag and the child to parent to child relationship where each child is identified by the character and that's the try note and let's work on the Twilight instructor so for we're gonna have a root note here which is going to be initialized to be a empty try note in the beginning so it's going to be a pointer to try note in the constructor would basically set this to be a new try Note 4 insert we have to process the word character part captor so we're gonna have a for loop for each character we're gonna check do we can tell do we have that if we have that we don't create a new note if the if we don't have that note character yet like the first a if we if there's a fresh try we only have a root when we see the first record a we're gonna actually create that try node and establish the parent to try out the relationship so if it's not in there then we should do this which is so we should we can grab a reference to this first if we don't have the key then we're gonna use the set child copy please to be the character C and a new note so that's if we don't have the note otherwise we'll just follow that note and process forward which is going to be known equal to oh we need a getter I'm sorry we need a getter - - traversal inside this inside getter - - traversal inside this inside getter - - traversal inside this tree so good child takes a key and we should return the child does it look right yeah it takes a key and return the children with that key so that's the insertion once we process that once we are done with this full loop we should flag the very last node to be true so it's a despite it's done by calling the set fly so that's insertion search is pretty much a similar and copy this the only thing difference is that if we don't have that character we return false otherwise we shall keep traversals through the Twilight data structure and in the end we should return whether that no determination node has a flat and starts with a say it's also very similar to this so we're working with some prefix rather than word now if we just don't have that character we should return false otherwise we should keep traversal going down into the towards the leaves and if we don't return false in the middle of the search values we can successfully you know process all the character in this prefix so in the end we should return true so that's pretty much the logic the three parts are really similar it's a it all starts with this route and just going down the path towards the leaves in the insertion or check if the note is nothing there it will actually create the node and establish the parent to child mapping otherwise you would just in the case of search and starts with it just traversal through the tree the only difference between search and the starts with is search for search you want to grab the flag for the realistic character associated with the node of the realistic character before starts with as long as we don't terminate early we should return true so that's the only difference between search and starts with so let's quickly check do I have some stupid mistakes it looks okay yeah so let me try to run through some examples No Carol uh I sure no not this one it's a boolean but I'm not returning the returning listed this condition checking so that's the only error okay let's submit all right so that's the implementation of try yeah that's pretty much the question they're just very happy that I can cut this thing up easily now compared to two years ago I don't even know this thing existed yeah so that's all | Implement Trie (Prefix Tree) | implement-trie-prefix-tree | A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
* `Trie()` Initializes the trie object.
* `void insert(String word)` Inserts the string `word` into the trie.
* `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise.
* `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise.
**Example 1:**
**Input**
\[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\]
\[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\]
**Output**
\[null, null, true, false, true, null, true\]
**Explanation**
Trie trie = new Trie();
trie.insert( "apple ");
trie.search( "apple "); // return True
trie.search( "app "); // return False
trie.startsWith( "app "); // return True
trie.insert( "app ");
trie.search( "app "); // return True
**Constraints:**
* `1 <= word.length, prefix.length <= 2000`
* `word` and `prefix` consist only of lowercase English letters.
* At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`. | null | Hash Table,String,Design,Trie | Medium | 211,642,648,676,1433,1949 |
274 | hi everyone welcome back for another video we are going to do another decode question the question is h index given a array of integers citations where citations i is the number of citations a researcher received for their i've paper return compute the researchers age index according to the definition of age index on wikipedia a scientist has an index age if age of layer and papers have at least age citations each and the other n minus age papers have no more than age citations each if there are several possible values for age the maximum one is taken as the age index let's walk for the code we first sort the array citations in ascending order we land it away fully away if a array element at index i is greater than the citations the length minus i then other elements to right of index i must also satisfy the condition since they are greater than the element at index i return citations the length minus i if there is no element that satisfies the condition return zero thanks for watching if this video is helpful please like and subscribe to the channel thank you very much for your support | H-Index | h-index | Given an array of integers `citations` where `citations[i]` is the number of citations a researcher received for their `ith` paper, return _the researcher's h-index_.
According to the [definition of h-index on Wikipedia](https://en.wikipedia.org/wiki/H-index): The h-index is defined as the maximum value of `h` such that the given researcher has published at least `h` papers that have each been cited at least `h` times.
**Example 1:**
**Input:** citations = \[3,0,6,1,5\]
**Output:** 3
**Explanation:** \[3,0,6,1,5\] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.
**Example 2:**
**Input:** citations = \[1,3,1\]
**Output:** 1
**Constraints:**
* `n == citations.length`
* `1 <= n <= 5000`
* `0 <= citations[i] <= 1000` | An easy approach is to sort the array first. What are the possible values of h-index? A faster approach is to use extra space. | Array,Sorting,Counting Sort | Medium | 275 |
1,288 | hi all welcome to learn code repeat so today we will be looking at day 4 of the october lead code challenge the name of the problem is remove covered intervals let's look into the problem so the problem says given a list of intervals remove all intervals that are covered by another interval in the list interval a comma b is covered by interval c comma d if and only if c is less than equal to a and b is less than equal to d after doing so written the number of remaining intervals so basically the question asks is if there is an overlapping interval then all the sub intervals inside that needs to be not considered and only the main overlapping that is the superset interval needs to be considered and give the count of that so let us look into the first example here we have 1 4 3 6 and 2 8. so let us plot this example so 1 4 will be like this is the interval 3 6 is from here to here and 2 8 is from here till here right now if you see what the condition it says is the interval that is covered by a super interval right so this is a super interval which covers this particular interval right so this should not be considered and then return the count of whatever intervals are not covered right so this will be one this will be two so the output is expected to be two right now if you see this once you plot it looks like very simple to identify the intervals that are not covered right the condition here was a comma b c comma d and a is less than or equal to c and b is less than equal to d right so if it is a comma b and c comma d then c should be less than or equal to a and b should be less than or equal to d what this means is this is my a and this is my b right and this is my c and this is my d so here c if you see c is 2 and a is 3 so c should be less than equal to a that is what is given here d is greater than or equal to b or in other words b is less than equal to d right that is what is given here so if this is a condition that means the c d is overlapping a b right in that case we should not consider a b ok so the reason once you plot it you are able to identify is because you see this you visualize this as a sorted interval right so that is what we can do here we can directly sort this array because this is unordered array we can sort this interval array and once you sort this you can see that based on this condition you can identify if the interval is overlapping that means if this condition is satisfied that means the interval is overlap so when i sort this right this superset will come first and then this will be coming right in this case at least in this case right so if this is my current i position right or let us say this is my previous interval which is i position and this is my current interval which is j position right so i just need to check whether interval of my previous position which was i of 0 is less than or equal to i am using the same condition a is my current intervals position right j comma 0 okay if this is the condition and here it will be b right b is this is j so that is my current 0 is less than or equal to interval of sorry here it will be one current one is less than or equal to interval of i one right so in that case if this is less than this if that condition is satisfied then my current interval needs to be removed from the total length right so let us say if i am having a count variable which is 0 right i can simply increment that count right but if that is not the case right then my overlapping right should be considered as my current so my previous right previous j or either previous i should be equal to j i is my previous index right so i should point to j and that we can do it in the for loop once we have the sorted array so this is a very simple algorithm that we can use however there is a catch here the way we sorted is important because we not only need to sort it by the starting index but we also need to consider the ending index let us take another example so here i have plotted the graph i will come to this part later on so here i have plotted the graph and if i see this particular interval is overlapping this so i have crossed out this similarly this interval is overlapping this one i have crossed out this and this interval is also overlapping this so i have crossed out this one as well so at the end we have only two largest intervals so that is why the output is two so here if i only sort by the starting index right so if you see this can come first or this can also come first in the array right if i sort the array only by start index and if that is the case then a condition of c is less than or equal to a and b is less than equal to d right to satisfy this condition we have to identify which of the interval is c right which is a b and which is c d it can be that this is a b and this is c d or it can be the other way as well right so to check that we have to also check which one is having the largest n index right which is the maximum n index in that case and we have to take that as the c d ok so to keep a track of that right we have to create one more variable to keep a track of which one is the largest index and so point that variable to that particular largest index so to remove all this complexity while sorting we can very well sort by start index and end index right so what will happen in that case right so when i sort with the start index and an index i will sort by start index in ascending order and by n index in descending order so my output will be something like this right so 1 7 will be first because 1 and 1 is same but 7 is greater than 4 because we are sorting the n index in descending order this will come first right so let me write down the index value here so this will be 0 this will be 1 this will be 2 this will be 3 and this will be 4 right so here i am making sure that the largest overlapping interval will come first before its sub intervals which the largest may be overlapping with that right so once i have that order in place right i can very well say that my current interval if it is largest that is a c and d value right so i can start with saying that i equal to 0 i is my largest overlapping interval and j is my current counter which is the next interval right and i can have this j in a for loop j equal to one till j is less than my length of the interval and j plus ok now i can in my for loop i can just do the do this check right that they have provided so i is my largest interval right so i of 0 is less than or equal to j of 0 okay so i am checking first this particular condition and into now b is my j value j of first index is less than or equal to interval of i of first index ok if this condition is satisfied right that means my i index interval is overlapping my j index interval right so i am incrementing the counter okay however if this condition is not satisfied right so that means my current j interval is not getting overlap by the i interval right so when i go to the next counter my j interval may be overlapping the j plus 1 interval that may be the case right so in that case i need to assign i as the j value so basically i is keeping the track of which interval may be overlapping the next interval so this is the simple logic here now let us code this algorithm so first i will get the length of the array now if my interval is zero length or even if its of size one right i can directly return the output as the length value right so i will add that check here so i am assigning my i index as 0 and my j will start with 1 i will also assign a variable counter to count the total number of intervals that are getting overlapped so initially it will be 0 now the if condition will be there if this is a case then i need to increment my counter else my i will be equal to my g ok this will be my condition inside my for loop and before this i need to also sort my array so here i will do a arrays dot sort intervals and the comparator will be if my 0th index is not equal to my other 0th index in that case so if my a of 0 is not equal to b of 0 that means my start index are not equal then i can directly do a ascending order for my start index else i need to do descending order for my end index if my start index are same right so this is my comparator for the sorting order and once i have the counter incremented that means i am counting all the intervals that are getting overlapped by some other interval right so once i know that right i can very well return my length minus the count so this is the remaining value right so let us submit the code and see whether it works fine and the code is accepted so the complexity of this algorithm will be o of n log n the reason why it is of n log n is because we are doing a sort here so sorting takes o of n log n and after that we are going through the intervals again which will be o of n so it will be o of n log n plus n which is same as of n log n so the time complexity is o of n log n and since we are not using any additional space so the space complexity is o of one hope you like this video if you have any question please do write into the comment section and if you haven't subscribed to the channel please do subscribe to the channel thank you | Remove Covered Intervals | maximum-subarray-sum-with-one-deletion | Given an array `intervals` where `intervals[i] = [li, ri]` represent the interval `[li, ri)`, remove all intervals that are covered by another interval in the list.
The interval `[a, b)` is covered by the interval `[c, d)` if and only if `c <= a` and `b <= d`.
Return _the number of remaining intervals_.
**Example 1:**
**Input:** intervals = \[\[1,4\],\[3,6\],\[2,8\]\]
**Output:** 2
**Explanation:** Interval \[3,6\] is covered by \[2,8\], therefore it is removed.
**Example 2:**
**Input:** intervals = \[\[1,4\],\[2,3\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 1000`
* `intervals[i].length == 2`
* `0 <= li < ri <= 105`
* All the given intervals are **unique**. | How to solve this problem if no deletions are allowed ? Try deleting each element and find the maximum subarray sum to both sides of that element. To do that efficiently, use the idea of Kadane's algorithm. | Array,Dynamic Programming | Medium | null |
48 | said today let's see this rotate an image romantics problem so it's a medium problem let's quickly jump into the description so you're given an n into n 2d matrix representing an image and we are asked to rotate the image by 90 degrees clockwise okay and they're saying that you should have take the image in place which means we should not use extra memory you should use the same matrix and given this input matrix 1 2 3 4 5 6 7 8 9 you have to rotate this matrix in clockwise also you should rotate the matrix in place so how do you rotate this matrix let's say you have a point you're at 7 you have a reference point it's 7 let's pull this and rotate this matrix so when you rotate it you'll get 7 on the top and 4 will come next to it and then one will come next to it right now whatever it is next to 7 will come again at the top it in beneath 7 and you will have 8 by 2 and then beneath 8 fight you will have 9 6 3 so that is how this rotated matrix is got so if you have we no trouble understanding this maybe you can write all these numbers in a paper and then try to treating the paper and you look so that seven you come to the top and four will come next to it and then one will come next to it in other words you can you know have a reference point at 7 and try imagining that you know you're pulling to rotate it clockwise so if you pull this up right 7 well if you pull this up so I'm come to the top and 4 will come next to it and one will come next to it and whatever is beneath 8 right since you're pulling 7 to the top it will also come to the turbit then since 7 is at the top it will be beneath it right so since we are rotating this in place right why the approach that you going to employ is vivianne to transpose the matrix so what is transpose of a matrix a transpose of a matrix is nothing but you know you transform the rows into columns and columns into rows so 1 2 3 is a row here in the input matrix a 1 it will become a column and the transverse matrix right and two four five six as a row and then it'll be gonna call him so four five six and or three six seven eight nine is a row and it with McCallum and the transpose matrix and now if you observe the transverse matrix and the output matrix right you see that four five six the middle column is same and one two three is the first column and this intermediate matrix the transpose matrix and it is the last column the expected matrix which is rotated matrix and seven eight nine is the last column and the transpose matrix whereas it is the first column and rotated matrix so once you get the transpose matrix what you have to do is you have to just swap the first and the last column so basically we're going to employ you know the reverse approach here they're just going to have a pointer pointing to this column and then we're good to have another point of entry to this last column and basically we're going to just now swap these values and if you observe right all test input matrix and the transpose matrix one let's start I is equal to zero and I will be less than the number of rows which is two and say J is equal to zero and J is less than two and then three it is actually three sorry so zero so initially I is zero and J is 0 right 0 remains the same and if you consider this as 0 1 is 2 0 1 will come to 0 1 will go to 1 0 right let's come to 1 0 so if you see in 0 it remains a sub 0 and then 0 1 come to 1 0 and then 0 2 will go to 2 0 right so which means that the first iteration itself we have transformed the first column right one has come to one and two which was here let's come to here and three which was here has come here right so in the next iteration you should not start from J is equal to zero should actually start from T is equal to your row reverse I because if you start J is equal to 0 then we will be potentially overriding it so next I Tricia you will actually start with 1 and 0 right and 1 and 0 will be replaced with 0 1 so 1 & 0 is now 1 0 is replaced with 0 1 so 1 & 0 is now 1 0 is replaced with 0 1 so 1 & 0 is now 1 0 is what - and now when you replace it with what - and now when you replace it with what - and now when you replace it with 0 1 you're just making it the same matrix a and so we should not override the same matrix again so we should actually start the second do the J is equal to high let's transform the matrix and come back to the next step okay so let's transfer the right race into a transpose but simply say I'm going to have n rows equal to matrix dot the end and calls is equal to matrix of 0 dot length so we are going to do a transpose and true is equal to 0 Rho is less than number of rows and 4 and column is going to be row because when you complete the first row at iteration you have already completed the first row column basically saying that you know when you complete the first row you're ensuring that the first column elements are also in place they should start column is equal to column is less than or false and contrast bus so you have this will be doing a swap mechanism you're saying row and then I think all okay I'm just going to copy this to just save time this row become parliament column will become Rho and transpose matrix is saying to this and it will become hard 10 okay so now we've got the transpose matrix right so we are here now if you see the first episode of your transpose matrix and the output rotated matrix we see that the first row has become the last column so basically what has happened is 0 has become 0 2 and 0 1 and 1 0 this has become so 1 0 is what - and very so 1 0 is what - is what - and very so 1 0 is what - is what - and very so 1 0 is what - right 1 0 is 2 and where is 2 here in the rotated matrix it is at 1 2 ok so basically if observe this pattern row is saying because role is going to be the same right the column is only different so how do we get this column right 0 has become 2 and 0 has become - let's take become 2 and 0 has become - let's take become 2 and 0 has become - let's take another an example let's consider 3 element 3 is all let's consider that element 9 the element 9 is at 2 comma 2 and where is that - the rotation matrix it is at 2 that - the rotation matrix it is at 2 that - the rotation matrix it is at 2 comma 0 right so which means called row is same column is different so when basically how do you get this is number of columns which is 3 here - a number of columns which is 3 here - a number of columns which is 3 here - a current column minus 1 will be this planet because here at current columnist to number of columns is 3 so 3 minus 2 minus 1 isn't going to be 0 and same thing applies here the current column is 0 number of row columns is 3 so 3 minus 0 is 3 minus 1 which is 2 so the part with column is 2 and if you see in any reversal approach you have a pointer pointing to this and you have a pointer to the last one 1 0 swap these to the middle element will be already in place right and even and stringer parish and interesting reversion example also you see that the first and the last will be swapped and by the time you reach the middle they will be already in place so we are just going to I treat over columns and columns by 2 because the middle column will already be in place when we have required values so let's transform this transpose matrix into the expected rotated matrix and rose and o + + + 4 in rotated matrix and rose and o + + + 4 in rotated matrix and rose and o + + + 4 in column equal to 0 and call it's less than and calls all plus so again employ the swap approach you're going to have a temporary variable and just trying to say we may have copied this so this is going to be it tricks and so we saw that matrix o Row is going to be the same there is this is going to be n falls - 4 - 1 so let's put that be n falls - 4 - 1 so let's put that be n falls - 4 - 1 so let's put that value in the target was going to be the same this is going to be and calls - -1 so let's run this code and as I said by the time they reach the middle it will be able to identify so we need no Intel they shall get the transpose matrix and then transform the transpose matrix into the rotated matrix Andros this should end Rose this we have got that it is accepted submit this it takes so much of time okay so if you see it 18 minutes ago I submitted it was due dry mess and now it is wanna miss I have no idea it was the same approach so there is something wrong with a lead code time calculation algorithm because the same approach you know it's 18 minutes back it was saying zero I miss consistently so say yeah that's it nice so this is the answer so basically when you rotate a matrix we're just going to do it transpose of the matrix and then you have to just transform the transpose matrix into a vegetable matrix by just reversing first in the last columns thanks guys I hope you'll like this video bye | Rotate Image | rotate-image | You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000` | null | Array,Math,Matrix | Medium | 2015 |
72 | hello everyone this is mustafa from the code show again with another lead code problem this one is a very popular dynamic programming problem this name is it is a distance the problem statement is that we have like two strings world one and world two and we need to find the minimum number of operation to convert world 1 to war 2 and we have like three operations only we can do on the world one to convert it to war two these operations are insert character and delete character and a replace character uh here we have like horse and we have rows and we have like uh the minimum number of operations to convert was into ros is only three operations okay so we first thing we will replace h with r others that we will remove the r from horse and then we remove the e from ours okay so let's try to uh take a closer look on this example and let's assume we have like two pointers first pointer on the first word another pointer also on the first character of the second word so here you have like simple example uh we have our pointers this one position one and position two we have like the operation we already did and the first thing we would like replace h with r and we have like r o and our the first pointer now is pointing on o second pointer is pointing in o also so we don't need to um to do any operation because the two characters are the same so we will only increment the position one and position two so we have like uh here we have like r and we have also here s okay so we will delete this r and increment the pointer here that point points to s right now after that we have like 2s here um we don't need to do anything we will just increment the host pointers if we can so here we incremented this and we have like e and s so we will delete the e also and we have like three operations because we did delete we did a decision here also another deletion and we did replacement here to replace arms uh to replace h1 and that's it how we can code these steps into an algorithm so here as we usually do we as usually do with the dynamic programming problems we do a backtracking we can start to solve uh create a solve function that would be our backtracking function or our recursive function so let's try with it so okay it will take two argument position number one and position number two okay and let's try now think about our base case when we will stop doing this location over and over again i would say we need to stop if any of this of those pointers uh become uh like hit the end of its port like here we hit the end of the second word and here we have this at the end of the first one so whenever we if we have any of this position reached the end of its world that will be like um a base case or we need to stop doing the recursion so here let's try to do in this case position one is larger or equal to the world one and another base case if position two this merger world 2 and yeah so if you repeat against example we had two s's here yeah and at the end we need to make that two strings equal so we need to delete the remaining part of the first word actually and each character will represent attribute operation so our base case would be the following if we reach it the end of the first word we will return the difference between the second word and its current position and the same also for the second one okay so here we need to do something like this we return word to minus its current position and we need to do same thing here then word one minus its composition and that should be it uh now let's try to think about our recursive case so um we have like two recursive cases as we see here an example first one if the characters are equal okay we will need only to increment if they are not equal we will need to try we need to try to do an operation on the string okay so if word one of position one not equal or two of position 2. what we will need to do is we need to solve or try to solve with the replace operation so how we can represent the brace operation is by incrementing the position the two positions of that walls okay so this is the position one and this is position two plus one and here we have uh the operation we did we need to increment the operation counters this one and also we need to try to solve with the insertion operation so the insertion operation will be represented as yeah the insertion operation will be represented as we need to only increment the first position okay and we need to try from the same position on the second word and we also increment the operation counter the last operation is the delete operation and we will need to try to solve from the current position we are at in our first world and we need to increment the position 2 for the second word also we need to increment the operation counter and at the end we need to use mass to find them which uh which will return us the minimum operation we need to use we need to return here so this is the first point if the word if the if this character are not equal the character from the second word if this if statement is not correct we will need to solve only from the next position so position one plus one and position two plus two we need to return it and that's it we need to return so we need to fall from zero and zero so that is the recursion part or the backtracking part so actually i think we can try it now yeah it works fine now we need to add the memorization part let's try to make a 2d array that would cache the two parameters here so here we have like a for memo be quite new array and the reliance would be like word one prince one and we need to fill this array with uh another areas uh with the length of wall two okay so uh let's do it so we need to for loop we have like four i counter equal 0 and i is the then minimum i need to increment i now we need to fill every array every position sorry was -1 every position sorry was -1 every position sorry was -1 so we need to use this inside our back tracking part so first thing we need to check if the memo of the current position in position 2 also is not equal minus one we need to return its value okay so also here we need to write into the array and also we need to right here in the array and at the end yeah so we said the value will ethernet we also set the value and we return it here and uh yeah if we found the value of it we will return it so let's try to run this now we have like a title this is a strange word also another type yeah it could be like this it seems that we don't return at some point yeah we have like a type of another type of here yeah there's a typo i think we forget to add i here it works fine let's submit it work is fine thanks for watching thank you | Edit Distance | edit-distance | Given two strings `word1` and `word2`, return _the minimum number of operations required to convert `word1` to `word2`_.
You have the following three operations permitted on a word:
* Insert a character
* Delete a character
* Replace a character
**Example 1:**
**Input:** word1 = "horse ", word2 = "ros "
**Output:** 3
**Explanation:**
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
**Example 2:**
**Input:** word1 = "intention ", word2 = "execution "
**Output:** 5
**Explanation:**
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
**Constraints:**
* `0 <= word1.length, word2.length <= 500`
* `word1` and `word2` consist of lowercase English letters. | null | String,Dynamic Programming | Hard | 161,583,712,1105,2311 |
1,800 | Hello friends, welcome, this is youtube1 linker challenge, the challenge is going very well, let's go straight to our screen and start, so here I am on the screen, the number of our question today is 1800. And the name of the question is 'Maximum Ascending Sub Array'. name of the question is 'Maximum Ascending Sub Array'. name of the question is 'Maximum Ascending Sub Array'. Okay, 'Maximum Ascending Sub Array'. Now let's Okay, 'Maximum Ascending Sub Array'. Now let's Okay, 'Maximum Ascending Sub Array'. Now let's understand a little bit what is a sub array. It has also been written here that what is 'Sub Array'? A sub array is defined as a what is 'Sub Array'? A sub array is defined as a what is 'Sub Array'? A sub array is defined as a continuous sequence of a number. These arrays are fine, any continuous part of the array, we call it a sub array. Now what we have to find is that if the question is defining the whole in its name, what is doing is that the maximum ascending sub, we should have the sum, okay. What is the maximum? We have to find out the ascending sub-ascending We have to find out the ascending sub-ascending We have to find out the ascending sub-ascending part of the array, like if I talk about this example, in the first example, 10 20 30 5 10 50, then in this, two of my counts, ascending sub- 30 5 10 50, then in this, two of my counts, ascending sub- 30 5 10 50, then in this, two of my counts, ascending sub- array, which one can I see? One, I can see this. It is visible that these two are the biggest, however, this is also a sub continuous, this is also continuous, but the maximum, the more digits there are in it, the greater will be the maximum. Okay, in this we might have also given that all If we see positive numbers, then it is okay, then all the numbers are giving us positive also. With this thing, it has become very easy to understand all the things. If the numbers are positive, then the questions should become easier for us. Okay, now I can see this. If I look at the sum of this part, what will come is 10 p 20 30 p 30 60 6 and if I look at the sum of this array then 10 p 5 15 p 50 sorry this is 50 ok 50 so here What is coming is our 65 aha so which is bigger between 60 and 65 what is it ok to return me the answer so we have to find the maximum if I talk about this array the elements in this array are my 10 20 30 40 and 50 so What is this entire array? A ascending order. So the total sum of it will be our answer. Let's see how 10 + 20 30 our answer. Let's see how 10 + 20 30 our answer. Let's see how 10 + 20 30 + 30 60 + 40 100 + 50 150 + 30 60 + 40 100 + 50 150 + 30 60 + 40 100 + 50 150 So this entire array is an ascending order. What is there, we have an array, so the whole of it will be even, that will be our answer. If I talk about this part, then what is there in it? 12 17 15 after 13 after 10 11 If I look in it First of all, I see this, but no one is becoming all, even I myself am not becoming all, with anyone else and this we have one all, one we have all this if If I look carefully, the one which will have the most numbers is ours. First of all, it will be the maximum. Now, what is becoming the sum of this whole and what is our 33, then 33, which is our sum, is the same. If we return it then it is the maximum. We have to remove the saber, okay, maximum saber and elements, so how will we remove it is a very easy question, there is no very difficult question, it is a very easy approach, due to this, we have come directly here on the screen, now first of all I take a saw. From Let's I have taken this one or this one's array, we will increase one or two elements in it so that it becomes easier for us, 10 20 and 30, after that, from Let's 5 10 50, we have taken one more element, here P0 is ok, we have given this I increased the elements a little so that we can understand the approach better. Okay, so we write its indices. First of all, zero, four, f and si. Now look at one more thing in this, note that sub-array of size one is note that sub-array of size one is note that sub-array of size one is ascending if size one. If there is a subray then that is also ascending. Okay, so this thing we know that size one means atlist one element has to be returned. Okay, so first of all we will create two variables, why will we create them in front of you? First I made current sum which will be current sum and one is our answer maximum sum no in both initially what will I do store our first 10 this because at least one element of atlist is making even and I will check from here I will start checking here, I will keep my pointer here, okay, I have placed the index here, now what should I check, I want ascending sub-array, if I want ascending sub-array, if I want ascending sub-array, if I want ascending sub, if the previous element is smaller than the current element, the previous element is smaller than the maximum then whenever. I have to have one previous element smaller then I have to add that number to the current sum. So now let's see if it is making it so, what did I do? I did 10 x 20. Now I reached this index. I added the previous element. What is the previous element? He is small, he is checking because he is in an ascending fear. Meaning of being small is small. Yes brother, he is small. He said yes, he is small, so 30 p. What happened? Now I reached here he checked the index behind and removed it. Now let me check the one behind is the bigger one, so it means here my ascending order is broken. My ascending order is broken, which means now a new subre will start from here. Okay, the previous subre is finished, so whenever I have such What will I do if something happens, I will look at my sum, what is the sum which I had now, which is bigger than the previous sum, if it is bigger, then update 60 updates, now I have further updated from here, what should I put in the current sum, the same element which I had talked to Sabre because he could become a part of the next Sabre. Maybe I will get a bigger element in the future. Now he came to Aa and asked if the previous element is smaller than what he is doing now. If so, what should I do? Just one. Do plus in this P What happened now I again Again asked whether 40 is smaller than 40, is 40 bigger than 50, if it was not so then what would we have done? We would have compared both of them, the previous sum which had come out till now, we had the same sum in the current sum of the previous one. It is not bigger than the maximum. It is 65. So after 65 I will update the answer. 40 Now it could have been that there would have been a bigger element here. What would have happened here would have been a bigger element. Let's mean here 40. If instead of there is some big element which is bigger than the sum, then we will have to check once after the loop that the current sum is not bigger than our max sum, so we will check that thing in the last, okay now when If we code then you will understand better, so let's code directly on the screen, that's enough, so first of all I took the max element, which was our current max, which was our answer max, in it I put the number of zero, I put zero element, then I Current max li current me in that also num of zero the first element is fine and I have run the loop from k to k run from i iv to this lesson nam last I have to go to nums dot length and opps ps y thing what should I check now? I have e if my names of a my means if the previous element is smaller than what names of a if it is smaller then it means now it is a part of the sub array, it is a part of whatever sub array is running then I will sort it current max current Max plus current max plus numbers of a aa only we have to do plus why do we have to do it because we have already done plus in the numbers of aa my means we have already added zeros in case of n also ok so I have added it else if not so So first I have to check the current math which was given in the previous section to see if it is big then what will I check for it. In maths, the one among us who will have the maximum value is math dot max of max comma current sorry current. Now put Max Current Max, what should I put in Current Max? The Current Max will be starting a new collaboration, so I will put Nums of I in it, I will also put Nums of I, then my work will be done in this way, but this code is complete right now. No, why not because it is possible that after the loop ends in Current Max, the last condition of Current Max comes here and the last element of Current Max is not updated yet, so I have to write this line once outside the loop as well. So that the value of the last element of the current mix is big, if the current is higher then we will have to do more up and return because we feel that everything is right by running it and seeing that everything is working fine by submitting it and seeing that it has been submitted. While doing this, we will try to understand each case, so I have brought my array to Y and will make it a little bigger, now I take one of our A from late, I took 10 20 30 and 40 50 sorry don't take 40 from taking your ascending fear. If it doesn't happen, here we took 10 15 and 18. Okay, I wrote y so that I can explain the last one to you. Once I write that down, we have our index 0 1 2 3 4 and f. Okay, now first of all we took the current max. What value did we put in current max? What value did we put in zero and max also? What value did we put? Off G 10. We have put this. Now I have started ours. Start it from here. Come, the value is here. The value of i on one index. My one index. Now I checked whether the previous element is smaller than me. The element P is smaller than me. Being small means the current max mend to me is 10 P 20 30. Now I again moved ahead. After checking again, is 30 smaller, it asked, yes, so going into it, Ra came to the current mess, 60, now it came here, I asked, are you smaller than me, there is no previous element, if not, then it will go to else. After going in, the first thing that will be checked is Max, the value of Max was 10, mine is 16, which of the two is bigger, the one who is bigger will come in it, come in Max, come in my 60, what will be the current after coming in 60, come in Max, come in What will come in Max? What is the number of Aa? If possible then let's see what happened now, what will happen now is that now first of all what will grow next is our aa moved forward aa forward b aa after moving forward asked what aa the index on which he stood asks the previous index are you younger than me yes If it is small then what to do is just go to the current max and add it 10 + 50 60 go to the current max and add it 10 + 50 60 go to the current max and add it 10 + 50 60 Okay now come again go ahead and ask the previous index What did you ask from the previous index that you are smaller than me Yes I am so 80 + 60 140 Gone 80 + 60, how much is 140, + 60 140 Gone 80 + 60, how much is 140, + 60 140 Gone 80 + 60, how much is 140, now look, our loop has ended, now what happened after our loop ended, this loop has ended, current max, so in current max, maximum is still read, maximum is all read, max is not updated. We found that this is why the last condition in max was 60 comma 140 so 140 and which is the maximum out of 60 140 so what came in max is 140 so that's why the answer here is 140 and this is our sabre which is math. I hope you have understood very well how we have solved this question. Okay, let's meet tomorrow where we will be solving the next question. Hope so you have liked the video. If you like the video then watch the video. Like it and subscribe the channel. If you have any doubt then you can contact us. | Maximum Ascending Subarray Sum | concatenation-of-consecutive-binary-numbers | Given an array of positive integers `nums`, return the _maximum possible sum of an **ascending** subarray in_ `nums`.
A subarray is defined as a contiguous sequence of numbers in an array.
A subarray `[numsl, numsl+1, ..., numsr-1, numsr]` is **ascending** if for all `i` where `l <= i < r`, `numsi < numsi+1`. Note that a subarray of size `1` is **ascending**.
**Example 1:**
**Input:** nums = \[10,20,30,5,10,50\]
**Output:** 65
**Explanation:** \[5,10,50\] is the ascending subarray with the maximum sum of 65.
**Example 2:**
**Input:** nums = \[10,20,30,40,50\]
**Output:** 150
**Explanation:** \[10,20,30,40,50\] is the ascending subarray with the maximum sum of 150.
**Example 3:**
**Input:** nums = \[12,17,15,13,10,11,12\]
**Output:** 33
**Explanation:** \[10,11,12\] is the ascending subarray with the maximum sum of 33.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100` | Express the nth number value in a recursion formula and think about how we can do a fast evaluation. | Math,Bit Manipulation,Simulation | Medium | null |
802 | hey everyone today we are going to solve the little question find the eventual safe States so there is a directed graph of nodes with each node leveraged from 0 to n minus 1. the graph is represented by a zero index to the integer array graph where graph I is integer array of nodes are adjacent to node I meaning these are H from node I to each node in graph I a node is terminal node if there are no outgoing edges a node is a safe node if every possible path starting from that node these two terminal node or another safe node return array containing all the safe nodes of graph the answer should be sorted in ascending order okay so let me explain with this example zero one two three four five six nodes and then each node has this pass so for example node 0 has 2 paths to node one and the two in order two and another one has also two nodes two paths and two node two and a two node three and they're basically we iterates through all nodes one by one and as simultaneously um we keep track of like a current status for each node so there are three status so zero is a bit DT node and the one is a visiting node now and that two is a like a terminal node so that means if we reach the timer which is 2 so that node is one of answers so let's begin so first of all we start from node zero and uh so tick node 0 here so now I'm visited so that's why um up to date node so zero to now visiting right so that's why one and then uh check adjacent node and which means one two so like this one and two and uh okay so let's go to node one so node one is um not unvisited in order yeah I right so that's why updated like a visiting so one and then uh check other Json node and two and three so let's move on to another two so node two is also unvisited um node right so that's why in our visiting so output database one and then node 2 has only one pass to node five like this so let's move on to node 5. so node 5 is unvisited model right so that's why update to one and take like adjacent node but as there is no out going pass so that means um this is a one of a terminal nodes right so that's why in this case update um this status to two and then I'll return to so this us is looks good okay so let's go back from node 5 to 2 and then in order to is uh definitely um one of a safe nodes right uh because uh there is only one pass and to another five and the Note 5 is terminal node so that's why update um status of node 2. to like a two so that means if we reach the node two so we can reach the like a terminal node that means five so that's why uh almost uh it's same as like a node two is a like a terminal node so that's why update the status of node 2. and then um so there's no only one pass so let's move back to one but one has another pass to normalcy right so let's take to this bus so now we visiting the no Z so that's why I play the status to one visiting and then all the three has only one pass to node zero so like this and so let's move on to another zero but um here is the important thing so we start from another zero right so that's why no status of node 0 is now visiting so it's kind of uh like a circle so in that case so that means uh we can't say um node 0 is um safe node so definitely another is not answer because there is a circle and also um so in the circle um so there are a few nodes like a node one and a node three right like this zero one three zero so that's why node zero and then all the one and then over three is definitely um not safe node so this is not answer yeah um that's why um so far we should know the two to like an answer variable so is that variable so two and then um so we know that node one is not safe no C is not safe and node 2 is a safe node and uh how about a four so now we are visiting four so up to date status of node four to one and there is only one pass no to notify so we know that node 5 is a terminal node so that's why um node 4 is also safe node so that's why um as a notable to these are the variable and then so now we are notify but there's no pass right so that's why move back to four in the case um update the status of node 222 so that means again it really is the number four that means that is a um like a Safeway safe node and then um let's start from node five so node 5 itself is and there is no pass right so that's why node 5 is a random answers right so that's why add five and then move next and then how about six so now visiting six so update status to one and then there's a there's no pass so that's why six is also terminal node so that's why R6 to answer variable and then update status to two and then there's no um status uh pass and there's no node here so that's why we finish iteration and then in the end we create like a two four five six so that's why in this case output is like this yeah so that is a basic idea to solve discussion without being said let's get into the code okay so let's write Circle first of all um calculate the ranks of graph so graph and visit it kind of Interest with zero multiply and so zero is um visited and the one is visiting and the 2 is I got time you know and then result variable with empty list and so basically we did it through all nodes one by one so for pi in range and a node length of node and if let's say is safe and current mode if this function be done through so append the dot null to result variable so result dot append and I and then after that return result variable so let's create a is fun easy save function So Def is safe and a node in the first of all check the visited list if visit it and the null is greater than zero so that means we already visit that node and then later visit it node equal to so if that node is a terminal node so we should return true if like a visiting um return false and then if not the case that means current node is unvisited so now we are like visiting that node so update the visited node equal one and check neighbor in graph in the node and if not is safe bar in the case we should be down pause if not the case that means current node is terminal so visited BC did node equal to and then return yeah I think that's it so rain is updated let's get in a very efficient algorithm so time complexity of this solution should be order of V plus e so V is the number of nodes and vertices in the graph and the E is the number of edges in the graph so this solution called performs like this first search and starting from each node and the based in each node and the edge once so in the last case all nodes and the edges are visited so result in the time complexity of Mega order of V plus e space complexity is order of V so V is the number of nodes and the vertices in the graph so the space complexity is determined by the like a visited list which was a visitation status of each node so in the worst case the visited list will store the status of all nodes so resulting in space complexity of order of V yeah so that's all I have for you today if you like it please subscribe this channel hit the like button or leave a comment I'll see you in the next question | Find Eventual Safe States | k-th-smallest-prime-fraction | There is a directed graph of `n` nodes with each node labeled from `0` to `n - 1`. The graph is represented by a **0-indexed** 2D integer array `graph` where `graph[i]` is an integer array of nodes adjacent to node `i`, meaning there is an edge from node `i` to each node in `graph[i]`.
A node is a **terminal node** if there are no outgoing edges. A node is a **safe node** if every possible path starting from that node leads to a **terminal node** (or another safe node).
Return _an array containing all the **safe nodes** of the graph_. The answer should be sorted in **ascending** order.
**Example 1:**
**Input:** graph = \[\[1,2\],\[2,3\],\[5\],\[0\],\[5\],\[\],\[\]\]
**Output:** \[2,4,5,6\]
**Explanation:** The given graph is shown above.
Nodes 5 and 6 are terminal nodes as there are no outgoing edges from either of them.
Every path starting at nodes 2, 4, 5, and 6 all lead to either node 5 or 6.
**Example 2:**
**Input:** graph = \[\[1,2,3,4\],\[1,2\],\[3,4\],\[0,4\],\[\]\]
**Output:** \[4\]
**Explanation:**
Only node 4 is a terminal node, and every path starting at node 4 leads to node 4.
**Constraints:**
* `n == graph.length`
* `1 <= n <= 104`
* `0 <= graph[i].length <= n`
* `0 <= graph[i][j] <= n - 1`
* `graph[i]` is sorted in a strictly increasing order.
* The graph may contain self-loops.
* The number of edges in the graph will be in the range `[1, 4 * 104]`. | null | Array,Binary Search,Heap (Priority Queue) | Hard | 378,668,719 |
863 | okay so uh need code practice time so in this video there are two goals the first goal is to see how to solve this problem and then we are going to do some coding work and the second goal is to see how we should behave in a real interview so let's get started so remember the first step in the real interview is to always try to understand the problem if there is anything unclear please bring up the question and at the same time think about some ash cases so let's take a look at this question so all the nodes distance k in the binary tree so we are given a binary tree a target node and an integer value k so we want to return a list of the values of arnolds that have a distance k from the target node so the answer can be returned in any other so let's see example as root so this is the root which is which represents a tree something like this and the target is equal to 5 and k is equal to 2 so the output is going to be 7 4 1 because the nodes with distance as 2 from 5 is uh 7 4 and 1. okay that makes sense so let's see some constraints so the given tree is not empty so it's not an empty tree and each node in the tree has a unique value between 0 to 500 so the target node is the node in the tree okay and the k is between zero to one thousand so first of all we know that the tree is not empty and it's for sure that the target is one of the notes within the tree uh but we don't know whether the kai uh is actually valid or not because if it is because if there's no um no nose within the root within the tree that has distance of k from this target then we are going to return empty but i think that should be covered uh by a by the general algorithm so let's see how to solve this problem so the next part about finding solutions so this part is mostly about you communicate with your interior and words or draw something whatever so use any technique any way to explain how you're going to solve this problem and do some run time space analysis so let's see for this i will say first of all we need to at least find the node from the tree and then to find the distance from k it makes me feel for to find all the nodes with distance k from this node it makes me feel like it is a bfs function it's a bfs problem but the thing um it's very it's a little bit different from the regular bfs it's because except for the children knows we also need to find the we also need to extend to its parent node so for example for this um node 5 the first layer we are going to try to extend include the left child the red child and this parent and for the second layer um we are going to extend the children's and the corresponding parent so since this note doesn't have a parent you're just going to expand to its uh it's right child so i would say first of all um you could use either bfs or uh i think we should it should we could either use bfs or dfs to find the parent relationship uh for each node for example we find the parent of five as three we find the parent of six as five so and so forth so first of all we need to run either bfs or dfs to find the parent relationship and add it into a separate map and uh the next thing we will do a bfs to extend from the target node layer by layer to try to find uh all the nodes that has distance k from the current target node so having said that the runtime is going to be 11 because we just need to almost look at all the nodes within the tree twice and uh so runtime is all events space wise it's also olefin because we need to record the parent relationship uh and potentially we also need to record uh what which notes has been visited in our bfs uh part b or bfs part so having said that uh let's do some coding work so in the coding part we care about the correctness of the code the readability of the code and also the correctness of the code so uh let's take a look so it's not an empty tree and target is for sure uh to exist in this for sure to exist in the tree so first of all let's define a helper function call it bfs dfs so the dfs is going to have you're going to have two things the first one is the node and the second one is the parent all right so we are going to first of all define a map with tree node shino so the sec the first one is the node and the second one is his parent per node so i will say parents know the parents the new hash map all right then we will run the advanced dfs on top of it so it will be root and then none pointer uh and i actually at the same time you need to pass in the know the parent which is a map into it this is not parent so now apparent all right so um if node is equal to none uh if node is equal to none they just need to return and otherwise so otherwise we will need to have node parent dot added let's put the put node and the parent then we are going to say dfs on top of no node.left and paren sorry node no node.left and paren sorry node no node.left and paren sorry node and dfs no dot right dot node so yeah so that's it and also we may not really want to have the pair which is the root and the nun pointer put into it so i will just put a if parent is not equal to a num pointer then we are just going to put the node and parent into it yeah so that's it for the dfs part to have the parent node yes um and then the next part is about um bfs so for bfs we essentially need to have a queue of the tree node so the tree node uh let's say so q use linked list as the underlying implementation so first of all you put it's add you add the target node into it so well q is not empty then we are going to keep continue so in this case we actually need to keep track of one is the distance starting with k and the other one i would need to keep track of is the because we need for example for 5 the first layer is 6 two and three um we don't really want to visit five again because we have we don't really want to visit the nodes we have already visited again uh so we need to have pretty much have a set of the notes let's call it visited as new hash set so first of all we will have inch size as the cutout size and then you're going to say i 0 is smaller in size and plus i so if uh so first of all we need to put pop the thing so tree node the node as equal to q dot pop okay it's full all right so yeah we actually need to define the thing we are going to return finally so let's define the list of the integers um this is nose with distance okay new that's a linked list so if um so if the distance is equal to k then we need to have nodes with distance k is dot adder uh dot add uh it will be dot at the node. value okay and then um for how to extend it so we would need to make sure that so if node dot lot is not equal to a none then so if node the left is not equal to then you're going to add it into the queue but first of all we need to make sure that the node doesn't exist so if um visited dot has dots contains if visit doesn't contain node.left node.left node.left then we are going to have visited the no doubt left and we are going to add the q uh no that left all right so this is the left branch and uh the next thing is about right branch right is not equal to a none then if um uh not visited so actually uh we could define another helper function let's say void uh add a let's stop calling add a node to a q so essentially we have several different things the first thing is the tree node to be added and the second one is a q and the third one is the visited so the thing is if the node is equal to a none then we just return and if visited dot contains the node then we are going to return and if the node is not none we haven't visited then we are going to have q dot add the node so you could use this helper function actually to have node.left to have node.left to have node.left and the queue and visit it so similarly we have a node to queue snow dots right q and visited and similarly we will have the root dot okay so it's no i know to kill i will say if the if know the parent dot intense key which is the note then we will call the add the note queue uh node parent dot get or maybe you just call it get or default uh so this is the node and the non-pointer non-pointer non-pointer all right so if the parent is not none and it's not in the visited and you're going to add a parent into it so yeah i think that's pretty much it about how to extend this layer and about how to add the node and finally uh you're just going to return um what is that we're going to return node where's distance good all right so uh having said that um i think we are mostly co-complete uh but i think we are mostly co-complete uh but i think we are mostly co-complete uh but i think there is a bug here actually we should plus the distance here um because we just finished uh visited one layer which we need to plus the distance and um after we plus the distance if the distance is larger than if it is larger than k they pretty much just need to break this while loop here so um after you're done with code we are done with coding it's not done uh with the interview we need to do some testing so the way we do testing is first of all we do some sanity check by going through our example to see how it is going to work at the same time we are going to explain how this piece of code is going to work to the interviewer and after that we will introduce some different task cases to make sure we have good enough test coverage about different branches in the code so let's see let's take the exact as an example we find the target as 5 ks distance s2 within the tree so first of all we have the node parent thing and we have a dfs on top of it and uh if parent is not equal to none then we just put the node and parent relationship or and if node is equal to a none then you just simply return so first of all you're going to put you're not going to put anything when it's true because we call the root none then we go to the left and right child uh yeah so i think similarly we could and then we are going to deeper and deeper as we do that we keep adding the parallel relationship into uh the node parent map so i think after that we should be mostly good about it and uh after that after the dfs it's the bfs part so we have the q we have the distance we have the visited so while the queue is not empty so first of all you have the size of the queue which is the number of the nodes at this layer so we are going to say okay node is equal to none sorry node equals to the for we are going to pull the node from the queue and if the distance is equal to k then you're going to put it into it so first of all we pull the 5 from it which is the first layer um and currently distance is equal to 0 which is not equal to k so we are going to add the left right hand parent into it so when we try to add we need to actually i didn't update the visited so you should have the wizard dot add the node when we try to add node to the queue so um so okay so we update the visited yeah and we also update the queue so currently we have the queue that has three nodes in it the plus what's the distance because this layer is finished and next time uh next time when we step into the while loop again so the distance is one and then uh we are going to try to extend the this node this we first of all we try to extend six so six we see that the left child both left and right are none then we are not going to add into the queue and we see that the node file is already visited so we are not going to add into the queue so for two similarly we are going to add seven four but we are not going to add five into it for three we are not going to add five and we are not going to add its parent because the parent is a 9 pointer and also we are going to add the 1 into it and we are going to plus the distance not distance is equal to 2. so the next time we have three seven four and one in the queue we add the values and these ten after you extend the distance is larger than two so you're going to simply break so i think mostly it should work uh from what i can see let's give it a shot by run this piece of code all right so what uh what is this it's node oh okay so i think i should some typo here you should also pass no parent into it okay so it's wrong answer let's see why it is wrong so we got set five seven four and one into it but uh should we do it so i think the thing is we didn't add let me try to add the first stuff into the visited then we didn't actually update the visited with the first node this is essentially where the bug is so i think this should fix the book so visited oh so we have we should define it here uh should add a queue while we update the visited yep so this should fix a bug let's give it a submission all right so now everything looks good um so regarding the test case setup i would say um i think the having this task case is pretty good enough but if you want to keep some other test cases for example when k 0 or when k is larger than 1 k 1k setup as a value that we will return nothing from the tree uh so that should be that would be great but uh if you just set up this example i would say that's perfectly fine so that's it for uh this coding question if you have any questions about the puzzle or about the solution feel free to leave some comments below and if you like this video please give me a thumb up and i'll see you next time thanks for watching | All Nodes Distance K in Binary Tree | sum-of-distances-in-tree | Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._
You can return the answer in **any order**.
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2
**Output:** \[7,4,1\]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
**Example 2:**
**Input:** root = \[1\], target = 1, k = 3
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 500]`.
* `0 <= Node.val <= 500`
* All the values `Node.val` are **unique**.
* `target` is the value of one of the nodes in the tree.
* `0 <= k <= 1000` | null | Dynamic Programming,Tree,Depth-First Search,Graph | Hard | 1021,2175 |
1,774 | hello everyone let's take a look at this new core problem it's a um the second problem in the weekly context although it's the second problem but i think it's a little bit hard since it's kind of like a knapsack problem so it's a dp problem also you can solve it unlike by dfs and since the constraint is not set strict okay let's take a look at like how to solve this problem if you haven't used the problem you can take some time to read the description is quite long so we need to create like ice cream so some um this flavor and we have to choose exactly one piece flavor and there are some toppings and we can choose any toppings and for each topping there are at most two like so for example like for chocolate we can only choose two chocolate toppings but we can choose any types of tokens so given target asks us to compute a cost which is the closest to the target okay let's take a look at this example so we can choose this flavor 7 and choose one top in 3 so we have cos 10 which is closer to target and let's take a look at like how to use dp to solve this problem so we have a dimensional dp array it's boolean array to indicate that if i have um cos 11 or if i have cost 12 at first the default value is force first we can just follow on the base costs and set value to true so we have one and seven so one seven is true since uh for example i can choose base seven and i don't need to choose any toppings so seven is okay next i can use um the first topping three so four and ten is two since ten can come from seven four can come from one next i can use second topic 3. so 13 is true since 13 can come from 10. so for each topping we can just follow my array and for each value i can just if it can come from previous number for example 3. i need to check if 13 is true or not so count top on top is 3 so i need to check and table 13 minus 3 which is table 10 is 2 so table 13 is true okay next we can use topping four so 17 is true since 17 can come from 13 14 is true which comes from 10 11 is true which comes from seven eight is true which comes from four five is true which comes from one okay next we can do second typing form but i didn't draw here since we already figured out how to solve it so this is implementation let's take a look at constraint so the base cost is between one to like ten thousand so we can choose a base cost and target is also between one to one thousand so to only choose one base cost and for targets we know the diff is smaller than one thousand so for my table i can just use a constant number like twenty thousand since we don't need to calculate thirty thousand forty thousand since we already know as long as i choose any base cost so optimal div is like the div is already smaller than one thousand so ten thousand okay so i just for loop base cost and set the table base to true then we just for loop each topping and for each topping we can use at most twice so there's also enough for loop here then i just track each value to see if they can come from a perfect previous value if it can comes off come from previous value then table current value is true then i just check my table and depicts the best number finally just returns this number so it's a very typical um db problem and it com it's in the second problem in the weekly contest uh since the constraint is not that um bad since an amnes and smaller or equal center there are some other solutions okay listen thanks | Closest Dessert Cost | add-two-polynomials-represented-as-linked-lists | You would like to make dessert and are preparing to buy the ingredients. You have `n` ice cream base flavors and `m` types of toppings to choose from. You must follow these rules when making your dessert:
* There must be **exactly one** ice cream base.
* You can add **one or more** types of topping or have no toppings at all.
* There are **at most two** of **each type** of topping.
You are given three inputs:
* `baseCosts`, an integer array of length `n`, where each `baseCosts[i]` represents the price of the `ith` ice cream base flavor.
* `toppingCosts`, an integer array of length `m`, where each `toppingCosts[i]` is the price of **one** of the `ith` topping.
* `target`, an integer representing your target price for dessert.
You want to make a dessert with a total cost as close to `target` as possible.
Return _the closest possible cost of the dessert to_ `target`. If there are multiple, return _the **lower** one._
**Example 1:**
**Input:** baseCosts = \[1,7\], toppingCosts = \[3,4\], target = 10
**Output:** 10
**Explanation:** Consider the following combination (all 0-indexed):
- Choose base 1: cost 7
- Take 1 of topping 0: cost 1 x 3 = 3
- Take 0 of topping 1: cost 0 x 4 = 0
Total: 7 + 3 + 0 = 10.
**Example 2:**
**Input:** baseCosts = \[2,3\], toppingCosts = \[4,5,100\], target = 18
**Output:** 17
**Explanation:** Consider the following combination (all 0-indexed):
- Choose base 1: cost 3
- Take 1 of topping 0: cost 1 x 4 = 4
- Take 2 of topping 1: cost 2 x 5 = 10
- Take 0 of topping 2: cost 0 x 100 = 0
Total: 3 + 4 + 10 + 0 = 17. You cannot make a dessert with a total cost of 18.
**Example 3:**
**Input:** baseCosts = \[3,10\], toppingCosts = \[2,5\], target = 9
**Output:** 8
**Explanation:** It is possible to make desserts with cost 8 and 10. Return 8 as it is the lower cost.
**Constraints:**
* `n == baseCosts.length`
* `m == toppingCosts.length`
* `1 <= n, m <= 10`
* `1 <= baseCosts[i], toppingCosts[i] <= 104`
* `1 <= target <= 104` | Process both linked lists at the same time If the current power of the two heads is equal, add this power with the sum of the coefficients to the answer list. If one head has a larger power, add this power to the answer list and move only this head. | Linked List,Math,Two Pointers | Medium | 2,21,445 |
19 | this is one of the frequently Asked question in interviews like Google mang Facebook companies and the question is like remove and node from each of the list means you have to remove the specific node you will be giving a head of that linked list and removing which node you have to remove so here I have given a link links and I have given n is equal to 2 so basically 0 1 2 so this from here I have to cut down and I have to link this to five and here's the code for this you can pause the video and get the code and do subscribe to code for placement we will be making more such videos and in near future so do subscribe our Channel and be with us here you can see the Beats is hundred percent and within 0 Ms so this is the code guys do subscribe | Remove Nth Node From End of List | remove-nth-node-from-end-of-list | Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], n = 2
**Output:** \[1,2,3,5\]
**Example 2:**
**Input:** head = \[1\], n = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[1,2\], n = 1
**Output:** \[1\]
**Constraints:**
* The number of nodes in the list is `sz`.
* `1 <= sz <= 30`
* `0 <= Node.val <= 100`
* `1 <= n <= sz`
**Follow up:** Could you do this in one pass? | Maintain two pointers and update one with a delay of n steps. | Linked List,Two Pointers | Medium | 528,1618,2216 |
523 | hello friends today nests of continuous sub Arisa will give a list of non-negative numbers and their target non-negative numbers and their target non-negative numbers and their target integer K we need to write a function to check if the array has a continuous sub array of size illicit you there are some sub your multiple of K actually this problem is a classic sub arrays on problem we can use an idea of prefix sub the reason is that it's very easy to catch the sum between index 0 to index I is the index of the you know the rest of the on other words other index in the array so it can be 0 1 0 2 so on so forth it's very easy because we can get that sum by iterate from left to right and we accumulate as a Sun but folder index from like fronds 3 to 5 it can be harder but we can use the same idea to get as a sample in this sub array we can use index 0 to index 5 - index 0 to use index 0 to index 5 - index 0 to use index 0 to index 5 - index 0 to index 2 is that correct we can use the subtraction to get the sum of the continuous sub array so not a starter from the index 0 so in this question we can also use this idea let's see we have some one some two which are both start from index 0 and if they're subtraction mojo k equal to zero that means this sub-array is the multiple of K right sub-array is the multiple of K right sub-array is the multiple of K right so we then we can get someone mojo okay you go through some to module K so that means we can just do a normal iteration from left to right and we get the accumulated or some and if the K is not equal to zero we use the same module K and if this thing we already seemed before that means we find a sub array that's some equal to the multiple of K the last thing we needed to check it whether the size is great or you couldn't - so the algorithm ate it couldn't - so the algorithm ate it couldn't - so the algorithm ate it but there is some minor details we needed to take care one thing is how about if the someone is the whole array and actually the sum to is does not exist so that's the reason we should take care of the special case 0 because when is someone is a whole array the sum to actually is 0 like if this array is sum equal to 6 and 6 is multiple of 6 we need like you have the sum - so we need like you have the sum - so we need like you have the sum - so we need use the 6 - 0 and we know there's use the 6 - 0 and we know there's use the 6 - 0 and we know there's multiple 6 and how to check whether this is some module K we have seen before we can use a hash set or hash map but we also need to check whether the size is great or equation - so we need the that great or equation - so we need the that great or equation - so we need the that is the way is to use the index so we can use the current index minus the previous index so in the end we will use a hash map and the key is the some mojo K and the value is the index in that case for the 0 we should at first I put as a 0 minus 1 because in this case the current the index is 3 and a 3 minus negative 1 we care for just exactly the size of this someone write exactly the size of the separate is 4 okay so now let's write the code we will use a map integer and we will call it map and to not forget to put as a special case which is 0 negative 1 actually in every sub array some problem we need to take care of the 0 but sometimes we need to put a 0 if it's a code sometimes we needed to put an active one it depends on the specific case you need to think about this special case and then we use a sum to accumulate then we iterator this array from 0 I less than number stalin's I plus the sum will accumulate a current value and the only window K not equal to 0 we let some equal to some module K otherwise it cannot be done right ok so if the map contains key so we already did before then we'll check the size if I - map get then we'll check the size if I - map get then we'll check the size if I - map get some great oh you couldn't you if yes we return true otherwise we put the some I threw the map and finally we return force okay we finished and turn complexity is linear b : linear b : linear b : okay I don't know why it's so slow but the same code is permitted 80 hours before all most of them it's just a tool you know it's a nice piece the data so it's quite fast but at least you know the time capacity is big ole and that's enough maybe that's the way have some problem okay thank you for watching see you next time | Continuous Subarray Sum | continuous-subarray-sum | Given an integer array nums and an integer k, return `true` _if_ `nums` _has a **good subarray** or_ `false` _otherwise_.
A **good subarray** is a subarray where:
* its length is **at least two**, and
* the sum of the elements of the subarray is a multiple of `k`.
**Note** that:
* A **subarray** is a contiguous part of the array.
* An integer `x` is a multiple of `k` if there exists an integer `n` such that `x = n * k`. `0` is **always** a multiple of `k`.
**Example 1:**
**Input:** nums = \[23,2,4,6,7\], k = 6
**Output:** true
**Explanation:** \[2, 4\] is a continuous subarray of size 2 whose elements sum up to 6.
**Example 2:**
**Input:** nums = \[23,2,6,4,7\], k = 6
**Output:** true
**Explanation:** \[23, 2, 6, 4, 7\] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 \* 6 and 7 is an integer.
**Example 3:**
**Input:** nums = \[23,2,6,4,7\], k = 13
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
* `0 <= sum(nums[i]) <= 231 - 1`
* `1 <= k <= 231 - 1` | null | Array,Hash Table,Math,Prefix Sum | Medium | 560,2119,2240 |
1,609 | hey everybody this is larry this is me going with q2 of the recent contest juvenile trees uh hit the like button to subscribe and join me in discord and let me know what you think so this one is a relatively straight application of either pre-order or in application of either pre-order or in application of either pre-order or in order it doesn't or shouldn't really matter as long as you do it from left to right um or even post order as long as you do it from left to right then you know then it's good uh and then after that um so what i did is i just run a depth first search uh i go through each node i keep track of the level i you know for each level i append it to a list and then i do the traversal and then after that i just have a for loop for each level we just check whether the condition is true um which is the conditions that you have here uh so it's pretty straightforward um it's a little bit more in the implementation side so let me know what you think i don't want to get it's linear time here and it's linear time here because we look at each element at most once one time so you know you're not it's linear time uh and space is going to be over n because we put every element inside this levels thing right so oh it's a linear time linear space uh let me know what you think i know the description isn't that um you know if you're having trouble finding this uh explanation i would recommend just starting up on three algorithms i think this is a pretty straightforward application of it and there are way much similar problems on the code with this problem it's just that they have different criteria and in this case uh the only thing that changes is just the criteria whether this is a force or true and you just have to keep track of them uh let me know what you think uh i am you know going to learn from how to explain these so definitely hit the like button hit the subscribe button uh and yeah and hit you know and you can watch me live now or solve it live during the contest now oops you uh hmm that's not good okay that's good that is okay oh strictly whoops um don't miss them oh snaps this is okay index what a real problem uh that was kind of a wealth contest uh mostly on the q4 uh let me know what you think about me solving this problem and i will see you next contest bye | Even Odd Tree | find-all-the-lonely-nodes | A binary tree is named **Even-Odd** if it meets the following conditions:
* The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc.
* For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increasing** order (from left to right).
* For every **odd-indexed** level, all nodes at the level have **even** integer values in **strictly decreasing** order (from left to right).
Given the `root` of a binary tree, _return_ `true` _if the binary tree is **Even-Odd**, otherwise return_ `false`_._
**Example 1:**
**Input:** root = \[1,10,4,3,null,7,9,12,8,6,null,null,2\]
**Output:** true
**Explanation:** The node values on each level are:
Level 0: \[1\]
Level 1: \[10,4\]
Level 2: \[3,7,9\]
Level 3: \[12,8,6,2\]
Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.
**Example 2:**
**Input:** root = \[5,4,2,3,3,7\]
**Output:** false
**Explanation:** The node values on each level are:
Level 0: \[5\]
Level 1: \[4,2\]
Level 2: \[3,3,7\]
Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.
**Example 3:**
**Input:** root = \[5,9,1,3,5,7\]
**Output:** false
**Explanation:** Node values in the level 1 should be even integers.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 105]`.
* `1 <= Node.val <= 106` | Do a simple tree traversal, try to check if the current node is lonely or not. Node is lonely if at least one of the left/right pointers is null. | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Easy | 563,1005 |
6 | everyone i'm back again with an interesting video this is an interesting problem that we will look at and i would share the solution that i developed to solve this problem uh says the string paypal is hiring is written in a zigzag pattern on a given number of rows like this uh paypal is hiring so zigzag pattern p a y then p a l i s high ring so this is the pattern that we have to assume that you know if a string is in a zigzag pattern uh spread on number of rows which will be input to the function and the output should read like p h n a p l s i g y i r so given a string and number of rows you we have to assume that you know it is in zigzag pattern spread across the number of rows and then the output is reading it in like straight line okay i hope that makes sense it this problem uh it takes some time for you to you know understand but once understood it is actually a very simple problem to solve so the intuition for solving this program is that what we would do is that we will have a list of number of string buffers like equal to the number of rows so in this case we will have a list which will have three string buffers and what we are going to do is that say you know we'll have to look through the string and in the first iteration up to like three characters or number of rows we would add one to the first string buffer and the second to the second string buffer and third one to the third string buffer now on the way up we will not add anything in the third string buffer but we will add an element to the second one and to the first one on the way down we will not add anything to the first one we will add one character to the second string buffer and second character to the third string buffer and so on so forth until uh that outer loop reaches to the end of the string so that's what we are going to do first up if the num rows is equal to 1 there isn't much that we have to do we'll just return as and then um i will declare a few variables and the you know the toggle one is the one that i will use to know whether uh i'm going down in the zip zag pattern or i'm going up so i'm assuming minus one like there is no zigzag pattern so the first one will be going down and i need bunch of other integers to loop through the arrays and here i am declaring a string builder result because in the end you know i will have to concrete concatenate that list as well the list of string builders so i will use one specifically for that and then this is my list of string builders new arraylist and i will have to initialize this list of string builders so i will do a for a loop and what i'm doing here so i'm initializing the list by you know adding string builders at each row so in this case if num rows say is three then this list will have uh three string builders and let's initialize i as zero i will do a while loop and what do i have so i have in this one what i would do i would set toggle as 1 that means that the next iteration this exact pattern is going up and once this exact pattern for going up is complete then the next one is that it will come down so i will set toggle as zero if toggle is equal to 0 and i will explain in a bit that you know why we have to look at the toggle parameters so when uh let me just set one more loop here so what is happening is that when the total is -1 total is -1 total is -1 what i want to do is that i want to run a loop till the number of rows that we have to worry about and then respective string builder in the respective string builder i would append that character like in the case of paypal is hiring so toggle is -1 for the first iteration so toggle is -1 for the first iteration so toggle is -1 for the first iteration of this while loop and i would get the first string builder append the character at index i and then it increment i and j before uh getting into the loop though i would have to set j as zero so the first element or the first string builder will get p the striking string builder will get a and the third string builder will get y in this loop and then what i'm doing is that i'm setting the toggle to one now why we need to know the toggle position is that in the second iteration of the outer for loop we do not want to assign anything to the last string builder so the j in that case would be j rows minus 2 in this case you know because j is starting from 0 so we have to factor in that and that is why we need to subtract it by 2. essentially what it does is that you know for example if num rows is 3 so you are subtracting 3 minus 2 1 and what you have is that we will loop it from the back in this case so we will set the first l first string builder with the character and then the second string builder so in this case we are setting up string builder one and string builder zero so that's why we have to start from uh from the n minus one for uh when toggle is equal to one so let me just copy paste it and update the certain things all set so you have to do continue and then on the way down what we want to do is that we do not want to assign anything to the first element so that means whatever assignment that we would do would be from the second string builder in this case it would be uh j1 that's a second string builder so i'll just copy paste this okay so i think this looks good so we will have our string builders updated with all of this toggling and looking at certain restrictions so once all of this is done and we are out of our outer while loop now we are ready to concatenate the results into the result string builder that we have since it is a string builder we have to convert or get the two string value from that so i think we are good to go now let's run the code great so we're getting the results back let me just run another test case so this one also goes fine in terms of the time complexity it is uh big o n you might argue that you know there are internal while loops as well but those while loops are going to run for certain number of rows and number of rows going by the test cases you we can assume that you know it will be some constant value only but yeah so that's what the time complexity is in terms of space complexity it will be of the order number of rows uh yeah so in this case uh yeah the time complicity i think uh getting back to my initial comment so it would be of the order n into the number of rows now if number of rows is a constant value like i mentioned you know going by the examples then we are looking at time complexity of o at n and similarly the space complexity would be also or num rows and if num nodes is a smaller value then it is constant let's try submitting it okay so this goes fine uh runtime is 11 millisecond faster than this now thinking about you know the optimizations now one very good optimization is that if you look into the solution and i can copy paste it to here to do a better comparison so one optimization that the solution from lead code does is that you know there are no internal while loops which is fantastic because if the number of rows is higher then you're looking at and into number of rows uh let's first submit this solution to see that you know if this solution gives runtime and you know lower than the one that we had from previous solution it does not and it may just be the test cases that we have for behind the scenes for this particular problem does not expose the limitation or the time complexity part from the previous solution but intuitively if number of rows is high then you're looking at high time complicity in the previous solution in this one it is doing all of that toggling untoggling just in the one loop itself so what it does current row is zero and it has going down as a flag to say whether it is going down or going up so going down is false here and then you come here in the first iteration you would add to our example it you would add b to the first uh string builder and then you would check whether you're going down or not so you're looking at curve is equal to zero it is zero and then you would make going down as true and in the last statement in the loop you're checking whether going down is true or not if going down was true you would update car row to next one so car row would become one and for the next character the second string builder will get the character now when you are to the uh end of car rows like if you said that in our example we were looking at num rows as three so after two assignment to the string builders car row would become two and curve would become when curve becomes 2 going downward become false again that means now you're going up so when it becomes false then you decrement the current row so current row would become one and in the next iteration when the zigzag is going up the second one second or third string builder will not get the value but the first thing will get the value while going up and likewise you know so that toggling that we had in the previous solution that is maintained through this sophisticated mechanism so this is a better solution and if asked you can go with both the options and talk about the differences between the two although the test cases for this solution in lead code did not expose the high time complexity of the previous solution it is just at par thanks for watching let me know if you have any questions for me | Zigzag Conversion | zigzag-conversion | The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: `"PAHNAPLSIIGYIR "`
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
**Example 1:**
**Input:** s = "PAYPALISHIRING ", numRows = 3
**Output:** "PAHNAPLSIIGYIR "
**Example 2:**
**Input:** s = "PAYPALISHIRING ", numRows = 4
**Output:** "PINALSIGYAHRPI "
**Explanation:**
P I N
A L S I G
Y A H R
P I
**Example 3:**
**Input:** s = "A ", numRows = 1
**Output:** "A "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of English letters (lower-case and upper-case), `','` and `'.'`.
* `1 <= numRows <= 1000` | null | String | Medium | null |
1,091 | welcome back to other Jess today's question is leak code1091 shortest path and binary Matrix so given an M by m binary Matrix grid return the length of the shortest clear path in The Matrix if there is no clear path return -1 so a there is no clear path return -1 so a there is no clear path return -1 so a clear path and a binary Matrix is a path from the top left cell to bottom right cell such that all the visited cells of the path are zero all the adjacent cells of path are eight directionally connected the length of a clear path is the number of visited cells of this path so in example one we have this Grid or this Matrix and we want to get from top left to bottom right and we have eight possible directions to go from with this initial point so we can go up down left and right and all the diagonals so we first visit this cell which will equal one and then we move diagonally to visit the bottom right cell which will equal one as well so adding those together will give us the output of two so this question is asking for the shortest path so we're going to be using reference search for the solution now we know the starting point is always going to be at index 0 and we know the end point is always going to be the bottom right so we know the starting point and we know the ending point now with breakfast search we're going to be using a Q and this queue is going to restrict the process in order to First in first out so we'll always have to shift off of the queue So within the queue what we're going to add is we're going to add this starting point so we're going to add the starting indices as well as the count right so we can initialize this with a count of one to say that we've visited this value right here okay so this has been visited within each Loop of the BFS we're going to have to make a check to see whether these indices are equal to these indices as you can see Zero is not equal to the bottom right so next thing to do is to check in each Direction so we're going to go up down left and right as well as all diagonals so as you can see all of these are out of bound this one we can't go here and we also can't go here because they're pointing to ones so we'll make that check if the next value is equal to a one don't go there if it's equal to a zero we'll go there so this is the only arrow we care about the only direction we care about so we'll add this into our queue so zero one we're going to add the indices and we're also going to update the count so one goes to two yeah so we've seen this we make the check we check to see where this is at the end it's not so we check the eight directions the issue we have here is that one of the directions goes back to the previous zero so before we even start making checks in here we need to go back a step and we need to update this at the end to one that way when we make the eight Direction check we're going to go back here we're going to see that this is a one and we're going to back out a bit because we're only looking for zeros within this prefer search so we're at this point the only directions we really care about are this one and this one so we can add the indices of this plus is count to the queue so one two we'll update the count to three this one zero two update the count to three and before we move on to checking this one we're going to remove this and add one so now we're here we check if this is at the end point it's not so we check the directions so the only two that we really care about is down here and up here so again we can add these into our queue and we've seen this one we're currently looking at this one so we can add two to four in here and also zero two and four in here now we update this to one we can remove that the next in the queue is zero two three so we shift off of Q to look at these zero two three so this one is going to check all of its directions right and as you can see none of the directions are valid right because we've updated this to one because there's a shorter path down here that means that we cannot go anywhere from this point so we can back out of this go back to here we've seen this now and we can shift off of Q and go to 224 so when we reach 224 we check to see whether the indices is equal to the end and it is so we can just return this count time complexity of this one is going to be oven because it's a bog standard breath as such and space complexity is also going to be oven so let's write this out so the first we need to make a check so if Grid at zero is equal to one then we just return minus one because there is no path going from top left to bottom right where the only values we visit are zeros then we need to make our directions array so I'm going to speed this up so these are all the eight directions that we're going to be going in and we're going to be using these to make the BFS a lot easier to implement with the Q we're going to initialize it and pass in the initial starting point and also a count of one then it's a case of carrying out BFS so what a q dot length we can extract the current X current Y and count from here so that current X count Y and count equal Q dot shift now within JavaScript there isn't a fancy way of Shifting off the queue but we can consider this as like a linked list DQ which is a one-time capacity list DQ which is a one-time capacity list DQ which is a one-time capacity if current X is equal to grid dot length minus one and current Y is equal to grid zero dot length minus one we can return count right so if we're at the bottom right position we can just return the count then we need to Loop through the directions and the way we do this is extract X and Y from the directions array and then we create the new X and New Y so the next positions and we do this by adding current x and x together and current y and Y together so this is just shorthand for writing that next X equal current X Plus X and let next y equal current y plus y just cleans up the code and makes it more concise now we need to make a check to see whether the next position is inbound and if it's equal to zero so if next X is less than zero or next X is greater than grid.length minus next X is greater than grid.length minus next X is greater than grid.length minus one so two for up or too far down or next Y is less than zero so too far left or next y is greater than grid zero dot length minus one so too far to the right we also need to make a check if the next value we go to is equal to one if it is then we don't want to go there so we just continue from this otherwise the position we're going to be on at this point is going to be zero so we need to push into Q that position so next X next Y and also we need to update the count here so count plus one and to stop us from carrying out repeated calculations we need to update next X next y to equal one voice we just return minus one let's run that and submit it and there you go | Shortest Path in Binary Matrix | maximum-average-subtree | Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`.
A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that:
* All the visited cells of the path are `0`.
* All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner).
The **length of a clear path** is the number of visited cells of this path.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 2
**Example 2:**
**Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** 4
**Example 3:**
**Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\]
**Output:** -1
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 100`
* `grid[i][j] is 0 or 1` | Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution. | Tree,Depth-First Search,Binary Tree | Medium | 2126 |
1,026 | hello hi guys good morning welcome back to the new video in this we going to see a problem maximum difference between node and ancestors and uh this problem is asked by Amazon Google and Facebook in last one year so in the last 6 months it has not been that frequent but in the last one year it has been let's see what the problem says that we are given the root for sure if we are having a binary tree or a tree we are usually only the root itself because from there we can easily start traversing we find we have to find the maximum value V which means V is nothing but we have two different nodes A and B then it's the difference value absolute again that's absolute this is a modulus which represents the absolute difference value between A and B so for sure if we want this V to be maximum again we want this V which is the absolute difference between a and b value we want this value to be maximum V value to maximum so what we can do is we can just take this as the maximum value we can take this B as the minimum value if this is maximum if this is minimum of the entire tree then for sure I can easily say that uh my V will be maximum so it just says that uh now um how this A and B are defined it is saying that node a is an ancestor of node B oh so a should be the parent of node B if either any child of a is equal to b or any child of a is an ancestor of B so child of a is equal to b or any child of a is an ancestor of B basically like let's say if I have a c which is an ancestor of B so with that also so I can easily say that okay it's true it is true now the first question which you might say is B you told that this a value needs to be maximum and B value needs to be minimum so shall I say that I will take my ancestor as the maximum value and the current node as the minimum value are you seeing this to take which means are you seeing that let's say if I am here so 8 will be for sure it needs to maximum right so eight will be big and 14 will be small but it is not small so this will not form a ancestor pair which means it is not maximum than it is not more than this 8 is not more than 14 so it should not form this pair but no I'll say it's absolute value so I can write the same thing also as B minus a which means for sure this can be a maximum value this can be a minimum value right so any node again a need to exist of B that is true which means A and B only needs to be two different node in the level obviously in the path of the tree from root to node like root to the leaf node A and B should be there either a here or B here or a here or B here it can be like this so if we go back and see in this example that this is one path which we can have this is Again One path which we can have and again from root to ancestor this is again next PATH which we can have this is again next part which we can have so basically out of all these four parts I have to get in that okay what can be the maximum value of a minus B and again I just wanted to maximize my a and minimize my B and again that can be any node a can be any node it's just that it has to be a different node than that of my B node okay now uh by why is that different needed because you saw that if it is a same then for sure the answer would actually be a zero so we just wanted that to maximize it we want to have these as a different node itself so what I and by this you can see okay a was actually A8 and B was actually a one which will give you the maximum difference which is actually a seven and that's how you can simply solve this now coming on that how we can do it as we saw that we'll just keep track of the maximum and the minimum value along a path as we go on from root to all the leaves so I can Simple Start From The Root which means I'll simply okay right now the maximum value is eight minimum value is eight and then I'll go on to my leaf node okay sorry I'll go on to my next nodes and again that's a simple DFS travel which I can do I can just simply call for left and right and asking for what is the maximum difference which you can give so what he will do is while going down he will update his maximum and minimum value okay he'll update maximum which is actually it will still remain eight minimum will update it to three okay he go down then he will update the maximum two maximum is still same minimum becomes one now he'll go down oh it has become null now when it becomes null I should okay my entire path has been traversed when it becomes null which means okay my entire from root to Leaf which means all these things are actually traversed when all this is traversed now you should find out okay what is the maximum value as you want your V was absolute of a minus B Now find out what is the maximum value of V so he will say the maximum value of V is 8 - 1 because uptil so far I have 8 - 1 because uptil so far I have 8 - 1 because uptil so far I have updated both my maximum and the minimum values with the corresponding maximum and the minimum so I have I know okay what is the maximum value or the maximum difference value here so I'll update this and I'll get a 7 so now what will happen is he will simply return this number 77 Now by why is this returned can't we simply updated globally yeah you can uh globally have a variable called as answer which you can update it every time you reaches you reach a null node so that is also what you can do by why can't I update it every step which means Here Also let's say you came in here let's say I update here firstly my answer I update here also my answer and then at n also my answer yeah you can do that also is very much okay it's just that will be much more redundant because for sure in this path you would have grabbed what is the maximum value and what's the minimum value for sure so ultimately you can check in the itself so that's uh much more easy for you to check now okay we'll do the same thing for this path so when it was traversing down it had got its maximum minimum like this now when it will go it has traversed here it has returned him the answer as seven now he will go down and he will say okay I'll update my maximum and minimum values okay maximum will not be a because it is8 and 6 is less than 8 and again minum is less than six also again Maxim minimum will still remain same so he will also compute the answer because next value is n he will also compute the answer because same way he'll also go down again he'll compute the answer both will compute the answer as current existing answer is equals to maximum of answer comma uh this value which is here it has competed 8 - 3 5 so which is here it has competed 8 - 3 5 so which is here it has competed 8 - 3 5 so now they can simply return this value so uh from my answer which means from my left portion I'll get in as a value of five but for sure I'll have the maximum value in my answer so I can again there are multiple ways to solve it you can also initialize globally and also you can update it locally right so he will say Okay maximum answer will actually be a seven from left side now the same way maximum value minimum value is 88 maximum value is updated to 10 Again maximum value updated to 14 maximum upd to uh still remain at 14 because value is 13 now I will compute my answer so it will be 14 - 8 which actually six but will be 14 - 8 which actually six but will be 14 - 8 which actually six but still you will see that okay it will return six so from right I'll get a six from left I'll get a seven maximum value from left is like maximum value from left is seven from right is actually a six so for sure I'll take a maximum which is left from right like from left and from right so I'll get a seven as the maximum value from Total so that is how I can simply get my answer and this was the answer for me so if you go on the code it's as simple as that firstly if my base case if my root is null then I'll simply return a zero because for sure I cannot now I'll simply have a function called as maxti is it's just a recursive function I'll call a root I'll give the current node value which is the current see I have to maintain my current Max and my current minan so I'm just doing that while maintaining by going down itself in the tree I'm maintaining that so um I as soon as I land onto this Max diff function which is the same function right here first base case is okay if I have reached the null as I showed you I should have to return the maximum minus minimum value as you saw that when I have reached the null I was Computing this maximum minus this minimum value and this is what I got as the answer now when this portion is done I will go and find my maximum Val which is maximum of this maximum current value and the node value but just maximizing my maximum value just minimizing my minimum value and then both values I have I simply call my Max for lifti which means calling for left and passing in the maximum minimum value and same for the max right diff which means calling for the right and passing the maximum minimum value now when I have the maximum from the left and maximum from the right I'll simply take the maximum to return to my final answer as you saw when I have maximum from the left maximum from the right and I'll simply take the maximum of both of them to return in the final answer and that's what I am doing right here and that's how you can simply solve it in O of n time and O of n space because o of n time because you are traversing on all the nodes of the tree and O of n space because in worse case your recursive stack can be a screw tree and that can go very deep which means just like this a straight A straight kind of a tree and that's how you can simply solve it so I hope that you guys got this bir care bye-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 |
134 | hey everybody this is Larry this is the seventh day of the legal daily challenge of the year or the sixth day out no let me now look at this uh hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem I'm gonna just see if there any bonus coins nope uh yeah um today's prime is gas station so let's take a look um and I am doing this a little bit earlier in my night so I am going to do a bonus problem so definitely hit the power alerts or whatever and then we'll do one more time together if you feel like this was too easy for you um and there will be one prompt that I haven't seen before even though I don't remember most problems but you know who knows but inside the subconscious who knows how those things work all right let's take a look today's Farm is 134 gas stations or the end gas stations on a circular route where the amount of gas is gas supply you have an unlimited gas tank that costs of course of I to travel from the eye station to the next station you begin to drive an empty tank at one of the gas stations given two images away gas and costs return the starting gas stations index if you can travel around the circuit once in a clockwise Direction otherwise we turn negative one foreign okay oh it's guaranteed to be unique okay I was gonna be like huh can you just do it for me everybody but yeah okay um what is does that mean so basically gas means that it costs oh no wait what is oh that's basically how much you get and then it costs that much um to get to the next one so in theory okay so the station three index three you fill up with oh this one index three and zero index is always weird when they say it like that but uh yeah so you start at four you use one and then you go five and you need to do two okay I think I got it now so the first thing to do is that we can do with a circular thing for this particular case we only need to go um we only need to circle around once so what that means is that and in this case there are constraints that they tell you for example that it's going to be unique and so forth so you can uh one kind of uh um I don't know if it's called I don't know if it's a hack but the way that I do it is basically doubled it away right um foreign something like this away um you can think about wrapping around once just as you think about like for example you want to go from three all the way back to one you could also just think about it this way instead of doing physically manually running around and it'll make the map slightly easier maybe I don't know usually it does make the coding a little bit easier otherwise we wouldn't do it so okay so let's see so let's just say what current is your zero start is equal to negative I mean it doesn't really matter but also zero and then now we say n is equal length of gas uh and then now for I in range of n we have g c maybe it's equal to gas up I COS of I every pie crust I never for enumerate okay fine let's do it with a numeral enumerate uh so we have something like that what and then basically currently we fill up right I guess just Gene we fill up and then we it takes us uh cost to go to the next one right and then now if current is less than zero that means that well I just want to make sure I'm off by One cases that's what I'm reading on um basically for example four then you use one and then you four by five and that's roughly why maybe I'm off by one let's see um so if coin is equal zero then that means that the current one ended and we need to start off a new one right and then here we say start is equal to I maybe or I plus one maybe I don't know else if else then we just continue but we also want to do a check where if I minus start is greater than or you go to n and this has to be the original N I suppose then we can return I or we can recommend return start then we return negative one afterwards I think this is roughly right but I feel like I'm off by something because basically you try to start at one it fails immediately and they've tried to decide to segment of fails immediately and then so that third one also fails immediately then four um why isn't that working so four one five two and let's just print it out it's okay oh I am done I forgot to restart it to zero I was wondering why um almost like the other thing okay I've been making a lot of silly mistakes lately but this one's okay all right so let's give it a hmm I'm trying to think of it so I mean I think the hardest point for me to explain this particular part is the one where um can you get to well no okay so this is why this is up uh good in the sense that like you know one question that you might have is like well if you get to zero or if you get to negative at some point what if you know let's say you have five elements a b c d e or whatever let's say you got the negative here right well yeah let's say you got the negative here um and You Begin this segment you know from ABC say right um why do we reset a d and not at you know maybe B right so that may be one thing that you may ask but the thing is that we know that because the pre um the precondition or the invariant of this thing is that going into C it was positive right or zero so that means that going into c um it has a greater like has a positive impact right meaning that okay with the and you know we don't even have to I mean I know that we're talking about adding and then subtracting so you can think about as a deltoid away but that means that if a plus b is going to be greater than zero um let's take a really you know obvious case where a plus b is equal to billion right so if it goes to a billion it adds to the negative value of c and it goes to negative zero that means that even if you take away the contribution of a which by default also is going to be greater than zero B plus C is also going to be less than zero right so that's why you're able to kind of reset it and set it at zero starting from D now going forward because we know that c is a very negative impact on the answer um okay I think now I believe that and then now I can maybe submit and hopefully I don't make a silly mistake sweet uh 10 12 streak um yeah that's pretty much it this is going to be linear time linear space hope I don't have to explain it that much uh why um the linear space well it's linear time and then your space because we double the space uh the way that I did it here but of course if you are very careful you can do this in all one space basically the same idea but you know a little bit more careful like yeah I mean yeah you could just set like G as for example you can maybe just do like a GC as you go to uh gasup I dot add or something like that right and then of course you have to want to fold it twice or something but anyway so you could get this in constant uh space but yeah that's all I have for this one uh that's pretty much it let me know what you think stay good stay healthy do good mental health have a great weekend everybody I'll see you soon and take care bye | Gas Station | gas-station | There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.
You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.
Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique**
**Example 1:**
**Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\]
**Output:** 3
**Explanation:**
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
**Example 2:**
**Input:** gas = \[2,3,4\], cost = \[3,4,3\]
**Output:** -1
**Explanation:**
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
**Constraints:**
* `n == gas.length == cost.length`
* `1 <= n <= 105`
* `0 <= gas[i], cost[i] <= 104` | null | Array,Greedy | Medium | 1346 |
71 | guys anyone ask you what is your path in life what is your aim in life do you have to clear your path right so that's a question this is in this question you will just play with the dot double dot and double slash if there is single dot in the string you will go to the current directory if there is double you have to move up double slash means single and anything other than that you have to consider it as a directory name here are the examples you are removing this and this right and let's go to solution is very simple we will just use a stack and you will split the path with the use of flash so first slash Traverse okay every element in the path and then there are two statements so the first statement will come to else if because if the element is not in any three of these then you will directly append the element to the stack stating it as a directory now if it's very simple if the stack is not empty and the element is equal to double dot then we'll simply pop at the last we'll just append the result with the Slash and that's what I'm | Simplify Path | simplify-path | Given a string `path`, which is an **absolute path** (starting with a slash `'/'`) to a file or directory in a Unix-style file system, convert it to the simplified **canonical path**.
In a Unix-style file system, a period `'.'` refers to the current directory, a double period `'..'` refers to the directory up a level, and any multiple consecutive slashes (i.e. `'//'`) are treated as a single slash `'/'`. For this problem, any other format of periods such as `'...'` are treated as file/directory names.
The **canonical path** should have the following format:
* The path starts with a single slash `'/'`.
* Any two directories are separated by a single slash `'/'`.
* The path does not end with a trailing `'/'`.
* The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period `'.'` or double period `'..'`)
Return _the simplified **canonical path**_.
**Example 1:**
**Input:** path = "/home/ "
**Output:** "/home "
**Explanation:** Note that there is no trailing slash after the last directory name.
**Example 2:**
**Input:** path = "/../ "
**Output:** "/ "
**Explanation:** Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
**Example 3:**
**Input:** path = "/home//foo/ "
**Output:** "/home/foo "
**Explanation:** In the canonical path, multiple consecutive slashes are replaced by a single one.
**Constraints:**
* `1 <= path.length <= 3000`
* `path` consists of English letters, digits, period `'.'`, slash `'/'` or `'_'`.
* `path` is a valid absolute Unix path. | null | String,Stack | Medium | null |
316 | hi all welcome to learn code repeat so today we will be looking at day 11 of the october lead code challenge the name of the problem is remove duplicate letters there are two problems in lead code one is three one six and the other is one zero eight one both are of similar type so let us look into the problem so problem states given a string s remove duplicate letters so that every letter appears only once you must make sure your result is the smallest in lexicographical order among all possible results so this sentence you must make sure your result is the smallest in lexicographical order among all possible results its kind of a confusing statement but will look into this with an example so here for example one it states that input is bc abc now among this the unique characters right are a b and c right and in lexicographical order that means the sorted order of ascending characters right it will be a b and c so that's the output here abc and the other input is this will look into this example but before that the constraints that have been provided is s dot length is greater than or equal to 1 and less than equal to 10 raised to 4 and s consists of lowercase english letters so let us look into example 2. so here in this example right we have c b a c dc right so the unique letters are a b c and d these are the unique characters right now here when they say lexicographical order writer they mean that the output should be such that the character order in the string should not change so here the character is a is appearing here right it should not change at the same time we should select unique characters in our output such that the smallest in lexicographical order should be selected first right what i mean by that is now here in the string right if i do not change the order but still i want to select all the unique characters right what are the different outputs that i can get so here one is c p a and then there is d so here if i select this red that means c b a and then here d because c was already selected so i won't select again c b c it was already selected here so i won't select again so when i select d and this is the same sequence of order in the string as well right c appears first then b then a and then d appears right so this is one sequence and we are including all the four letters that is there in the string s right all the four unique letters we are including here the second sequence that we can have is i can select b here and then a then c and then d right this is second sequence and the third sequence is if i ignore c and b then i can select a then c d and b right the fourth one i can do is i can select a d c b and the fifth one can be a d b c right so i selected a d b c so in all this if you see i have made sure that there are only unique letters and all the unique letters are included in this right now among this results right which one is the lexicographical order the most lexico graphical order that means the smallest character should appear first and then the next largest so which gives us the best lexicographical order right so here obviously since a appears first c and b we cannot take this into account because a is the best lexicographical order that we can have among these three right if you see after a we have c here and here after a we have d right now c comes before d so i cannot use this now between this 3 and 5 right a c d b and here a d b c so obviously c comes before d so we cannot use this as well so this will be the final output that i need to select and that is what here they are expecting acdb okay so now let us look into the logic how we can build this right so what we can do is we can go through this string and since we want to get the unique characters right at the same time we want to keep the lexicographical order right so when we go through the string right if you want to skip a particular string right i can only skip it if i know there are multiple different occurrences later on in the string so for example if i am going from left to right here right and let us say i want to skip c i do not want to consider c here now then i can only skip c if i know that c is available later on in the string otherwise i cannot write so first step will be to know that right we need to know the how many numbers of that letter is present in the string right so first step will be i will build a frequency map ok first is frequency map i will build so once i build this frequency map so i will go through c so i know that for c there is one two three four there are four c's for b there is one two there are two b's and for a there is one a and then we have d there is one b ok so once i have the frequency map then i can go through the string and build the final output string right and during that process i can check whether the previous one that i added is greater than the new character what i mean by that is let check this right if i am going through the string from left to right so let us assume that i include c in my final result right then i go to b i will check whether my current character is less than my last character in the result so my previous character or the last character in the result was c now c is greater than b that means my current character is less than my character in the result right now i can start my result with this current character which is b only if i ignore c okay and i can ignore c only if i know that c appears later on in the string right so for that i will check my frequency map okay i will check if i can decrement the count and still it will be greater than zero so i will decrement the count by one and still it is greater than zero so from the result i will remove the last entry and add my current character which is now b current character is b okay now i will move to the next character which is a okay now here if i see i can only include a if my previous result is less than my current character okay now here a is not less than b so i need to remove b now i can remove b if i know my frequency map if i decrement the value it is still greater than zero so if i decrement it will become one it is still greater than zero so i can remove this b and i can keep my result as a okay so the steps that i am doing here is add the letter in result and check if last character is so my last character should be less than current care in my let's say string is s so in measuring s so last character of result should be so last character in result is less than current character if not remove the last character of the result if the last character appears later on in the string that will come to know using the frequency map here right ok so let us say we added now a and then again we get a c my next current counter is at c i will check whether i need to add c right i'll check whether c is less than my last character its it is not so i can directly add c without removing the last character now before adding c right i also need to make sure that whether that character is already present in the resultant because i need to form a unique result right so for checking that i can have like similar to frequency map i can have a unique set or a unique array since it is given that its only 26 characters so i can use a boolean array to check if current character is added already so if current character is already added then i can directly skip it else i can add the current character so since c was not added i will add the c now then i will go to the next character which is d again d is greater than c so i do not need to remove anything i can directly add d and also d is not already added in the boolean array so i will add d so here as and when i am adding to the result right this is my result string so as then when i am adding a character to the result string i will also add the same character to my boolean array ok and similarly when i am removing any characters i will also mark that character in my boolean array as false okay that i have already removed i am not using it so here now we have added a c d now again c comes in my current character is c i will check in my boolean array that c is already present so i will skip that c now my current character is b okay i will check in my boolean error that b is not present then i will check whether my b is greater than d which is the last letter of the result it is not greater than d then i need to remove the last character provided there is more occurrence of the last character in the shrink later on in the string and that we can check if we decrement the value and the value is greater than zero so here the last character is d if i decrement the value of d here it is not greater than zero so we cannot remove this value ok so since this value cannot be removed we will keep this value as is and we will add the current character here as is okay so we will add ac db and then i will move to the next character now next character is c was already there in the result so i will ignore this so that way my final result is ac db which is same as this okay so for doing this operation right we were removing the last character and then we were adding right so the data structure that supports this in a o of one time right is either you can use a linked list or you can use a stack right so if for example if you are using linked list you just need to remove the last character from the list that is of one operation right so if you see we are going through all the characters of the string array so that is o of n time and the additional space that we are taking is for the boolean array and for the frequency map right so in worst case that also will be o of n so we are taking off n time and o of n space here so that will be the complexity so let us code this logic that we have here and while going through the code i will again explain the steps that we performed here so that way you will be able to relate this logic with the code logic easily let us look into the code so the first step we had was building the frequency map so for that i will define int array since we know there are only 26 characters lowercase characters so i can define a in frequency array of 26 characters so i will go through each and every character in s and build the frequency map so what i am doing here is i am incrementing the value of the frequency array for that particular character position minus a so if the character is for example c so it will be c minus ascii code of a so here ascii code of small c is 99 and ascii code of small a is 97 so it will be 99 minus 97 that will give us 2 so at index two it will increment the value ok so c will be index two because it is the third character and since we are using zero index so it will be index two ok so that way we are building the frequency map here so once we build the frequency map we will go over again in a for loop through this letters and we will need a boolean array to check whether the characters were already added we will need a linked list to form the final result so first we will decrement the frequency of this character so as and when we are going through each character we will also decrement the frequency so whether we are using it or not we are already passing through that character so that frequency of that particular character needs to be decremented from the frequency map right frequency of ch minus so i am decrementing the frequency now i will check whether the character was already added so by default since its a boolean array by default the values will be false and i will make it true only when i am adding that character to the result right so here if it is already added then i can continue with the next character now i need to check whether this current character is less than the last character in my result list right so i'll check if my result or get lost the last character of the result if that is greater than my current character and if i have more of the current character later on in the string right so that we can only check from frequency map so the current frequency is greater than 0 for that particular character so that means the current character appears later on in the string as well in that case we can remove the last character from my result right so in this case i can directly do result dot remove last okay now since i am removing this last i also need to make sure that this added is turned back to false right so i will also do is added so result remove last will not only remove the element but it also returns the element that is removed so i can use this as is and say that this is false so this will also remove it and also make it false in the is added array okay now here this can only happen if the result is not empty right so we have to add that check as well that result is m t should be false okay now here if i remove the last element right what if the second last element so after removing the last element the new last element is also greater than c in that case also we have to do the same step again right so here sort of if it should be y that means we have to do the same step again and again until my last element in the result is less than the current c h and also provided the frequency of the ch is still greater than zero only then i can afford to remove that character okay actually i am removing this large character right so i need to check the frequency of the last character not the frequency of current character c h is the current character so here it should be frequency of get lost so i can only remove that last character if the frequency of that particular character is greater than 0 that means that character is appearing later on in the string so i can remove it now okay so once i do this after that i can add the current character in my result and since i am adding the current character i need to update the is added for the current character so once i do this in the for loop the remaining result will have the unique character set so at the end i can directly form the string from the remaining result here what i can do with a string builder and then go over the linked list so while result dot node is empty strp dot append i will do a result dot remove first so i am removing the first element from the result and adding it into the string builder so i am doing this until my result is not empty and at the end i can return the string so let us run this code and the test passes let us submit this and the code is accepted and as i said the time complexity of this will be o of n and the space complexity since we are using o of n space so the space complexity is also o of n i hope you like this video please do hit the like button and do subscribe to the channel for future such videos thank you | Remove Duplicate Letters | remove-duplicate-letters | Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/) | Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i. | String,Stack,Greedy,Monotonic Stack | Medium | 2157 |
98 | foreign code called validate binary search tree it is a medium let's get right into it given the root of a binary tree determine if it is a valid binary search tree a valid BST is defined as follows the left subtree of a node contains only nodes with keys less than the node's key the right subtree of a node contains only nodes with keys greater than the nodes keep both the left and right subtrees must also be binary search trees so we have sort of this recursive definition here and if we go to example one we have the root node two the left child one and right child three and here we output true because the left is less than the root and the right is greater than the root and notice here it says less than or greater than it needs to be strictly less than or strictly greater than it can't be equal to and example two we have one five three four six the left child is less than the root so that is valid but the right four should have been greater than five but it is less than it so we output false now this is actually pretty simple and straightforward as long as we know what a binary search tree exactly is so if you know what binary search is this is very similar to that so in a binary search I would have say the following ordered array with indices going from 0 to 10 which means I know I have 11 elements and what I want to do for this is look for say a Target so I'm looking for 11 performing a binary search the first thing I do is I split that array straight down the middle so this is where I would be splitting and I would compare that value with my own I know that mine is greater than the value that I see here so I need to look in the right half that is where my values would be so when I take this half and I split once again right down the middle and I compare once again the value that I'm seeing with the value I have mine is less than the middle so I now need to look into the left of this new hat so what I'm doing is the balance are getting smaller and smaller every single time and that's exactly what we're going to do with the binary search tree it's the same concept instead of an array we have a tree and instead of splitting at the midpoints we sort of split up roots and we're guaranteed that everything to the right of our root node has to be greater than it and everything to the left has to be less than it now let's take a look at an example with an actual troop so I have a tree here and I want to fill out values to make it valid so for my very first Top Root node what values can I put in here there's no restriction so my range can be from negative Infinity so negative Infinity all the way to positive Infinity there is no bound no restriction for my first root note so negative Infinity all the way to positive Infinity say I go with 10. so this is my root node this means that my right child has to be greater than 10 so it can go from 10 all the way to infinity and same thing for my left which would range from negative Infinity so negative Infinity to 10. it has to be less than 10. so what values can I actually pick anything greater than 10 say I go with 20 and anything less than 10 say I go with 4. these are within bounds so they are valid now for the right child of 20. we're going to have a tighter bound this time around because not only does it have to be greater than 10. it now also has to be greater than 20. so here it needs to be from 20 all the way to Infinity these are the values that I can pick between so I'm going to say this is 40. what about my left child the left child of 20 has to be less than its root so it needs to be less than 20. but remember this all was the right subtree of 10. so it needs to be greater than 10 but less than 20. so the bounds are going to go from 10 to 20 and of course this is non-inclusive course this is non-inclusive course this is non-inclusive so these are what my bounds are I can pick between I'm gonna go with say 12. and same on the left side right the bounds over here would be from 4 because it is the right child it needs to be greater than four but it still needs to be less than 10 it's still Bound by the parents right bound as well so we're just making it tighter instead of going from negative Infinity to 10 it now goes from 4 to 10. so 4 to 10 let's say we go with 6. and same thing over here the bound instead of being from negative Infinity to 10 it is the left child of four so it needs to be from negative Infinity to four and say we go with two so these are my values and Bounds let me also write these out okay so I just went ahead and rewrote all of the values with the bounds in place now let's take a really quick recap at the top we have our root node 10 that falls between negative Infinity to positive Infinity so no real bound there the right child of 10 we know has to be greater than 10. these bounds are not inclusive so it needs to be greater than 10 and it can go as high as possible and 20 is valid it is greater than 10's left child needs to be less than 10 so that is our bound and 4 is valid now 20s right child not only does it need to be greater than 10 it also needs to be greater than our own root value than 20 is a value so it needs to be greater than 20 and it is 40 is greater than 20. so this is valid as well now 20s left child it needs to be less than 20 because it is the left child but it needs to take into account its own bounds that it gets from 20. it needs to be greater than 10 but less than 20. and 12 Falls within that range so it is good as well now 4 is right again it needs to be greater than 4 it is the right child but it is coming from its own bound which needs to be less than 10 right this whole thing is a left subtree of 10 so it needs to be between this range this bound and 6 Falls between that so it is valid as well and over here Four's left child it needs to be less than 10 but also less than four so the total Bound for that becomes less than four which it is 2 is less than four so this whole tree is valid now what do we notice here right every time we have a child it's taking the root node as one of its bounds so the right child of 10 needs to be greater than 10. the right child has its node parent node as it's left about the left child has the parents node as its right bound and again here right the right child of 20. has 20 as it's left bounding to be greater than 20 and the left child of 20 has 20 as its right bound it can only be as big as 20. same thing here we have a root note of four and if you are the right child four is your left bound you have to be greater than four and if you're the right child four is your right bound you need to be less than four so what we're going to do is I'm gonna iterate through our entire tree in order to check validity we're going to be passing in our root value as one of those bounds and keep the other bounds as is because that's the only one we're getting tighter on and we're going to do this for every single node all the way down and if at any point we break that bound we know we need to return false if we've gone through the entire thing and everything is valid then we would return true that this whole tree is valid so let's go ahead and total this up then run through a super quick example now this is a binary search tree and four trees the best way usually to iterate through is to use a recursive DFS approach so to do that I'm actually going to write a helper function first so this is going to be my helper and I'm going to take in my route and what else do I want to take in I want to pass in the bounce each time I want to make sure my root value stays within that so I'm going to be passing any left and right about now with a recursive solution you want two things the base case and the recursive case so for the base case what is base case number one what happens if the root that I'm passing in doesn't exist if it's non-existent it can't be not if it's non-existent it can't be not if it's non-existent it can't be not valid right so if root is none we would return true and what this means is we've gone through every single node in our tree and we've reached the end we've gone past the child past the leaf node so a leaf node is any node that's not having left to right child we've gone past that which means if we've made it that far everything we've seen up till now has been valid and we would return true now when do we return false well every time we want to make a check if our root is within bounds right so we want to see if left is less than our Roots value and is Our Roots value less than right and this is not true so if this condition does not hold then we know we're not within bounds and we would return false now we know our root Falls between these bounds if it has not exited either of these if conditions now we want to check our child notes so we want to check both left and right children and see if they both return true so for that I am going to say we want to return self.helper to say we want to return self.helper to say we want to return self.helper on root dot left so I'm calling with my left child first and what are the bounds that I'm passing I am passing in the same left bound that I have from my parents if I'm a left child I have the same left bound as my parent so I'm going to be passing it left the only thing that is changing is the right bound right that is going to get tighter and that's going to take our root nodes value our appearance value so this is going to be root dot about this is getting tighter so if this is true and if my right node is also true so solve dot helper on root dot right and what am I passing in for my left bound if I am a right to note I am getting tighter on my left bound right if I'm a right note right here I'm getting tighter on my left bound because there's a new value that I need to be greater than so I'm going to be passing in root dot vowel that parent node for my left bound I need to be greater than this new left and my right can say what it was from my parents so that is going to be right exactly what we're passing in because this is going to remain unchanged the right bound remains unchanged and if both of these return true then we would output true if either returns false we output false because of this and operator right here and that is our helper function what are we going to call it with we pass in the very first note so we're going to be calling this helper with our root node so root and what are my initial left and right balance well that would just be negative Infinity so negative infinity and floats of positive Infinity let's go ahead and run this code long answer I actually don't have a return here so let's see if that is the reason all right that is accepted and we can go ahead and submit this and it is accepted as well so we're talking about space and time complexity we are going to be going through every single node so fourth time that would be o of n because we want to check if every single node is valid and for space our recursive call stack could be as big as the number of nodes in our tree so that is also over and over space now let's super quickly run through a quick example just so we can see how our code is running line by line I'm actually going to be taking example two and modifying it just a little bit so I have the root Note 5 and have one six four three so let's start at the very beginning and just go through this line by line the first thing I do is I call my helper function with my root node being passed in so I'm calling puffer with my not being passed in negative infinity and positive Infinity these are my left and right bounds I'm just going to write this out so it's a bit clearer so I have group and five left this and a right being this now I'm in my helper function and I see if my root is done I would return true root does exist so it's not none now I want to check these bounds does my value fall between these bounds it does so now I'm going to be calling the helper function again with my left and right child so what is the left child of my root node five well that would be one so I'm passing this in with one and my left would stay negative Infinity that bound stays negative infinity and my right updates to the value of my root so that would be 5. and I would call the helper again with my right as well so that would be six root dot vowel so the left bound becomes five and my right bound would stay infinity and since we read left to right we would solve for this first so we're calling helper again with root node one left being negative infinity and right being 5. now I go into this condition once again root is not none and one is between these two bounds negative Infinity is less than one and one is less than five so now I call helper again passing in my left and right children so left and right children of one are none so I'm just going to be passing them in and the left bound for the theoretical none would be the left so that would be negative infinity and root dog vowel which is one and I'm passing in with my right which is also none root dot val which is one and infinity so I'm reading this left to right I first call helper with these values I have root equaling none left being negative infinity and right equaling one now what we're in this condition and root is none so I would return true so I return true for over here and I can go and make this call again but I know this should be returning true because the root would be none so this would also return true that means that this whole call up until one this whole thing would be true because we have returned true and this call we bubble all the way back up would be true so the left child would be true now we want to call this with our right so now we want to call it in with six which would be helper with the root being six left being five and right equaling Infinity we go into this helper function and root is not none and now we want to check the balance is left less than the value which it is and is the root value less than the right bound that it is so now we're going to be calling our left and right helpers so I'm going to be calling with my left child so left child of six is four the left bound stays what it is over here so that would be five and my right bound what I cannot be greater than would be my current node's value so six so I need to say between five and six and for my right child I am passing in my right node so that would be three my current value so 6 I need to be greater than 6 and my right bound which is infinity I need to be less than infinity So reading love story again I will be calling with this right over here so I'm calling with my root node being 4 my left Round being five and my right bound being six I go into this helper root is not none so now I'm in this if condition is my left less than my root value that is not true right left is not less than my right so I would return false over here once I return false I can actually bubble back up to this color and say that this is false at this point I don't even need to call this Helper and have it figure out if it is true or false I have one false so that means this whole thing evaluates to false and I bubble this back up to my color which is false so this whole thing is now false true and false would equal false and I would return false because this is not valid four should have been greater than 5 and less than six obviously this wouldn't be an integer we can see that this already breaks but this would be false and that is what we would return so this is how we would validate a binary search tree if you have any questions at all let me know down below otherwise I will see you next time | Validate Binary Search Tree | validate-binary-search-tree | Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_.
A **valid BST** is defined as follows:
* The left subtree of a node contains only nodes with keys **less than** the node's key.
* The right subtree of a node contains only nodes with keys **greater than** the node's key.
* Both the left and right subtrees must also be binary search trees.
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** true
**Example 2:**
**Input:** root = \[5,1,4,null,null,3,6\]
**Output:** false
**Explanation:** The root node's value is 5 but its right child's value is 4.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-231 <= Node.val <= 231 - 1` | null | Tree,Depth-First Search,Binary Search Tree,Binary Tree | Medium | 94,501 |
1,542 | This point lungs and sunscreen in this question I have given you a string which will only visit someone will keep mother will edit content from zero to nine this is ok now what is the use of it see you tell on this any servicing You can catch the letter post, I caught your reception, now whatever numbers are there in it, the number of years the commissioner has showered on it has to be made on these ROMs, okay then some will be able to become servicing, some will not be able to become, what should I tell you that friend, the longest Lanka substring. Which can become the first film, okay with these flights ware Shyam friends, now how much love can you have, then look at this sticker, it will be seen as Samsung 214 2418 What gas can I wrap in space, so basically duty then here to two and here But if you set it to one then it will come to 142. Edit: This is a ROM Edit: This is a ROM Edit: This is a ROM so its length becomes 5ghz. Why is this my answer because there was no one else on this page who can make a calendar of length more than 5, ok? So this is my answer, there is no reaction on doing this and the number of behavior you can do is so big, if you look at some more examples, if you get some time like this 1234 560, then only one court will become soft on this first, hold some back, you one. If I take two as hang, then two will become Passion Pro m1 length, you add, so basically the length of all this screen is one, that is my Ki Reddy, I have to find you a long serving, how many times should I lift it and open loop is fine, if there was one more two in this, if this But look at 2068 here, how to scan Jatin happens, basically you can see so many and 212, this is first tight in this row, then the answer will be three, it is okay, this question is two, this trick will have only visits from zero to K line and The length of this make-up line and The length of this make-up line and The length of this make-up comes from one to five according to. Okay, so you can try it from now. Let's switch on to solve. When can any spring balance ROM be made? What is the property of electric param? Calendars. There is something in it which is called two three legs, it is not a pearl drop and but okay, it is proved that now you can do these flats, then you do something like this, 2308 youth gone, all the characters in this pen, they are all from one number and time. is torch light 2b again three twice hiv two times here if it was on again then put four bugdi in the plane room now so if any substring it has ABCD of some strings here then if I say that so many From so many contacts of spring that all the guys, if number and times are even then you can make it a calendar. You do not have to show the height by making an Israeli panel, now you have to blend it. Okay, so it can be made as a printer, then select its length option. You can do it, okay, another pan is heated in it, which is called two three loot 518 so many people with the number love and there is one more person along with it, so you and welcome make it central and 4321 people will go next to him, this is also a calendar, this But all the guys are from even time And one guy is just different Even on flash lights If still and number track Thought 24 forced Two three for four Can be any four On this 4 is what it is Five behavior all the rest twice again Pet is from one number, so now basically my question is who has been completely reduced, so I have a brief sample on my string, there is every possibility in my chemistry in which all the elements are repeated even number of times, all have an even number of repeats or 120 is also the number time or all the events except one more person, then that is also fine, okay then it is fine, we can do this, if absolutely take it, okay, then look at every point, whatever I pin is at this point. And number once from us on this point three more number from time and two more numbers from obscene speed and go ahead free 21 4545 and tree that there is something like this then this point if you directly then here you husband who is that even number time It has arrived here, I am confident, it is completely fine, it is okay, 3rd November, I will have to cry to get over it, okay, three, now there is another number, and the number, time, SIM, is with it, and whatever it is again or Even times five again or that too add and this guy at two o'clock and the number is time so for that if there are two more guys then he can send you a comment then so much prefix is wrong I will do that then so much prefix is wrong I will do that then so much prefix is wrong I will do that I will have to submit something like this from the shooting If I remove it then three events are created or two events are created. Okay, so how can I make this work? Look at this post, basically three more numbers from Sa and the rest are 245, all these are zero legs. From or even 110, you can sleep tight, all these guys are fine with the even number time, so the number track they feel and the total overall marriage number time, now you will get it out this year, even then, after getting out of this year, whatever number Remaining joint account that too one lokay good ok but there is free speaker here and number 17 tight and number matters and we take 5 told me that even on this much portion no three and number friends I would have been one traveler or there would have been fiber Okay, if you remove three accounts on this, how many degrees will go, then five will go to 142 or 5 will go to free two or 5150 will go, whatever degree will be formed there. Okay, so if I work on this then basically what I have to do is this. There is some configuration like this, there are two more people, okay, so to remove three, I need some traffic in which three more number are friends and all the other people are event number, timezone, okay, if anyone else, tell the order here, but for example, if there is powder here. But what else happens is if the lover point had come here once and there tell me if an ad is coming then if you remove so many sequences and do something like this intermittently here and there then send the fiber. Had it been even then it would have become more. My work would have got spoiled because I had created one and the other one was created. Okay, okay, now the Congress has come back to do what I have to do. What is the basic thing? Look at the current situation, how many people are there and so on. Find out if there is an app, either celebrate Eid to all of you, meaning three and two, this is a day and make it number wise, Dad, I need a fee point like this, there are three more numbers, Times also has two more numbers, legs and remove that. Two then and all the rest should be whatever life is the light okay or else or what can you do? The first person reached Shraddha and the second person said that you leave one more person and organize the event for all the others. It was admin sir. Give it as a gift or make it an event. Okay, so Abhinav, let's take an example. It's okay after applying it. If this oil strainer had been given to me, then look at this point or see how many times the Sun Temple is there in the traffic of this point. So on this basically two has come once and number times is every third number and again or even times and five is also the event torch light so if I have to have so many segments in the calendars then basically ending on this One substring to do is okay, from here onwards, I will have to make these two more guys one here or at least one will have to be made one, light or what is the one more addition that you can do in these Make both of them even and also you can order something from here, this is also your choice. Okay, let's see now what else can I do to make both of them even. So now what can I make like this? Look at the location, there are two here and also three from number time and number time set, so many tourists, remove so many parts from these, okay, so these two and the number that is their account, this event will become this change. It will be even, okay, so basically, you will only get this wisdom, how many front row torch lights are there in such big cities, and now if this course is done on all of us at one time, then you can paralyze us by cleaning it, white, this is a correct. Substring will be this then ignorance one and can say that now I will try to change one of the two I do something Can I create an event by changing these three If there will be one more then it will work Okay so basically I will get such a sequence Where all the people are even times on please, that and times are tight, here two is that and time is here, two is here and time is three and time is no breast cancer which has three jo in its prefix. That and the number and the times the van coming back only three, here there were three more but also two more a bit tight remove this which will make both of them ok then this is not possible now you could not do this ok can I do this Now find such a sequence Pichola in which there are two places and times and here it is and tank right if you give this much papad then the remaining portion will be left here, you can change it to kheer pantro and make the team mute 245 are two times 4455 something is clear Okay, now let's take one more task and examples and to see this we will have to change it a bit, here I have put it 13 times, I am okay, let's do 13 outside the last two times, see this till now. If there is electricity juice, then six will also come here, see from the given time, we had taken two cords before, eat this, we new this too, celebrated this too, if so many scams have happened, then it will be done, if it has to be made in just two people, then that too will be done. Remove so many ideas, now look at what has been mentioned, I will add to this also, I will also describe this along with it, any one more reason out of these will do, okay, no forward can be made in this and if we had to make another one, then we have the sequence of electricity, that. Two more number times are these and number friends and also call on four more numbers ok and if you remove the point on number times even then it becomes Lovers are going to score a lot this is three more times from this many times From and 6a torch light, if I remove so many people, then give me more number permissions and he will become the same. If I remove this much, he will become Bigg Boss 30 more times. The form here will not matter because there are not only so many fans but one. And tension, yes, it changed with the intake and it will become right, all the guys here, if there is one more guy from the given time, then you can use the SIM, okay, it is fine, but again how will I do it in the work, everyone, I have to maintain the account and keep it. When time you all type that if you do it amongst each other then it is on Sunday everyone will have to do it first consider the estate if one person has some configuration like this then switch off next switch off after doing full test such anger infection is this end square's he will go New, this is what we don't want, so now we are going to do this, now basically this circular pattern, we will make only that an accident, let's see how by using bread, so now I am going to put the states in an intermediate form like here. But I came, okay, then I have multiple with the right on the interior, here at that place, this need will be erased, intact, I am pleasing 12345 Sitam is so beautiful, okay, so here, I will have sacrificial youth, I will give them the meaning of zero, no. That element event has come, the number of one means that element and time are shadow. Okay, so if this situation had to please me at a distance of one number, then what would I have done? You are here and time has come, the tube has become yours or cotton. F-35 has been made tube has become yours or cotton. F-35 has been made tube has become yours or cotton. F-35 has been made and this is the tabs from one time which is 520, this is business, this is also zero times, one is not here even once or is it a product and does not cry, okay so all the other 10 are that point. Whatever else is inside, there is only one number here. Now see how our work gets reduced. If you represent everyone on this phone, then let me find you a CR. Friend, if you want to make all the brothers PM, then it is okay to remove these two also. Two, right now, you have to make both of them PM from Android. You need some sequence where all the even number times should be only two and three and you need exactly the same condition, tight all the people are 09 times and here one here. There is one at the same position earlier also somewhere on the set. Okay, so for now you just need to friend only one number, the interior number. If you find it at any position then your work is done. You will get this 1GB. This is one. Good excuse will be made, the other way was that and you close one, basically you have to do these two, okay here but apart from this you can do any one, so if I should do this, what I have to do is that find. Those who want to do that I am talking that these two and number lovers along with six more numbers will become time pod, the result like that will also become then good morning, the second option is if you do n't do anything else, cover it and call me now on 25 You have to point out this sequence, does it add anywhere first or not? Okay, don't do this and this also. Do this and this instead of this and here. ₹ 1 instead of these two. ₹ 1 instead of these two. ₹ 1 instead of these two. If you don't do this and this also then now it is on the ground. Come, if you say that friend, I have made one person an event, leave him alone, dial him, we are installing electricity here, I have made all of them one, it was being shut down, so it was done. It is of zero size, it has become like a hero, now one, you are making it zero, I am now more like, yaar png, such a sequence and here 3 even numbers are fine from the time, so if this let's support had come here seven times, then I am removing the audience of even number times. If I remove four then again Sarveshwari Question 19 currency will be left. Now all my efforts have come on Sachin. You just have to search this number and for this if you want. You can use an SMS which will give you the course morning of this number an inquiry into it then okay so again what do you do here you strike all the different possibilities right you have from zero to nine cactus become Okay, so keep making all of them one by one, try once to see that all are done, send the straight one easily in the same condition and secondly, order all of them one by one, you can total a tweet here. Keep doing it, just once, set it to one, this time set it to 101, set it to 120, set it to zero, make it water or make it a commo, we fold you like this, do something less, do n't discuss that. While solving it, we will discuss it, okay, first of all, it will be smooth, interior coma is 218, okay, now what will I do, see, most of you are infiltrators, because of this, it means something like this, friend, twice. This number is okay so basically 0 if you represent that I have to do it, if so then you would like me to do something like this 01 means I will search here okay so if you complete someone here then I have done it here. I will put a mark soon against 80 here - I will keep the points soon against 80 here - I will keep the points so that the rest of the work is done, then in the A map, I got up and put the gas at zero - it in the A map, I got up and put the gas at zero - it in the A map, I got up and put the gas at zero - it is closed, okay, I will not do it now, so now let's start the work. Do all the sides, let me enter the enterprise's proof and loot, first take out the character. Okay, so again, let's start now. Look, where are you going to develop till now, here is two, this point is packed juice straight, so 1000 here is Chakli, all the temples are there, okay. Okay here prostate is the method of one bitten and light or copy of four goes neither so what does he have to do he just has to toggle this plate instead of this one crazy why if it was even time before this it was 700 then now one more good Or it will become more, give one, it will be okay, if it is still on how many and in the number friend side where one is kept, if one more operation is done, then now it will become odd-even, tight, it will become zero, odd-even, tight, it will become zero, odd-even, tight, it will become zero, electricity comes then Just go to three and toggle that monkey edit and if we can do it louder okay then basically I have to do just mom I have to do some number like this have to make a mask 200 is running one two and three get the lift made The one who is the current character has one, everyone else has zero, okay, so the statement that is coming till now is pro, after running him, 2 That's why the guy stock came A state in, that's why or was on this, I went and made a mask on 1 Swift, how much is this? Bar is character - there character - there character - there is zero time, dog or worship, will do 323 and set, okay now next day Petkovich will do 18 masks, Parmarth, now whatever is straight, it is absolutely according to the current situation, from one number and time, and number times, first of all, what should I do? So here we show the list of the people who were there on representative and representation, there is one there, if I find exactly the same condition somewhere on the part, then you can completely even, tight, complete power plants can be made, these are the complete details. Pentro, this will be done, okay, so now I am going to ask everyone, do you have the exact same configuration, only the straight one will do this incident, there is no difference in it, I call it this business index, 500 yards contact with the current ID. date date date is stomach if j is equal to null then I have not found any such stand before no devotional fan you I have got straight before also ok now see the length what will happen if you are currently here at this point high on him Told that Arzoo is here so much Bichi Tej was where you are going to remove ok so I can take it from here till I but I can become these Rome side so if it is 2012 and here 3 4 5 6 Dancing Flag Afternoon August 6 So but who do I do before this, for this it will become i minus plus one, in this you have this to this one - itne bande hain one more here you will get 10 so here I have requested you Madam X N X which is not Pamma Well, I made it the highest, when all the guys even number of times, now if I can tighten the time of any one, then what will I do, one more time of all the drivers from zero to nine. Let's get a chance here by taking e world request 204 and this lu judicial commission plus again let's make meat for it that you will become mafia one I will set more number time ok now next day whose request do I have this Also we saw here if the current scenario is something like this is the current status of the show. If you have to mix all of them then you have to have tight requirements. If you have to leave one more then make any one crazy that now I am not yours. There is a requirement, bring more of this and give it, if it is different, then this guy will be more concerned about the result, all the rest will become fans, okay once I install it, I will dial it, if I open it, I will do Tubelight, now I will use the torch light. If you ask for help from , get current sports and see , get current sports and see , get current sports and see this interior of CPI(M), you this interior of CPI(M), you this interior of CPI(M), you can get it here, then it is okay and then chakli same to oo that if it is not a journal, I got it straight, then the answer is maximum. Do it okay, this work will be completed then you will get the answer, this is a written and when it is coming absolutely correct, it is presented for this test because we have not updated our pet, so basically I have done the work of current state. I have done it but as it is time, it does not have the data of my current state. It may be difficult in the future if someone else asks for my set then it is not my responsibility that I had posted zero here first in the exam. After that, whenever the current is broken, it is okay, then see once when we need to break, for example, here two is three, in this much, you are also even, still they are 221 in this, TV is okay, hence in this position. But it is 11000, okay, this is also another one, this one is also another one, okay, so for this, there are all the temples, this one must have an inactive state, 138, this one's arrangement is fine, now suppose that some person will come on Twitter who Will say friend two and remove the triangle it here ABCD is some rate here you will go on rough inducting atoms take 20123 and 576 at this point demand war 40 bring from state part ok then what will he do he will make length I - Yes like this what will he do he will make length I - Yes like this what will he do he will make length I - Yes like this Try it, if I give you all the induction in this, then it will forward the three, it will make it tight, it will make it amazing, then I - whatever is there, it will become tight, it will make it amazing, then I - whatever is there, it will become tight, it will make it amazing, then I - whatever is there, it will become rhythm, the one here which will be added on comparison will be erased from both the places, two here. There is three and here it is 123 if you give well one and keep three then the life that is right will be able to maximize this volume on this side and what do I want maximum subsequent, then we want garre ok so what am I going to do If someone is already there in this state, then leave it, but if no one is there, then enter me as 28. My direction is on this form. Okay, so here if someone has entered 1. If you come here from the city, then I will not update it, okay, I will leave it there, so here we come inside the loop, I just have a map, don't have content, a pet is equal to pause, now I don't do half an hour of content. So I run Dot Net's Against I Current in Acting in the evening and verify the torch light 10334 slogan by submitting it here and try it. All the tests on the phone are running fine with this, but still our time complexity is 158 milliseconds. This was the complete code, this is just the implementation, we are going to change it, so why is it taking so much time, then the speed and time is being spent because we are doing the work on time, if anything happens then it will be Bigg Boss, then you know. I am going to tell me how much range do I state basically varies from one to nine number is zero 12345 680 i to maximum if we talk about the rally of this whole then I can also and number one wave to the maximum is this Okay, okay, if you make anyone in this zero, then it will reduce the overall value of you. In comparison to one, I know that what is there in this is that by taking 03 and folding the state till this value. He is going to make it so deep, it is repeated again and again, he will not ask directly from the time, hey, I will check, what value is there on this state, is there any indexing, okay, this course is like taking pizza, but the read-write on it is taking pizza, but the read-write on it is taking pizza, but the read-write on it is read. And right he will get trapped so ok so come next day basically how much valley will be on the interior so what you can do is fit one 10 times then basically will set off once I am here will be considered twice I am here I will come here 10 times, this is the number of lenses that I require, here the forest officer definitely comments that he will cover all the stretches, so what do I do to you, here now instead of the map, an interview will be made, map new Cant monitor, declare it 10 times, okay, and here ma'am don't need a map instead of it, inductive, I took the shoulder, I took the torch light, now you know, if I make it an interior, if I become a teacher, now basically this The tap keeps the body full of vegetables, the colonel is lying there, okay, so instead of the date, I read the tiffin here, from that position here too, ma'am don't get it, read where are you from, okay, so right now my work is here. It is completed, we have to see this point, this platform will not be there, what can happen at this point, if I tap on the map date, then I will come here to that stage and put a static eye-sight on it now. Aayenge, everything is a static eye-sight on it now. Aayenge, everything is a static eye-sight on it now. Aayenge, everything is a total, it was a mistake, okay, so this was also not correct, 158 This 2009 Torch Light Proxy has become ten times ready, so I hope you got to learn something from this video. If you got to learn from this video, If so, please like this video and tell us in the comments. Subscribe to our channel. Thanks for watching. | Find Longest Awesome Substring | consecutive-characters | You are given a string `s`. An **awesome** substring is a non-empty substring of `s` such that we can make any number of swaps in order to make it a palindrome.
Return _the length of the maximum length **awesome substring** of_ `s`.
**Example 1:**
**Input:** s = "3242415 "
**Output:** 5
**Explanation:** "24241 " is the longest awesome substring, we can form the palindrome "24142 " with some swaps.
**Example 2:**
**Input:** s = "12345678 "
**Output:** 1
**Example 3:**
**Input:** s = "213123 "
**Output:** 6
**Explanation:** "213123 " is the longest awesome substring, we can form the palindrome "231132 " with some swaps.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists only of digits. | Keep an array power where power[i] is the maximum power of the i-th character. The answer is max(power[i]). | String | Easy | 485,1416,1885,2319 |