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
1,676
hello everyone let's solve this nickel problem lowest common ancestor of a binary fort today so many similar problems for example on 236 16451 fifty so there are always common ancestor entry one two and three so if you haven't practiced those problems you can practice some force since they are very similar questions okay for this problem uh you know that given the root of a binary an array of adrenal object nodes we need to return the lowest common ancestor of ordinal c nodes so for this problem we not only have two nodes but maybe we only have one node we may have four nodes for example in this example for node four and seven the lowest common ancestor is two for this example notice one so lowest common ancestor is one like first third example we have nodes seven six two four so lowest common ancestor is five and for this one nodes contains all nodes for lowest common ancestor is the root node which is 3. okay let's take a look as constraints some constraints are important for example all nodes are distinct and all nodes will exist in the tree okay so let's take a look at how to resolve this problem assuming we need to return the common lowest common ancestor of node 4 7 and 6 let's see like for the screen note which just returns an immediately for example four notes seven and four just return four two seven return seven two so first no two in front so something in the left there's something that writes so no two notes i'm the common ancestor of my two children so no two will return two to note five note six will return six to number five the number five fine uh there's something left there's something right so i'm the common ancestor of my two children so no five will return no uh number five to three in the right part the nothing's another one just return one pointer to no three then those three fans are in the right size and nothing but in left side and says something so i just returned the left side so no through it just return 5 which is the correct answer so the code is very similar to the code 236 for this problem we need to put our nodes into a set then in the lowest command center function uh your through this now pointer we just written on pointer if my current node is in my set i just return my card note otherwise i try to search the left path i try to search the right part if there's something in the left and there's something in the right then the card node knows that uncommon ancestor might be children so i just returned you otherwise i try to return the branch that give me something okay that's it see you next time
Lowest Common Ancestor of a Binary Tree IV
minimum-number-of-days-to-eat-n-oranges
Given the `root` of a binary tree and an array of `TreeNode` objects `nodes`, return _the lowest common ancestor (LCA) of **all the nodes** in_ `nodes`. All the nodes will exist in the tree, and all values of the tree's nodes are **unique**. Extending the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor)**: "The lowest common ancestor of `n` nodes `p1`, `p2`, ..., `pn` in a binary tree `T` is the lowest node that has every `pi` as a **descendant** (where we allow **a node to be a descendant of itself**) for every valid `i` ". A **descendant** of a node `x` is a node `y` that is on the path from node `x` to some leaf node. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], nodes = \[4,7\] **Output:** 2 **Explanation:** The lowest common ancestor of nodes 4 and 7 is node 2. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], nodes = \[1\] **Output:** 1 **Explanation:** The lowest common ancestor of a single node is the node itself. **Example 3:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], nodes = \[7,6,2,4\] **Output:** 5 **Explanation:** The lowest common ancestor of the nodes 7, 6, 2, and 4 is node 5. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * All `nodes[i]` will exist in the tree. * All `nodes[i]` are distinct.
In each step, choose between 2 options: minOranges = 1 + min( (n%2) + f(n/2), (n%3) + f(n/3) ) where f(n) is the minimum number of days to eat n oranges.
Dynamic Programming,Memoization
Hard
null
858
okay so uh need code practice time so in this video there are two goals the first goal is to see how we should solve this problem we find the solution and then we are going to put some code there and the second goal is to see how it should behave in a real interview so let's get started remember in the first step in the real interview the first step is to try to fully understand the problem if there is anything unclear please bring out the question to the interviewer and at the same time think about some ash cases so let's take a look at this question it's got mirror reflection so there is a special square room with mirrors on each of the four walls except for the southwest corner so there are receptors on each of the remaining color number zero one and two so there is square room has walls of lens p and the laser ray from the southwest corner which is this corner first meets the east wall which is this wall at distance q from the zero from the zeros receptor okay so return the number of the receptor that the right needs first it's guaranteed that the ray will meet a receptor eventually so let's take a look at this example we have ps2 qs1 and we have the output s2 so the reason is okay so the p here is 2 so the length of the mirror wall is 2 and q is the distance from the receptor uh from the first from the zeros receptor uh okay so this so the distance from the zeros receptor is one so the reflection point the distance between the first reflection point and the reception is q which is one and uh okay so this is a trace of the laser all right so i think we understand the problem we are just trying to find which receptor uh it is going to receive the laser finally all right so the next step is about finding solution so how to solve this problem so honestly um i thought about this uh for quite a while and also i searched a bit on the internet and finally i found a very good explanation about the solution so let me use some graph to explain what it is so the first of all um i need to introduce a concept which is called relatively prime so if so for example if p is 4 and q is 2 and this is the trace of the laser it is the same if we just shrink it uh to like well to ps2 and qs1 so it's the same effect so what we could do is we could just shrink it and make it smaller and finally make p and q to be relatively prime so that way it can use our computation in the next step so in the next step we will try to find the trace we'll find try to find the trace of the laser so let's define the blue uh blue thing as the real world and the yellow one as the word in mirror so we will see that um we are going so after the first reflection we uh we are in the real world and the second reflection point is actually in the mirror world so this part is p and this part is q so we will find because p and q are relatively prime so you see that uh we will and so when we end up at the reception point we are ending at the cubes world so this is uh the first world the second world and the third world so we so this is q so we are ending at the q's world with p reflection uh is it true yeah so we are we have p reflection and we end up in the qs world because uh because this is p and this is q and they are relatively prime oops so we are having uh we will have so uh for the final thing for the final point when we need the reflection it'll be some something like we go pq about this distance so we are all right so we are ending at the qs world and we have piece p we have we will end at q's world with p reflections so this will give us a very good story so if the q is a out number so if a q is the odd number then we are actually in the real world so if q is even number we are at the uh we are at the mirror world so the p reflection give us um the idea how much how many times it reflects because each reflect is going to change the direction of the laser and it will give us a different reflection point so as long as you know what which world we are at and how many times we reflect we can easily use that information to compute which reception point is going to re is going to receive the final laser so let's do some coding here so the first one we need to find the gcd for p and q so we are going to have so okay so after you're done with finding the solution part it's time for us to do some coding so for coding we care about the correctness the readability and also the speed so we have the defined gcd p and q and the thing is if q is equal to zero then you return p otherwise we will return gcd this is q and p modular q let's see so q is between zero and p is between one the hundred so if okay so q is like this if q is equal to zero then you should just return zero i think which is a uh i would say this is a ash case uh we need to think specially if q is equal to zero then we need to return uh return zero so otherwise we will compute the gcd uh so you compute the gcd let's say gcds is equal to gcd uh p and q and we have p d y equal to g c d q do i equal to g c d um so after that we have the p and q as uh relatively prime numbers so you say if so in the q's word if q is equal to so if q is equal to the modular two as equal to zero that's an it's one world otherwise it is the other world so if it is an even number then so if it is an even number so for example this is so if it is even number so for example this is two and uh this is three so this is three and this is two we will end up having so let me draw something so if it is two three and two uh so this would be uh two again this would be two again so we will end up at the q's so we will end up at the mirror world so if q is an even number we will end up this is a narrow world so in the mirror world we should just return zero otherwise it is uh it is a real world so if p is a odd number so let's say if p is equal to so the q is the odd number let's say p is equal to two and the q is equal to one we end up at the real world so i'll say uh if p is a odd number because we have the re so if we have the reflection like p times so if it is a if it is an even number if p is even number then we should have returned two like for example if p is two and q is one then we should return two so otherwise we need to return one so for example p is three q is one they reflect so we have ones once and once so this three times so you're going to return one finally so that's pretty much about the code let's do some testing so for testing usually you need to go through some simple tasks and explain how this piece of code is going to work uh let's use let's say p is equal to three and q is equal to one so for the gcd we are going to have three and one so we are going to finally we are going to return one for here um yes so finally we are going to return 1 and gc after we compute the gcd and then we divide the gcd then ps3q is 1 still so because q is e code q is not an even number so we step into this part so p is not a uh even number as well so we are going to return one so it's the same it's something like this once twice and the third so i think it works well for some simple examples uh let's give it a shot by run this piece of code okay so it seems good let's do a submission okay so everything looks good and uh we are done with this problem so if i if you have any question about this solution or about this problem feel free to leave some comments below and if you like this video please help subscribe to this channel i'll see you next time thanks for watching
Mirror Reflection
masking-personal-information
There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered `0`, `1`, and `2`. The square room has walls of length `p` and a laser ray from the southwest corner first meets the east wall at a distance `q` from the `0th` receptor. Given the two integers `p` and `q`, return _the number of the receptor that the ray meets first_. The test cases are guaranteed so that the ray will meet a receptor eventually. **Example 1:** **Input:** p = 2, q = 1 **Output:** 2 **Explanation:** The ray meets receptor 2 the first time it gets reflected back to the left wall. **Example 2:** **Input:** p = 3, q = 1 **Output:** 1 **Constraints:** * `1 <= q <= p <= 1000`
null
String
Medium
null
146
day 24 lru cash it's one of the most important questions and it's asked very frequently in many programming interviews so let's see how we will implement it first let's understand the lead code problem which is problem number 146. in general the api that the client wants for is to access the keys they may not necessarily want to put keys this put is something which can be internally uh used by the cache but the problem in lead code asks you to implement a class lru cache which will have a capacity so maximum that many elements can fit into that cash lrucas and you need to implement two methods one is get so user will just get the key if it's in the cash uh it will return from the cash if it's not it will return uh you the key uh the value and also it will put that key into the cash so that next time you access this key it's accessed from cache and you also need to implement put method so here you need to pass key and value the user of this code and your task is to put this value under this key and lru means list least recently used and generally the name of gases comes from their eviction policy every cash has some capacity and they are not as big as the memory but they are smaller than that so they have to keep some capacity and they there need to be some eviction policy uh on what basis you will pop the elements so here the eviction policy is least recently used so you have 10 keys that have been accessed now you have n capacity only and now user accesses a key which is not present here so you need to insert this latest key also in the cache but you have support for 10 keys so what will you evict which key will you remove so you will remove the least recently used that is the key that was accessed 10 steps 10 time steps ago so whatever is the last or least recently used item in the cash it may not be exactly 10 time steps because let's say this first key is accessed again and again so this will itself be accessed 10 times ago but whatever is the nth element least among these that are present in the cache so for example let's run through this example initially the cash is empty and for our case let's say the capacity is 2 so first time we put 1 so key is one value is one so we have one now our size becomes our count becomes one then we put two so size becomes two now we want to get one so one is present here so it should return one so it returns one and one is the latest earlier two was the latest key since we put it this was the last key or the most recent key uh now when we access one is the most recent key so one is here two is here we will keep the most recent in the beginning now we want to put three but our capacity is 2 size is already 2 so we have to remove one of them so this is recent this side is recent so we will remove 2 and put 3 here now 3 is the recent one now we want to get 2 but 2 is not there in a cache only a space for 2 so we return -1 only a space for 2 so we return -1 only a space for 2 so we return -1 so all the key values will be positive this has been said in the problem statement so that you can represent uh return something when the key is not found so you will return minus 1 in that case now you want to put 4 so you put 4 in the beginning so this is the most recent and one is removed then you get one is not there so you return minus one and uh get three so returns three get 4 returns 4 so that's it so let's see how we will implement it so we there is a standard uh algorithm for this you have to implement both of these in order one time that is constant time so uh so how you can get key in order to get you have to return it in constant time so naturally something comes to your mind that i will keep a map where i will have key and some value because map allows you hashmap allows you to get or access key in constant time so you will have map but how will you maintain the ordering that is you have to remove the least recently used this map will not have ordering although some languages like java has some high-end version of hashmap has some high-end version of hashmap has some high-end version of hashmap called linked hash map which also remembers the order in which elements were inserted uh so if you iterate the elements the order is guaranteed it will be the same order it was inserted on the other hand hashmap does not guarantee the order of access simple hashmap similarly in python we have order predict which is very similar to this linked map so it's different from normal dictionary but in c plus we have the normal unordered map normal hash map so we will additionally use a linked list data structure or which will act like a queue so you keep inserting in one end and you remove from other end which will denote the least recently used and we will use one has map and java and python internally implements this so we will see the code of all of the three languages so let's see how we will do it in c plus first but let's forget about the language even these would internally be doing something like this so we have a linked list or a list and a hash map so we put one here let's delete it there is no node we create a node we put one here and let's say this side is the most recent so one is the most recent then we put two so two will be inserted here two is most recent and capacity is two now i want to access one we also put here one and two this will also have always this many elements if we remove from here we also remove from the map so that there is a consistency between linked list and map and what do we store as value let's say i want to insert three so i want to insert three then i have to remove this so i will remove the last and i will also remove it the key from here that is simple so removing is trivial you can access the last element of this list and remove that and also remove it from the map so that will be done in order on one when you want to remove something and remove will be used during put not during get because during it you don't need to remove anything so during put removing is easy and putting is also easy you put in the beginning but when you are accessing get some key then getting it from the map is order one fine but that key may be in the middle of the list somewhere in the middle here i am taking example of 2 that is not a good example so let's say this key is here so we got the key in the map but how do we bring this key to the front because searching in list will take order and time if you do it like this so now you understand why both are important map and link list because you need the ordering you need to remember the ordering eviction policies to evict the least recently used element so that can be done in list or queue or similar data structure but then problem with list is that accessing would be order n time on the other hand if you look at map accessing would be order one but ordering information is lost here we don't remember the ordering so we need both of these so how we will pair them so we want to access a key let's say it's five it's somewhere in the middle so we see in the map and we get it in the map and we can return it now our second task is to move it to the front because it was used very recently so we need to somehow store the value and also the position where this element is in the list so you keep track of not just value but also position in list both the things so key is one integer value is a pair of the value corresponding to this key and the position in list and this is required so you get the key you return the value to the user you also get the position you go directly to that position in the list and you bring it forward so in c plus we will be storing the iterator the list iterator and in java and python we will not uh need to keep track of these ourselves we will be using linked hash map and order dict so let's begin programming first in c plus first so we have to first implement the constructor so let's keep the private member variables we will need a capacity let's call it capacity then the list we can call it keys and then unordered map first the key is integer and the value is a pair of integer which will denote the actual value that we put using this function and the second will denote the position in list where that key exists so for this we will use the iterator of same type whatever is our container for keys and let's call it map we can also call it cache then in constructor we can member initializer list we can use or it's eq you can write it here also capacity equal to capacity now let's implement the get so we will only return a value when it exists in the map or the list if it doesn't will return -1 or the list if it doesn't will return -1 or the list if it doesn't will return -1 so if map dot find key not equal to map dot end so this is the case when key is found so when the key is found in the map or the list what we will do before returning we need to move that key to the beginning of list and also this map is holding the position of that key in the list so we need to update this also so let's do uh keys dot push so we have to remove this from the list first then only we will push in the beginning so let's remove it keys dot erase and what is the position that we want to erase from the map get key this will return this the value which is a pair and now the position will be the second element of that pair dot second so we will remove that now we have to put it back in the front keys dot push front so now this part is done so we have removed from that position and put to the beginning of this list now we will update the same in map and then we return map key and first is the actual value oh i have wrongly put this here so if the key was found then we did these things moved the key to the beginning then updated the map if the it does not find the key we will return minus 1 so we have implemented get let's remove this it's causing confusion ok let's implement the put now so the same check if we are putting something if that already exists we will move it to the front if it does not exist we will insert in the beginning so let's do that this part should remain same so we remove it we move it to the beginning and then map key equal to the value and keys dot begin else if it's a new key we need to check the capacity in this case capacity does not matter because it was already present we are just moving it to the beginning but if we are inserting a new element a new key that is the key that was not existing we need a capacity check if keys dot size this greater than check is not required you can do with equality but let's add it does not arm or let's remove it uh it's greater than capacity or equal to capacity then we have to remove it remove one element so front of this keys denote the recent back denotes the least recent so if size is equal to capacity we remove one least recently used now irrespective of that so we have decreased the capacity by one here beforehand and if it was already less than capacity then we it will not enter this code and it will simply insert in the beginning and we are done so let's try it out it works for this case and looks to be a good case let's go ahead and submit so our solution is accepted now we will uh write this in java and here we will use linked hash map so we will not need this list it will keep track of the ordering itself you are uh you can also implement it using the same way you just use the hashmap instead of linked hashmap that would be a good exercise but here i will use linkedhashmap so let's keep some private variables which will be the capacity and then linked has mapped now we will add the constructor so capacity equal to capacity and map equal to new constructor is done let's implement the get the same way if map dot contains key then get the value remove it why remove it because this map is not simple map it remembers the order in which it was inserted so first we found it somewhere in the middle then when we remove it's removed and we have to put it back so then we will just put it back it will be inserted in the front that is the as it will remember that this key is the most recent one so it will automatically take care of everything you just need to remove it and insert it back so the ordering will be automatically maintained so remove it and then map output t value and return the value that we fetched from this and if it's not there return -1 so this takes care of return -1 so this takes care of return -1 so this takes care of everything now let's implement the put so if map dot contents key if it contains key then we have to remove it from there and put it in the beginning the same way what we did in c plus only thing is that here it's much easier due to absence of list so map dot remove key and if it's not there in the map then it's even simpler you just put it in the beginning and also check the capacity so if it contains the key already no capacity check just remove it and in the end we will put it back so i am not putting it here because this will be common to both the cases we have to put it back in hand so for clarity let me write it here then we will remove it map.put key value if the key is present we remove it put it back it will be removed from some middle position and put in the beginning that case is done what will be the second case if it's not present in the map then we are inserting a new element so capacity check is required so if capacity is equal to capacity or can this capacity and this we will get from the size map dot size so we have to remove the first key that was inserted the way to get is map dot key set it will return you the set of keys and you have to use the iterator dot next this will give you the iterator to the first key that was inserted so you have to remove that and you have to also put it back and you will notice that this part was common so we put it outside and this is done so let's try it a key value map output line number 14. it's well now it works so let's submit so this solution is also accepted in java now finally we will implement it in python so we will init with two things capacity same as java and this solution is much more similar to java than c plus because we will be using order dict which also remembers the order in which keys were inserted if key in self dot map exactly same as java in fact value equal to self dot map dot pop so this will pop and also return the value and then we will push it back else return -1 next we will implement put or else if uh length of this is equal to capacity then we have to remove the first key and by default it will be true last equal to true where it will follow last in first out so you have to write four false here so this will mean fifo so if you don't put this default value default it will be true so when you pop an item from this map this order dictionary it will pop the last item the recently item that was pushed so if you write it false then it will pop the first item that was pushed so it will follow fifo and we are using fifo first in first out so the one that was inserted in the beginning will be popped out here so let's try it out and it works in python so let's submit and the solution is accepted in python as well
LRU Cache
lru-cache
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`. * `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key. The functions `get` and `put` must each run in `O(1)` average time complexity. **Example 1:** **Input** \[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\] \[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\] **Output** \[null, null, null, 1, null, -1, null, -1, 3, 4\] **Explanation** LRUCache lRUCache = new LRUCache(2); lRUCache.put(1, 1); // cache is {1=1} lRUCache.put(2, 2); // cache is {1=1, 2=2} lRUCache.get(1); // return 1 lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4 **Constraints:** * `1 <= capacity <= 3000` * `0 <= key <= 104` * `0 <= value <= 105` * At most `2 * 105` calls will be made to `get` and `put`.
null
Hash Table,Linked List,Design,Doubly-Linked List
Medium
460,588,604,1903
790
Hello Everyone and Welcome End Limited Tiles You will get some more space, here its length will be told to you that let's man do, there are ways by which you can fill this space with these dialogues like now here's the length The length here is three, so here I have to place one tile, so I can do it like this, you are of cross van, this is you of cross van, right, remove this part ahead of nine so that it is okay. So first of all, I have this tile, I can make it stand like this, take one, this one space is filled, this is empty, fill one such tile in this too, fill this one tile like this, do this, so this is filled, right total This is the first method, in this way I picked up these van size tiles, you pick up the cross van size ones, sorry , then I can do something like this, one tile, put it like this, done this. Ways are done, we found one more way, what can be a magazine, total three ways, how many ways come out with style, okay, how can we fill this space by picking up this one domino over here, this one Put it like this, I am the first red winner, this one over there, like this, make this one cry, I can do this lesson in something like this, there are total five ways, if I have our answer, in the discussion of this first one, you see, tell me how many ways you can You will be able to fill the space using these two dialogues. This is our question. Now let us formulate our question. This is a question of DP, so basically it will be what is late to late, you have to calculate DP of N. We will need something here, previously we have given some answers. Let's calculate that you got cross 10 from let's. Tell us the answer till ninth. Let's know from let's know how to get TP of 10 in this method. You have to find out how to do that. Okay, let's start with one less. Let's do this from this crash and try to understand that how will we get the DP of N right using the previous calculations which we have done and the previous answers have come out. Now what can we do? One way is as we try to understand. If you get a cross van late then what do you do, there is only one way like this, now let's talk The way you are applying the same thing, the second one you apply it like this, there are five ways = in 3 There is only one method at this five ways = in 3 There is only one method at this five ways = in 3 There is only one method at this point, there are five methods on this, now let's talk and discuss. For N = 4, discuss. For N = 4, discuss. For N = 4, whenever you have to get N = 4, it is 1234. We have to get it, so what can we do, if the old methods are given. In this way, DP of Van can be found, what can we do, all the ways in which you can complete this and all the ways in which you can fill the women here, you can fill the plus in two ways, right, you saw that Two ways, so many ways, in this way some answer will come that you have to get DPR N from LED, you have to find out what happened, then its formula will be that you get DP off and mines van, plus DPS and mines, you get it plus you in DPS DP. Off n mines will be able to mine one plus tu tak jaaga DPS zero tak sab mein multiply by tu rahega main inko sabko Equal tu DPR se ke up tu zero tak hai na and this is the part we had to nikla di PFN So what happened was, take the first two terms as a single, take the last key, multiply the rest and see, right DP. Now when I have to get n - 1, then the DP. Now when I have to get n - 1, then the DP. Now when I have to get n - 1, then the starting two terms will be single, dba n - 2, dba n - 3, the remaining dba n - 2, dba n - 3, the remaining dba n - 2, dba n - 3, the remaining terms will be What used to happen, you come twice in N - 4 5 / 0. If it happens then I will in N - 4 5 / 0. If it happens then I will in N - 4 5 / 0. If it happens then I will combine these two and get DP of N - 2 DPS N combine these two and get DP of N - 2 DPS N combine these two and get DP of N - 2 DPS N - 3 and the rest which is remaining, - 3 and the rest which is remaining, - 3 and the rest which is remaining, how can I know all these three DP of N. - 1 I can write -1 and basically it becomes The P of N - N - N - 3 + DP of N - 1 I 3 + DP of N - 1 I will make this one out, let's reduce it to the code part, whenever I am making us into one, that is What do I have to do to get DPS N? DP of N - 1 is required 2 * DP of N - 1 2 * DP of N - 1 2 * DP of N - 1 What will be the formula I can write for this that if N make it less equal then simply return one if one is one then return one. Another thing we can do is we know the value of n is three so it will return five right we can do something like this Let's create a DP let's create these objects okay so we have to calculate okay one extra size And we know that van is equal to dpf2. Correct, this is done. We have to return by taking plus. Let's make a mode above somewhere. 1234567 We will do the complete calculation ] submitted
Domino and Tromino Tiling
global-and-local-inversions
You have two types of tiles: a `2 x 1` domino shape and a tromino shape. You may rotate these shapes. Given an integer n, return _the number of ways to tile an_ `2 x n` _board_. Since the answer may be very large, return it **modulo** `109 + 7`. In a tiling, every square must be covered by a tile. Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile. **Example 1:** **Input:** n = 3 **Output:** 5 **Explanation:** The five different ways are show above. **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 1000`
Where can the 0 be placed in an ideal permutation? What about the 1?
Array,Math
Medium
null
969
hey guys welcome back to another video and today we're going to be solving the leeco question pancake sorting all right so in this question we're given an area a with integers and we need to sort it so the way we're going to sort it is by using something called they call pancake flips and in one flip what we need to do are these steps so we first choose an integer k and k is equal to or greater than zero or less than the length of our array and we reverse the sub array so let's say we have a k value of two we're going to uh reverse everything including zero uh index first index and second index so for example over here a equals three two one four and what they did is they chose a value of two so let's look at that index so in this case zero one and two so that includes the elements three two and one so what we're gonna do so as you can see over here three two and one we're gonna reverse that so when you reverse three two and one you get one two and three so reversing that you get one two three and four so that's what happens when you flip it at a value of k is equal to two okay so we return an array of the k values of the pancake flips that should be performed in order to sort a any valid answer that sorts the area within 10 multiplied by a the length of a will be correct okay so there are several different combinations and ways that we can do this but i just want to go through the most intuitive way that i came up with and that probably you're thinking of about as well okay so for this i'm gonna be using the same as uh same values as our example so our example over here is three two four and one okay so that's gonna be our input three comma two comma four comma one and we need to sort it so let's see how we can do that and just to show you in our example over here they actually did that in four steps so that's probably the most optimized way hours is not going to be that good but still going to give us the correct answer at a pretty good time okay so we have the that's our input and now we're going to have our output and this is basically going to be all of our k values so it's just going to be an empty list and we're just going to keep adding values to it all right so let's start off with our input over here and our goal is to sort it so there's several ways we could sort it but the most intuitive way that i came up with or that i thought of was that each iteration we're gonna move whatever the largest element is to the ending so in the beginning what is our largest element so three two four and one and well four is the maximum and our goal is to move forward to the ending so there's quite a few ways we could do that but a way which will work all the time is this one so what we're gonna do is we're first gonna move four to the beginning and then we're gonna reverse the entire thing so let's see how that works so over here where is four at four is at an index of two so we're going to reverse everything starting from the zeroth index up to and including the second index so this is at a k value of three so let's add that to our outputs and let's reverse this so we're gonna end up having four comma two comma three comma one okay and after this we're gonna reverse the entire thing so that's gonna give us a k value of four and when you reverse the entire thing we're going to end up with 1 comma 3 comma 2 comma 4. so if you notice over here we know for a fact that the last element is in place we got the maximum element in its correct place and we're done so four is in its place and we can kind of just ignore it from now so i'll kind of just draw like an imaginary line just saying that four is in its place so just ignore it from now on so what we're gonna do from now we're just gonna include everything to the left of that imaginary line so in this case that's going to include one three and two so the same steps again we're going to take the largest value which is three and then what we want to do is we want to get it to the beginning so in this case that we're gonna end up reversing these two elements giving us three comma one comma two comma four okay and where did we do the flip we did the flip about at the k value of two so we did that over there and after we do this we want to reverse the entire thing but over here you want to notice that we're not going to reverse all four of these elements instead we're only going to reverse everything to the left of this imaginary kind of line so we're just going to reverse 3 1 and 2. so that's going to give us a what 2 comma 1 comma 3 comma 4. so after this we have two elements in its correct place so right now the element 4 is in the correct place and 3 is also in the correct place so now we can move our imaginary lines so let's say it's over here so everything to the right of this is in the correct place everything to the left might be in the correct place but we don't know for sure so let's just continue with this process and i forgot to add over here this over here is going to end up having a value of three since we've reversed everything from there so three comma four comma two comma three okay so let's just go through this real quick so over here we have two comma one comma so over here we have two one three four but we only want to focus on two and one so what is the maximum element well it's two so actually two is already in its correct place so what's going to end up happening is that we're gonna start reversing it or we're gonna do the flip at a value of one so k is gonna be equal to one so when that happens nothing's actually going to change so we're gonna add the value one and now we're gonna flip everything to the left of that imaginary line so when you flip that's at a value of two and we're going to end up getting one comma two comma three comma four so this is actually completely uh done so we're completely done by sorting it but just to kind of go through the entire process our image so now two three and four are in place so for one we're gonna reverse it at a k value of one so then in that case it just stays the same one comma two comma three comma four and after that we're going to reverse everything to the left of that imaginary list which again it's just gonna stay the same so we're gonna be ending up with one comma two comma three comma four but we also need to account for that reversing so in the ending we have this and this over here is our answer so 3 comma 4 comma 2 3 1 2 1. so this is one of the valid answers there are several different valid answers if you go back to our example over here uh their answer is four comma two comma four comma three which at the end of the day we still get the same results and we're also following the conditions which is any valid answer that sorts the array within 10 multiplied the length of the array so we're good in that way so now let's see how we can actually write this in code all right so let's start off with our code and over here we're going to have about a variable and i'll just call this x and it's going to hold the length of our array and the reason we're actually holding that value is because we're going so the imaginary line that we were talking about we're going to use this x value to kind of implement it okay so after that we're going to have a list and this is going to be what we output and i'll just call it the k uh so k all the k values or k flips that we're going to make okay so now what we're going to do is we're going to iterate through everything all of the index indices inside of our array so for index in range length of a actually instead of calling length of a we can just call the x variable over here so i'll just call x over there okay so now we're iterating through everything inside okay so now we're iterating through all the indices in our array and what we're gonna do is our first step is to find what the maximum value is so i'll just call this variable max underscore and we want to find the maximum value of our array but what this does it's going to find the maximum value of our entire area but we don't want to do that we want to just find the maximum value of everything to the left of that imaginary line that we had so to do that we're going to index through everything and we're going to stop at the value of our x value minus the index and sorry over here for index in range okay there we go okay so what this is going to do is in our first iteration we're going to have x minus 0 right and each time so that means that the imaginary line is kind of at the ending and each time the index value increases by one so at the same time the x minus index value is gonna decrease by one each and every time so what that means is each time we're setting so first we have the biggest uh element in place then the last but one element is in place and so on and so forth until we reach the very first element so now we want to find what index this value is at so i'm just going to call this max index and to get what index it's at we can just do a dot index and what value do we are we looking for is the max value so this is going to give us where that maximum value is so over here what i'm going to do is i'm going to add a number one because we want to make k flip so to store the value k so k is actually whatever our index is plus one right so for k we start counting at one two three four but for our index is zero one two three so that's why i'm just adding one and it's going to make our further calculations easy as well so now we want to reverse everything until and including our uh maximum value so to do that's why we added the value one over here so we can directly just index from everything up to max index so that makes it a lot easier for us and all we're doing is we're going to reverse this so i'm just going to copy this and now we're just going to reverse it that's all we're doing over here and after we do that we're also going to append this to our k list so k dot append and we're going to append our max index okay so that should be it and that's the so that's kind of doing the first part which is we currently did this part over here and now we want to do this part over here which is reversing the entire sub area right and to reverse the entire thing what we're going to do is we're going to take a and we don't want to reverse the entire thing we just want to reverse everything up to that imaginary line so to do that we're going to do uh iterate through everything until x minus index so it's the same logic that we're doing using over here and same thing over here so we're just going to end up reversing it so reverse i'm just going to copy this over here and put this over here so now everything is reversed so in the first iteration the largest element would be in place by now okay so after this we also need to add this to our k list so k dot append and the value we're appending is this value over here so i'm just going to copy that x minus index and paste that over there and that should be it so we're going to iterate through each of our values and at the end and at the ending of this we're just going to return our k list so let's submit this and let's see what happens and as you can see our submission did get accepted and finally thanks a lot for watching guys do let me know if you have any feedback or if there's any specific legal questions you want me to solve and don't forget to like and subscribe if this video helped you thank you
Pancake Sorting
number-of-recent-calls
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**. In one pancake flip we do the following steps: * Choose an integer `k` where `1 <= k <= arr.length`. * Reverse the sub-array `arr[0...k-1]` (**0-indexed**). For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`. Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct. **Example 1:** **Input:** arr = \[3,2,4,1\] **Output:** \[4,2,4,3\] **Explanation:** We perform 4 pancake flips, with k values 4, 2, 4, and 3. Starting state: arr = \[3, 2, 4, 1\] After 1st flip (k = 4): arr = \[1, 4, 2, 3\] After 2nd flip (k = 2): arr = \[4, 1, 2, 3\] After 3rd flip (k = 4): arr = \[3, 2, 1, 4\] After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted. **Example 2:** **Input:** arr = \[1,2,3\] **Output:** \[\] **Explanation:** The input is already sorted, so there is no need to flip anything. Note that other answers, such as \[3, 3\], would also be accepted. **Constraints:** * `1 <= arr.length <= 100` * `1 <= arr[i] <= arr.length` * All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`).
null
Design,Queue,Data Stream
Easy
null
1,637
okay so we have our points and we'll sort our points um and we only care about uh the first number which would be the x-axis okay so now we have sorted points x-axis okay so now we have sorted points x-axis okay so now we have sorted points now we're going to say let um max difference I mean that's really what it is actually I don't need to do that um let's start with an index of one so we can Okay so let's say cons difference equals um the going to be in order um so we're looking at points I just the x minus points IUS one just the X and then we're going to say Max difference equals either I already have the max difference or I just encountered the max difference okay so that should be the solution uh we sort our points um we're only considering the x-axis we have a Max difference x-axis we have a Max difference x-axis we have a Max difference reiterate through all points we start with um the second point and because we're comparing from the point prior okay so in this case um we would receive this input okay after sorting I would have okay and then measuring difference then I would start here and I'm measuring um 8 - 7 which is 8 - 7 which is 8 - 7 which is 1 so my new Max difference would be 1 9 - 8 1 it doesn't change and then I - 8 1 it doesn't change and then I - 8 1 it doesn't change and then I return one okay in this case here this would be my input my sort would be like this and I start here so um difference of zero difference of two so now my new Max difference is two difference of three so now I have a new Max difference of one so I return three all right so I think this is the solution that worked
Widest Vertical Area Between Two Points Containing No Points
string-compression-ii
Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._ A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the maximum width. Note that points **on the edge** of a vertical area **are not** considered included in the area. **Example 1:** ​ **Input:** points = \[\[8,7\],\[9,9\],\[7,4\],\[9,7\]\] **Output:** 1 **Explanation:** Both the red and the blue area are optimal. **Example 2:** **Input:** points = \[\[3,1\],\[9,0\],\[1,0\],\[1,4\],\[5,3\],\[8,8\]\] **Output:** 3 **Constraints:** * `n == points.length` * `2 <= n <= 105` * `points[i].length == 2` * `0 <= xi, yi <= 109`
Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range.
String,Dynamic Programming
Hard
null
1,171
hello guys welcome back to my YouTube channel today I'm going to solve day 12 for from of this month on Le code if you guys haven't subscribed my YouTube channel yet then please go ahead and subscribe it now without any deay let's get started with today's problem so today uh we are going to solve problem number 1171 that is remove zero Su consecutive notes from link list okay so in this problem we have given the head of a link list and we have to delete the consecutive sequences of nodes that sum to zero until there are no such sequences after doing so we have to return the head of the final link list okay so here in this example one this is a head given to us okay so here from one I go to this next note two what is the sum my sum is three right after this sum three I go to next note so now my total sum becomes zero Okay so here uh make a note of it that I am adding okay so every time my sum should increase but if my sum uh becoming zero here then I have to just delete the delete these no nodes right I have to just delete these nodes and now my new head is going to start from this three and one okay so I'm going to print the output like this okay so this let me uh copy these three examples here and paste it here okay so see here so from one uh let's take one dummy node so I'm going to take one dummy node initially and that dummy node value is zero okay and I am going to point this dumy node to the my to the head of my link list okay and here I have pointed the Domino to my head to the head of my link list after that I'm going to perform the sum okay so here what is the sum 1 + 2 sum is three and what is the sum 1 + 2 sum is three and what is the sum 1 + 2 sum is three and when uh I add this sum three with minus 3 then my sum becomes zero okay if this is the case then I'm going to point this dummy node directly to this one and after that again I'm going to perform uh the sum operations okay so after that three I'm going to again perform the sum so my sum is four so it is not zero okay so we are good so now once uh I get the sum as zero I have to delete all these nodes okay I have to delete all these noes okay so here I have deleted all these nodes and now the I'm left with these notes zero Z is pointing to three is pointing to one and in the end I am going to just return dummy do next okay so here from here my head is directly pointed to this three okay so I am going to explain this in detail with uh one more example okay but uh let's understand this problems example because these all pro these all examples are very simple okay but I'm going to explain this with some complex example okay so here uh same way in this example you see initially I uh took one D or 0 is pointed to the head of Link list and here see uh 1 + 2 is 3 + 3 is list and here see uh 1 + 2 is 3 + 3 is list and here see uh 1 + 2 is 3 + 3 is 6 right 6 and then uh 6 - 3 is 3 and 6 right 6 and then uh 6 - 3 is 3 and 6 right 6 and then uh 6 - 3 is 3 and then 3 + 4 7 so right now nothing I then 3 + 4 7 so right now nothing I then 3 + 4 7 so right now nothing I haven't deleted anything because the total sum is 7even and it's not zero right now after that I'm going to start from this SP from here to here okay previously I started from here to here right some now I'm going to start from here to here from this two 2 + 3 5 - 3 here to here from this two 2 + 3 5 - 3 here to here from this two 2 + 3 5 - 3 2 + 4 6 so I haven't deleted 2 + 4 6 so I haven't deleted 2 + 4 6 so I haven't deleted anything now I am going to start from here this three 3 - 3 is zero okay it is here this three 3 - 3 is zero okay it is here this three 3 - 3 is zero okay it is zero now so right now I'm going to just point this two to this four okay I'm checking from this three now okay so 3 - checking from this three now okay so 3 - checking from this three now okay so 3 - 3 becomes zero so I have to just move the next give the next of this two to this four so now my new link list is like this 0o 1 2 and four okay so one by one uh one by one I'm checking the sum okay here also from zero I have started 0 1 sum 3 sum here 6 sum and 6 - 3 sum here 6 sum and 6 - 3 sum here 6 sum and 6 - 3 is uh 3 and then 3 - 2 - 1 so I haven't is uh 3 and then 3 - 2 - 1 so I haven't is uh 3 and then 3 - 2 - 1 so I haven't deleted anything here now I'm going to start from here so 2 + 3 5 - 3 2 to start from here so 2 + 3 5 - 3 2 to start from here so 2 + 3 5 - 3 2 - 2 0 so I have to delete everything - 2 0 so I have to delete everything - 2 0 so I have to delete everything here so now my uh node is like this 0 1 this is pointed null only okay so I have to just return dummy not next so here this is output okay so this is how I'm going to solve this problem so now let me explain it with some complex example so that you will get guys will get the clear idea okay so let's say uh this is a link list given to us so initially five okay initially five is there and then my five is pointing to uh minus 3 okay then this - 3 next is -4 minus four next is 1 One's next is 6 and 6 next is min -2 and minus 2's next is five okay so -2 and minus 2's next is five okay so -2 and minus 2's next is five okay so let's take this example okay so first I am going to take one dummy node so my dummy node is let's say zero so zero is my dummy node and this zero Zer is my D node okay this zero is my d note this Z is my dummy node and this dummy node is pointing to the head of my link list so this is the head of my link right so this is the head of my link list so this dummy node is pointing to the head of my link list right now okay this is done so now let's take the current element currently list note current is this dummy okay this is my current now after that I am going to run one y Loop okay in the while loop I'm going to check if my current is not equal to null so right now my current is not equal to null it is at this place zero node right so if my current is not equal to null inside that I'm going to initialize initially my sum is zero right initially my sum is zero this is what I'm checking inside the Y Loop okay so now I am here writing inside my by Loop while my current is not equal to null okay then I am going to uh check for this y Loop in the Y Loop initially I am starting initializing my sum as zero int sum is equal to zero and here the temp node is my current do nextt okay so this current do nextt is five right so damp node is my current. nextt this one so temp node is my current. next current dot next okay and my previous node is my current so my brief node is nothing but my current so that simply means that my PR is pointing to this zero right now okay so now inside this y loop I am checking if my sum is equal to zero but after performing the sum with uh this sum with the temp value okay so here let's perform the sum one by one okay so now I'm using this blue color pointer okay so sum is zero initially now I'm going to add the sum Plus St okay I'm going to update my sum values so I'm going to update my sum values as sum is equal to sum Plus temp do value temp dot value okay so this is how I'm going to perform some so sum plus temp dot value here uh it's nothing but 5 - 3 is 5 - 3 is 5 - 3 is 2 and 2 - 4 is -2 - 2 1 is -1 -1 + 6 is 2 and 2 - 4 is -2 - 2 1 is -1 -1 + 6 is 2 and 2 - 4 is -2 - 2 1 is -1 -1 + 6 is 5 - 2 is 3 and 3 + 5 is 8 Okay so nowh 5 - 2 is 3 and 3 + 5 is 8 Okay so nowh 5 - 2 is 3 and 3 + 5 is 8 Okay so nowh I here nowh I have found the sum zero okay so I didn't perform anything so here my sum is eight so I didn't find um sum as zero so in total uh sum is eight now so what I'm going to do I'm going to move my curve to the next pointer okay so now my curve is going to move forward okay so curve becomes curve. next so this is my new curve okay so now let me erase this part so now this becomes my new Cur okay so this is done C isal C next now again I'm going to check if my Cur is not equal to null so my Cur is not equal to null right now okay if it's done now inside that I going to again initialize my sum as zero okay and now my temp becomes curve do next that is this three okay so right now my temp is point to this value right C do next so let me erase this one okay this is done and my PR becomes curve okay so simply means that my brief is pointing to this five now right so this is done now listen it carefully here so let me erase this one okay so now my temp is pointing to this minus 3 and pref is poed to this value five again okay again now I have already initialized the SU so now from here I'm going to check the sum so minus 3 -4 what is the value of - sum so minus 3 -4 what is the value of - sum so minus 3 -4 what is the value of - 3 and -4 so that is nothing but - 7 - 7 3 and -4 so that is nothing but - 7 - 7 3 and -4 so that is nothing but - 7 - 7 + 1 - 7 + 1 is - 6 - 6 + 6 becomes 0 + 1 - 7 + 1 is - 6 - 6 + 6 becomes 0 + 1 - 7 + 1 is - 6 - 6 + 6 becomes 0 okay so now my sum becomes zero I was doing the C sum here and here at this point my sum becomes zero okay so what I'm going to do here if my sum becomes zero at any time so I'm am going to just update the value of my PR do next if my sum becomes zero so here I'm writing if my sum becomes zero then in that case I am going to update my pr. next is equal to PR do next pr. next is equal to temp. nextt okay temp dot next okay so here uh this was the temp last time right this was the temp last night while performing the calculation this was my temp so what is my temp do next temp. next is this minus 2 okay this is my temp. next so now my PR what was the pr my uh PR last time so PR is pointing to this five okay so PR was pointing to this five so now my PR do next brief. next so see uh this red color cursor brief do next is pointing to the temp. next that is this one okay so my Bri do next is pointing to the temp. next so this okay so this is the I have skipped all these notes now I have skipped all these notes I have skipped right so now my bri. next is pointing to my temp do nextt okay this is done now once this is done then my temp becomes this temp do next minus 2 okay so Min -2 okay so my temp becomes this time -2 -2 okay so my temp becomes this time -2 -2 okay so my temp becomes this time -2 so again I'm going to perform sum is equal to 0 - 2 is what's 0 + -2 is equal to 0 - 2 is what's 0 + -2 is equal to 0 - 2 is what's 0 + -2 is nothing but Min -2 right and - 2 + 5 is nothing but Min -2 right and - 2 + 5 is nothing but Min -2 right and - 2 + 5 is nothing but 3 okay so now I didn't get any sum so I am updating my sum as three here so previously it was eight now this time it is three but I have also deleted these nodes okay while performing the sum because my one time I get the sum as zero so I have dated all this and my new sum by the end of this is three okay now after that once this is done now my curve becomes curve dot next okay my curve becomes curve dot next so now my curve dot next is pointing to nothing but this two okay so now again now in The Next Step my Cur is updated to this green color icon okay Cur is now pointing to this value minus 2 okay because I have skipped all these notes now Cur is pointing to this value okay so now let me delete this okay I have deleted this so now my Cur is pointing to this one and again my I have initialized sum as zero my temp becomes C do next so that simply means that my temp is now this one this five curve do next because my curve is this one now so temp is to Cur do next so let me delete this connection as well this old connection and my pre becomes Cur okay so now C is this one right so now my PR becomes this value this minus two okay so now let me delete one more connection here I have removed this connection so now this minus 2 is my PR and this five is my temp again I'm going to perform the sum so sum here right now 0 + 5 is five so it's not zero so I 0 + 5 is five so it's not zero so I 0 + 5 is five so it's not zero so I Haven I haven't done anything okay again my Cur is pointing curve now my curve becomes this one after that my curve becomes this five okay curve becomes this five and right now my curve is not equal to null so again I am going to perform the same operations so from here my curve becomes five okay this is done and temp becomes Cur do next so temp is null right now okay temp becomes Cur do next this is null value okay this is another value so temp becomes this and pre becomes this okay now inside that I'm checking if my while my temp is not equal to null so my temp is null so I don't need to perform any of these operations because all these operations I am performing uh all these operations I'm performing while my temp is not equal to n okay so this time I'm not going to perform anything and my now my curve becomes this next null value okay so when my curve becomes null value then again I don't need to perform anything okay and in the end so here see the connection z is pointing to five 5 is pointing to directly to minus 2 and minus 2 is pointing to five okay this is the only link node list node that I am left with okay this is the only link list that I left with so in the end this is a dummy okay dummy so in the end I'm going to return dummy. next okay so this is going to my output 5 - 2 5 okay so whenever to my output 5 - 2 5 okay so whenever to my output 5 - 2 5 okay so whenever I'm getting the sum as zero in between the nodes I'm just going to update this five to this one and all these steps so I hope that you guys are clear with the explanation now I'm going to write the code is going to be very simple okay so now let's write the same story here in the code first let's create one dumm note okay this node dummy is equal to new list node and it is pointing to zero initially okay this D not's value is zero okay now I'm going to point dummy do next equal to head so dummy. next is pointed to head and Cur node I am going to start my curve from the dummy okay from my dummy and inside the it I'm running one y Loop and in the Y Loop I'm checking if my curve value is not equal to null if my Cur node is not equal to null in that case inside this I am going to update my Temp and PR right but also I'm initializing the sum every time so in sum is equal to zero okay int sum is equal to Z and Now list note temp is pointing to list node temp is pointing to Cur do next same story I'm writing the same story right Cur do next and PR is pointing to my Cur okay so list node C is pointing to my uh list node PR is pointing to my Cur okay this is what I have explained in the while explanation right this not previous pointing to my Cur this is done now inside that I am running one uh one more while loop okay in this while loop I am checking while my temp is not equal to null okay if my temp is not equal to null only in that case I am going to perform the addition right so this is the Bas condition so sum is equal to sum plus temp do value okay and if my sum becomes zero at any point of time then in that case I have to update my brief. nextt bri. nextt is going to point to the cut. nextt to the temp. nextt pr. next is going to point to the temp. nextt okay so this is done and otherwise we are just going to update temp with the temp. next and this is done and outside of this here I R temp is pointed to temp. next okay this is done and now after this in the end I am going to update Myer as my C as c. nextt right and now that's it in the end I'm just going to return dummy. next so this is very simple code I haven't used any mapping technique mapping key value PA nothing just these few lines of code now let's run the code so all the test cases has been accepted but before that let me write one more uh test case here like this 5 - 3 - here like this 5 - 3 - here like this 5 - 3 - 4 5 - 3 - 3 - 3 - 4 and then 1 6 - 2 5 okay 5 - 3 - 4 1 6 - 2 and 5 6 - 2 5 okay 5 - 3 - 4 1 6 - 2 and 5 6 - 2 5 okay 5 - 3 - 4 1 6 - 2 and 5 okay now let's run it and see the solution so the output for the test case 4 is 5 - 2 5 so what I am writing here 5 4 is 5 - 2 5 so what I am writing here 5 4 is 5 - 2 5 so what I am writing here 5 - 2 5 so I am right okay so if you want - 2 5 so I am right okay so if you want - 2 5 so I am right okay so if you want to okay that's other step if you want to see the sum that I'm getting uh this 8 3 5 and then zero whatever sum that I'm getting if you want to see then you have to just uh just add one uh system. out. print Ln okay here to print the sum okay so you can do that right here you can just add one uh system out print LM to see the sum whatever sum I'm getting after each step okay so this is done okay you can add this here one second let me get that okay so here you have to just add because here our while loop finishes right so here you can just add one system.out.print and sum so you will see system.out.print and sum so you will see system.out.print and sum so you will see the Su step by step whatever sum we are getting okay that's for that and now we haven't submitted our Port yet right so let's submit the code so see here uh our solution is accepted and run time is also very good just 2 millisecond and it beats around 90% of users with Java right so I hope 90% of users with Java right so I hope 90% of users with Java right so I hope that you guys are clear with today's problem and if you guys still have any doubts then please feel free to ask in comment section till then keep coding and keep practicing meet you in the next video thank you bye-bye
Remove Zero Sum Consecutive Nodes from Linked List
shortest-path-in-binary-matrix
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
Array,Breadth-First Search,Matrix
Medium
null
108
hello everyone welcome back here is vanamsen and today we will dive into another exciting coding Adventure today we have a fascinating challenge ahead of us uh converting assorted RI into a balanced binary search tree and we will be cracking this using JavaScript but before we start hit the Subscribe button and the bell icon to stay updated with our coding journey and if you find this video helpful don't forget to smash the like button alright let's talk about binary search 3 or BST in a BST the left child is always less than the parent note and the right child is greater and our mission today is to create such a tree from a sorted array and to keep it balanced we will make sure that the left and right subtree of every node different in High by no more than why uh so here is an example so we are given a minus 10 minus three zero five nine and we want to transfer this into a high bias uh balanced binary search three so how we do that uh here's the plan we are going to use a divide and conquer method here so in assorted array the middle element can become the root of BST and the left half of the array will become the left subtree and the right half will become the right subtree and we will apply this process recursively to construct the tree so let's turn this plan into our Java code implementation so Java Script uh let's Implement so if not num length return and let's floor length divided by 2 and root will be new three nodes now num of middle and root left will be sorted all right to BST Nam slice zero to meet and root right will be sorted RI to BST Nam slice from mid plus 1 and we finally return root so the code is very concise I think here we need to make a note okay so let's run our implementation and see if it's working so yeah everything's work perfect so let's now run it for unsinterest cases so for unsynthesis cases hopefully it will pass as well yes and our implementation bit 50 with respect to runtime and also 16 percent with respect to memory so uh just like that we turned our sorted array into a balance binary search tree using JavaScript so uh our course work for uh oh scene and syntax cases and as you can see our JavaScript works perfect so that's all for today uh coding I hope you found this video helpful and enjoy unraveling this problem with me and remember practice is key in the work of coding so make sure to try out this problem and make more and if you have any question or if there are any specific problem you want me to cover in the future video drop a comment below and don't forget to like share and subscribe for more exciting coding content happy coding and see you in the next one
Convert Sorted Array to Binary Search Tree
convert-sorted-array-to-binary-search-tree
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_. **Example 1:** **Input:** nums = \[-10,-3,0,5,9\] **Output:** \[0,-3,9,-10,null,5\] **Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted: **Example 2:** **Input:** nums = \[1,3\] **Output:** \[3,1\] **Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs. **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in a **strictly increasing** order.
null
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
Easy
109
1,567
all right so what do we got here we have an array of elements and they just want to know what's the maximum length of contiguous elements that gives us a positive product so here you know the two negatives would become a positive and that would be length four because you know all four elements uh give us a positive product when we multiply them together and here we ignore the zero because zero times anything is zero and these three elements would end up in a positive result and this would also result in a positive result but um this would only be length two and this would be length three so we take this guy okay so uh there's one observation we need to make that makes problems so much easier and that's that you know if you have an even number of negatives then you get a positive number and if you have an odd number of negatives you get an a negative number assuming there's no zeros in there and if you if there's a zero in there you just take so let's just say i had it i gave you an array and there was a zero right in the middle you just take the maximum of what you encountered before the zero or the maximum of what you encountered after the zero and you would just keep like a running no matter how many zeros there are you'd keep a running maximum but anyway um let's just pretend there's no zeros for now because it doesn't really make the problem any harder let's stick with our even number of negatives or odd number of negatives so uh if we have an even number of negatives so let's just take this i have an even number of negatives then the number of elements that are going to be a positive product is everything from the beginning and you know again if i threw like a zero in here and i threw some numbers in here then it would just be everything starting after that zero and we're going to keep a running count of like how many elements we've encountered and we'll reset the count when we have a zero so anyway uh back to this so just to repeat that if we have an even number of negatives it's everything starting from the beginning or from the zero whatever if we have an odd number of negatives well we have to start counting how many elements we have after the first negative because then this is going to be all positive so again if you have an odd number of negatives just count everything after the first negative and we're going to compare that with let's say we had you know 3 2 1 out here well you can consider this let's pretend all i had was this so far well this is i could consider zero negative numbers is technically an even number of negative numbers right so what i would say is that this is all if i have an even number of negative numbers which in this case is zero then it's all the all my positive numbers are all the numbers starting from the beginning which would just be three and then as soon as i encounter a negative i then have to start counting how many numbers did i encounter after that negative number after that first negative so now this i would compare one to three as in not as in i have one element here and three elements on the right are on the left and when i encounter another negative number so i'm going to let's say i get to this 5 then i can now just count all the elements from the beginning and when i finally hit this third negative number well then i'm going to count how many number of elements i have from the beginning but then after but i'm also going to keep track of how many elements do i have after that first negative so this would be four so i don't want to include this right because this would make it negative so we'll say how many elements do we have after that first negative or how many elements do we have before that which would be because this would be an even number of negative numbers so the idea is we just keep track of how many elements we had when we had an even number of negatives and when we had an odd number of negatives and when we have an odd number of negatives you just keep track of the elements that you encountered after the first negative so hopefully i know me saying it is it's a little jumbled but like basically even gives us that and odd would give us this everything after the first negative and we just want to keep track of that of both counts and depending on whether we have an even or odd number of negatives while we're like iterating through the array we'll update our maximum our global maximum variable then we'll return the maximum at the end and that's basically the whole algorithm um so i'm just going to code it out and hopefully like it becomes a little more clear so anyway let's just say we have max zero return max and we need to so we need to keep track of all the elements we've encountered so far so elements let's just say num from beginning and this could be either from the beginning of this of the array or after the first zero and so int um num after first negative equals zero okay and now we want to just loop to our array oh and then we need to know how many sorry one more variable we need to know whether we've encountered an even number of negative numbers or an odd number of negative numbers so boolean uh has or we'll just call it is even negatives is that a good variable name yeah we'll just go with that uh equal it's true because we start out with zero negative numbers you know from the beginning okay so let's just look through our array we're in num and nums and i was checking if i was actually recording i would have been anyway um so we looped our array and now we need to just we all so we always want to increment our number from the beginning and we now we just need to check if the number is you know positive or negative or if it's zero so if num is greater than zero then we need to update our okay so if we've encountered it so let's say we've encountered a negative number before this would be greater than one right or sorry greater than zero so if we've encountered a negative number before this would at least be one so what i'm going to say here is if uh if the number after the first negative or sorry number let me just type it before i get trouble talking okay so if i think if i haven't encountered any number any negative numbers yet i don't have a first negative right so if i haven't counted any negative numbers then i want to just leave this at zero but again we're keeping track of all the numbers after that first negative so even if this number is positive or negative the fact that i've already encountered my first negative number i still need to count it so we're going to just say we're just going to increment this by one because this number counts towards the number of numbers after our first negative okay so now i don't think i need these brackets so else if the number is less than zero so we have a negative number what are we doing here then we always want to increment our number after first negative right no matter what there's either this is our first negative or this is our second third it doesn't matter but we have to increment the number of numbers that we've encountered after our first negative okay and we need to update our is even negatives so now this will i'll just put this on the next line so if let's say we've encountered known negatives right because it starts out it's true well then we just toggle it equals is even whoa is even negatives okay so if i think that's just pretty obvious if i've encountered another negative number now that either it becomes even or becomes odd depending on how many i've encountered okay um so now if okay so otherwise this is a zero right the number equals zero then we want to just reset everything so we could just take all this right because if we multiply by a zero then um everything just becomes zero so number from beginning equals zero oh we gotta take out all these declarations or yeah the actual types okay and now we just need to set our maximum to actually have to think about this for a second uh if it's okay i know i want to do them oh okay wait so it's math.max of you oh okay wait so it's math.max of you oh okay wait so it's math.max of you know our maximum right or uh if we've encountered an even number of negatives then we want everything from the beginning right actually let me just call this example down here so let's just say that we've hit we're up to this point right we're let's just not even count this if we have an even number of negatives then we want to count all the numbers from the beginning and see if this is greater than our current maximum sum so that's what i'm doing here and if we have an odd number of negatives then we want to check if so let's say i let me move this back so let's just say we were like out here now and this is an odd number of negatives because these all these fives are negative so there's one two and three fives okay uh so we would want to check you know if we have an odd number of negatives does this number oh sorry does this number after the first negative is it greater than what we are all the number this so we would have had num from the beginning when um when we had an even number of negatives okay i'm jumbling a little bit but basically you know if we have an even number of negatives this would be numb from the beginning we would have counted this which is why we have this little check but as soon as we have an odd number of negatives we need to count we need to only look at the numbers after the first negative which is why i have this here this little check so if this is odd then we'll end up doing this will end up checking this number and it would do math.max you know and it would do math.max you know and it would do math.max you know compared to our maximum sum that we have so far okay so i think that is it and let's just see if it runs and i made a mistake where did i mess up it max num from beginning blah is even negatives num from beginning a few moments later okay i made one little mistake uh so numb after first negative this is i guess i should call this num from first negative because this is actually inclusive so uh so if you look at my example here i wanted to count all the numbers after the first negative i don't actually want to include this but here when i encounter a negative number i increment so let's just say this was the first negative number i encountered then i'm going to increment num after first negative so i actually just want so this will be one when i encounter that first negative number but it should still technically be zero but the problem is that this is my way of checking whether i've encountered a negative number at all so this is technically like number from the first negative number inclusive but i want it to be exclusive so all we're going to do is add a minus 1 here okay and that should just fix everything cool so that's how you do the problem just um hopefully it made sense but and if it helped you could like the video and um yeah anyway peace
Maximum Length of Subarray With Positive Product
maximum-number-of-vowels-in-a-substring-of-given-length
Given an array of integers `nums`, find the maximum length of a subarray where the product of all its elements is positive. A subarray of an array is a consecutive sequence of zero or more values taken out of that array. Return _the maximum length of a subarray with positive product_. **Example 1:** **Input:** nums = \[1,-2,-3,4\] **Output:** 4 **Explanation:** The array nums already has a positive product of 24. **Example 2:** **Input:** nums = \[0,1,-2,-3,-4\] **Output:** 3 **Explanation:** The longest subarray with positive product is \[1,-2,-3\] which has a product of 6. Notice that we cannot include 0 in the subarray since that'll make the product 0 which is not positive. **Example 3:** **Input:** nums = \[-1,-2,-3,0,1\] **Output:** 2 **Explanation:** The longest subarray with positive product is \[-1,-2\] or \[-2,-3\]. **Constraints:** * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109`
Keep a window of size k and maintain the number of vowels in it. Keep moving the window and update the number of vowels while moving. Answer is max number of vowels of any window.
String,Sliding Window
Medium
null
334
foreign problem increasing triplet subsequence let's try to understand the problem statement we will be given on Integer rnms and we need to return true if there is if there exists a triplet of indices such that I should be less than J which should be less than K and their values also in the same order that means I should be less than J should be less than K okay nums of i j k i mean to say if no such indices exist we need to return false okay let's try to understand this uh problem statement in diagram uh assume we will be given on the endanger array something like this okay and so our answer is going to be true why because let's assume this is I this is J this is K okay 0 index one index two index so 0 is then one less than two which attitude's first condition the next condition is the values so 1 less than 2 less than three okay that values it also satisfy the given condition that's the reason I set its true of in some cases it is going to be false so let's assume this so looking at this input the answer is going to be first because we are not going to get a solution here which satisfies these two conditions that's all about the problem so basically we need to find a triplet and we need to return true if the triplet particular follows this two conditions okay let's try to understand how we can solve this problem I am going to take a different example 215046 first let's try to understand whether this array going to give us to our response yes it is going to give true the reason is 0 4 6 this is index 3 this is index 4 this is index 5. right so 3 less than 4 less than five that's satisfied 0 less than four less than six that also satisfied is there any other way yes here two by 6 this is index 0 this is index two this is index five zero less than two less than 5 2 less than 5 less than 6 that is also possible thing okay uh we need to return here in this case true okay let's try to understand how we can solve this the basic and what is the navi approach that you're getting in your mind so it may be answer of big of n cube right the reason why I'm saying is first we take for Loop for I then we take nested JLo then we take nested kilo okay it's something like for I here then for J then per K right so with this approach we can able to solve this problem but the problem here is if you look at the constraints okay the length of the array that means the number of elements in the array is going to be Pi into 10 to the power of 5 which is such a huge data set okay so if you solve the problem in this direction and submit it will give you a time limit exception okay because it is not an optimized solution so we need to solve this in a optimized way okay let's try to see how we can solve so what you are getting into your thought if you know the first if you know the second that means assume I value numbers of J can't you return true if the next number is greater than second the order is something like first is assigned with zero let's assume second Ascend with one value and if you get a 2 okay can't you return there and then true you can right so that's a simple uh walk through let's try to see how we are going to solve exactly so basically what I am going to do here is I'm going to take two variables first comma second okay by default these are going to ascend with integer.max okay both ascend with integer.max okay both ascend with integer.max okay both integer.max then I am going to iterate integer.max then I am going to iterate integer.max then I am going to iterate through this array only once remember first 2 is 2 less than or equal to First you are right it is then what I am going to do I am going to replace my Max with the two then I come here 1 is 1 less than or equal to 2 yes then I am going to make it 1. okay then 5 is 5 less than or equal to 1 no but second one is five less than or equal to Max yes then Max will be replaced with Phi then 0 is 0 less than or equal to 1 yes then this will be striped off first is going to hold 0 then 4 okay we are at 4 is 4 less than or equal 0 no this four is the not equal to 5 yes then second will be replaced with 4. then six is six less than or equals to 0 no 6 less than or equals to four no that means 6 is greater than second right then immediately you can return true that's it I hope you got the logic let's try to understand time complexity since we are editing through ra once it's going to be big open the space complexity is going to be 1. that's it so basically these two variables are playing a vital role in determining whether this is a triplet or else not that's it let's try to solve it so I am taking my last submission so that you can clearly understand you see I took first and second by default this will be ascended to Max then I iterate through the nums of array if the given number is less than or equal to first then I send that number to First else if given number is less than or equal to second then I am going to assign it to Second else okay if these two conditions are not possible then I am going to return true because the third number absolutely going to be greater than second only okay then we can uh case we need to return first that means there is no such triplet exist that's all for this code let's give our yeah it accepted let's give a submit yeah it got submitted successfully it took two milliseconds to run and it beaten 99.61 online Java submissions beaten 99.61 online Java submissions beaten 99.61 online Java submissions that's all for this video I hope you learned and love the content of this video if you're really liking my content don't forget to subscribe and don't forget to tap the Bell icon it is a great motivation for me and till then 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
224
lead code practice question uh in this video there are two goals the first goal is to see how to solve this problem so we are going to find the solution and then we are going to do some coding work and the second goal is to see how it should behave in a real interview so let's get started remember in the real interview the first step is always try to understand the problem if there is anything unclear please bring up the question to the interviewer at the same time think about some ash cases so let's take a look at this question it's called busy calculator so given the string as representing an impression implement the basic calculator to a value okay so example one is equal to one plus one so we are going to return two similarly this one returns three and this one returns uh 23. so that makes sense um so it says the length of the string is going to be within 1 to 300 k so for sure there's no empty string and s only consists of the digits plus minus open closing parenthesis and the space so s represents a value expression okay so that's how that helps a lot so we don't need to consider uh those ash cases i think so the next step is about finding solution so how to solve this problem so usually for this kind of problem uh my first impression is this is the stack problem so let's see if it is applied appliable to use um stack to solve this problem how specifically we are going to use that so let's say for this one um we don't touch any stack we don't need to touch any stack so when we touch that usually it is we encounter the open closing processes so let's say uh when we encounter a number uh so when we encounter a number we just record the number and add up into the corresponding result and for the plus minus we keep it as a sign and when we encounter the open parenthesis let's say we just add the current results into the stack and also we add the current sign to the stack and when we encounter a closing processes uh we have the current results which is the expression within the processes and we know the sign which is the top element within the stack so we just dump the sign and get the result and also plus the previous result we have so for example let me give you an example to explain what i was talking about so let's say it is one minus two plus three so first of all we have result as one and the sign as plus let's see sign as one or minus one and then we encounter the minus then we change the sign to be minus and when we encounter the open parenthesis so we are going to put the result into the uh into the stack and also the sign into the stack so the top element is on the right side which is here and then we are going to set the rest as 0 and sine at 0 as well so here we will have the result as 2 and then next time we see the plus we have the sine as 1. uh so now we have signs one then we have another number which is three so then we are going to add on top of the result which we will have five now and when we encounter the closing processes it's time for us to pop the sign first so the sign is minus 1 which means we should turn this 5 into -5 turn this 5 into -5 turn this 5 into -5 so it is -5 and then so it is -5 and then so it is -5 and then the top and then after we pop the sign the top element was the previous result which is a positive one we are just going to add positive one on top of the current uh partial result so finally we are going to return minus four uh as returns up so essentially that's how we are going to solve this problem uh we use a stack when it is open processes uh we push the result and push the sign when this closing processes we pop the sign pops result and do the calculation so the run time and space those are going to be open and is the length of the string so let's do some coding on top of this question so for coding we care about the correctness the readability and of course the speed so let's give it a shot um so let's see first of all we need to define the results let's say it is a 0 let's start the sign as positive one and then this is a one pass through the string i is equal to zero i is smaller than s dot less and then we plus i so uh car c is equal to s dot car at i so we are going to switch um c so if it is a uh i think it's not switch um because when we encounter this a number we need to keep going through it until we had we get the whole number there okay so let's see um if it is uh c is equal to plus then we are going to say sine is equal to 1 else if c is equal to minus then sine is equal to -1 is equal to -1 is equal to -1 and uh else if um character dot is digit if it is a digit then we are going to say uh okay ins num as equal to let's see how to do that so if it is a digit uh then it means we need to get a number for it so in some sorry in them is equal to uh c minus zero and well i is smaller than s and the character is digit c then we are going to have num okay so we don't really need to have this here so we initialize that as zero we have num times equal to 10 and num plus equal to uh um c so you have this will be c uh c uh sorry um equal to s.car at uh i know s.car at uh i know s.car at uh i know so while it is true okay so let's see so c is equal to this well it is true um we are going to have uh c minus zero plus equal to c minus zero all right so at the end it is supposed to be arrived at the end of the string or it is the last digit um is the last is the next index of the last digit because we have the minus sorry we have the plus i here so we just need to minus i here okay so another possibility is we have um it is open parenthesis that is it is c is equal to open parenthesis if yes uh we need to define a stack here so let's say this is an integer stack so if it is an open presses what we are going to do is we are going to uh add the red or the result into it and we are going to also add the sign into it and then we are going to set the result to be zero and the sign is equal to one otherwise if it is a closing parenthesis then what we need to do is uh we will need to have the results times equal to stack dot pop and the results plus equal to stack dot uh i think do we have the yes it is yeah so this that's it and finally um we should return results yeah so that's pretty much it let's go through a very simple example to explain how this piece of code is gonna work so it's gonna be part of the interview uh you go through a simple task case uh do some sanity check uh and also fix a bug explain how this piece of code is gonna work so let's use something simple let's say one just one minus two minus three so it's going to uh so first of all when it is one uh we are let's say 12. because this character is a digit so initialize number zero uh first one num times equal to 10 and plus equal to one so now it's equal to one now it's the next one okay so we need to plus i here uh yeah so then uh we are actually doing something not that good so actually it should be something like this well it is uh smaller uh no so let's see let's have another thing here um j is equal to i j is smaller than s dot s and um character that is digits that's the car at j this is um plus j so we are going to have num times equal to 10. and num plus equal to um s dot car at j minus zero and finally we are supposed to have and j i is equal to j i would say and finally when it is out of the range we don't need to uh minus the i here right yeah so and finally i think we don't need to do that and if it is a digit we need to have rs plus equal to sine times num yep so let's see first of all when the first character is one and then it is the second character uh it's also digits uh we are going to have num as equal to 12 and i is equal to 1 here and then aft and then after that we are going to have i is pointing to the next which is this negative sign so the sign now and by the way rest is equal to 12 at this moment and now sine is equal to -1 and now sine is equal to -1 and now sine is equal to -1 and then next time when it is an open parenthesis we are going to have the stack to have the rest inserted to have the sign inserted which is minus one then the rest is equal to zero uh and size for the one now and then we move to here we have the num as two so rest plus equal to uh one times two which is two and for the next time when it is uh this minus we are going to change the sign to be minus one then when it arrives at the next number we have a three for the num and due to the sign which is negative we have minus three so we have res as two minus three which is minus one now and then we encounter the closing parenthesis we dump the minus one which is the sign so we are going to say this is minus one times minus one and then it is so it is one and the plus the twelve so we are having uh result as thirteen finally so i think it looks good uh let's uh do some i'll give it a shot by okay so it's new stack some typo here um let's see okay so now it looks good uh let's use this one so let's see let's say if it is this it's going to work for that okay so seems like it's good let's do submission all right so everything works here and that's it for this coding question and about the solution so if you have any question about the solution or about anything feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching
Basic Calculator
basic-calculator
Given a string `s` representing a valid expression, implement a basic calculator to evaluate it, and return _the result of the evaluation_. **Note:** You are **not** allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`. **Example 1:** **Input:** s = "1 + 1 " **Output:** 2 **Example 2:** **Input:** s = " 2-1 + 2 " **Output:** 3 **Example 3:** **Input:** s = "(1+(4+5+2)-3)+(6+8) " **Output:** 23 **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consists of digits, `'+'`, `'-'`, `'('`, `')'`, and `' '`. * `s` represents a valid expression. * `'+'` is **not** used as a unary operation (i.e., `"+1 "` and `"+(2 + 3) "` is invalid). * `'-'` could be used as a unary operation (i.e., `"-1 "` and `"-(2 + 3) "` is valid). * There will be no two consecutive operators in the input. * Every number and running calculation will fit in a signed 32-bit integer.
null
Math,String,Stack,Recursion
Hard
150,227,241,282,785,2147,2328
417
Hello friends to Jhal Ajay, once again welcome all of you to our YouTube channel teacher, I am taking this very interesting question in today's video, Pacific Atlantic water flow, one basic question before starting, if not subscribe the channel. If you have done it then please do it friend, if you don't like the video then please do like this video and join the Tiger Group. Okay, now let's talk about what is the basic thing to do in this question. Let's go straight to the white board. Life is great, okay, there are some sales in great, we were told that your grade, you are in the boundary of 2011, there is money also question and one is Atlantic question Edison, so much money is also question, enemy intraday question, okay, we are being told no what we have to do. We have to fill some values ​​in each of the cells like this is to some values ​​in each of the cells like this is to some values ​​in each of the cells like this is to dead one, it starts from some building, 10 days request you to give power fight, I can also fill some values, okay, now we are saying this, tell us how well. Is it or before that, it is understood that there was running here, due to this, there was a rain on top and due to rain, the crop got flooded, due to leakage, the water did not start flowing in our neighboring states. Now we are being told that the output Found that, tell me when the water is slow, which year is this cell, a particular cell, will even money be able to reach the water Question OD Question Means When the water keeps flowing and flowing due to three reasons, then it is going in the Pacific as well as in the plant. If such a sale goes ahead then it satisfies both the properties that the water generated from it reaches the paisa and also reaches the Atlantic, then they can, yes, it will be looting from within us, it will not happen otherwise, now let's talk, it will be fruitful. How did he say that to make him ejaculate, he will use this oil on Prince Charles only if the height of Bigg Boss is either equal to the current one or it is shorter i.e. if it is written free here then either it is i.e. if it is written free here then either it is i.e. if it is written free here then either it is free here or If it starts here or if anything big or small, it will not happen here, now let's talk about how to do it. Now we thought that friend, tell me one thing that I will have all these sales in Rover and this 101 percent in Columbus. In the Pacific, we will definitely spill the water, there is security because the money is taken from its body and whoever sells this green in the last column, this dad will definitely spill the water in the bucket of 1% Atlantic. spill the water in the bucket of 1% Atlantic. spill the water in the bucket of 1% Atlantic. Wait, the Atlantic is clinging to the mountain. This is very good, so why should we work in two groups? Let's make two groups, put the cells which are to the Pacific and put some cells which can be connected to the Atlantic, don't connect them and see what is the common sense between the two. That the sales will like that there is packing of water in both Pacific and Athletic, that means we should establish the connection of all the smudges with all these Dongri walas who can deliver water till the classification and in such a way, the connection of all the sales from these green boundaries. Used to establish that we can send water to the Atlantic and later see which cells are in the connections between these two, so how was our fabric formed? I have to get it done between this particular peel and this particular cell. How was this connection established? Let's talk, let's say my height of this year, Hitech Saif of this year and Hit Wires of this year, I am going to establish its connection. Okay, now you told me, I know that if they want to join the same group. If you want to join the group of Wiko Do this and it means that it is necessary for the water inverter to be successful between them. If there is no water flow between them then we will not be able to subscribe the connection between them. Now what will be the flow of water. I said how did the water flow if the height of my ex is My ex's height becomes bigger than why's height What do I say if my ex's height becomes bigger than why's height then I would say that there cannot be a character between them because ex's height If it becomes big then brother, there is a virus in one, the water has become slow, no, and this is what I will say, if only one device is small, then yes, there can be collection tablets between them, because in this case, if brother's height is big, then wire. The clock will remain on the water till the alarm is set because the actor is not forced to drink water. Connect with Viral. To Nex is not fond of taking him in his group, that is why a date is also right on him. If the value of the ex is there, then Hina. Correction has to be done between , otherwise it does not have to be done, we will do it Correction has to be done between , otherwise it does not have to be done, we will do it Correction has to be done between , otherwise it does not have to be done, we will do it for cement ultratech and later the intersection of both, now let us see how to code from , first of all, how to code from , first of all, how to code from , first of all, take the commented admission, number of daily bills also, and how much is the number of columns. 2 Answers It has been made that every paisa is left behind, Yogi 's money will also remain in the group of questions in the 's money will also remain in the group of questions in the 's money will also remain in the group of questions in the middle which will take them from alphabets and if you saw a celery then everyone's prohibition is folded and dimensions are kept the same which is our metric system action. I have capsicum, let's make it, okay, let's copy and paste the same, Tonic group is also ready, after doing these, let's make our deception, first who will do what will get the fame listed, then the era of taking the matrix will start, America will think about it. Or Britain will take it, whoever sends something now, the condition is that if the number becomes less than zero or the column becomes less than zero or the right most boundary crosses ours, then these are the basic things, so we have to take care of them. It will have to be done in that case and the second return 611 Previous Volume I said that the value of the currency and the previous service and connection are tablet agreements and they have to be maintained, so now what I said is that if the value of the previous currency increases. There is only one voice that if he grows bigger than this, then what can we do about it, in that case, if we ever follow the water, then it is good to do Vitamins. If he has visited, if he is a celebrity, then he has also been simply returned. Now it comes. I marked in India Has Visited that there is a connection between them and clicked on nov. I called where is here, called where in my down on the left and this one on the right, I started calling half of all. This text message of Sam Rahe will go in Rome - To the mind that you are calling will go in Rome - To the mind that you are calling will go in Rome - To the mind that you are calling Columns in Amazon will be the previous person which will become the value of the present environment, immediately called all the four means 1, two, three and four are done, now I always change Let's give such a question here, let's close like this, here let's do plus one, let's do it in all four directions, and the dead body returns, I have dad ready, now what should I do from here, I am the first among all. First I work, first one oh and last one get up for stop, for this I make Atlantic and Pacific connections, then if I want to make for row, then for I in research phone number forum, how many end updates connection benefit, by doing this work I made the connection metric- Stop the matriculation de sauce and said that metric- Stop the matriculation de sauce and said that metric- Stop the matriculation de sauce and said that initially zero eye at Kollam, whom did you send in the visit, practical that now connecting with the Pacific, you have to hit the president to visit, that number of finance contact that yes brother, dad is on, then as many visits as possible from this. All of them will go and become part of his group and the previous one is stopped and here we put a condition here that there should not be a prevented one otherwise check at the airbase that after that the same quantity is there for the last row also. So Matric Justice Lash Rok Hogi Hai - One IS Column Hai - One IS Column Hai - One IS Column Work is finished with Atlantic Minus One Again now for whom is the work to be done For the first column and last kolam straight face matric-matric sent roll straight face matric-matric sent roll straight face matric-matric sent roll number Which sent roll number IS Roti Kadak We will do it like this Pacific - - - Atlantic Matric-Matric IS Atlantic Matric-Matric IS Atlantic Matric-Matric IS Cry Last Column Atlantic Work is over Now both Travel and Range in Ujjain Range and one of these two is also a good recipe Atlantic If money is not available in both of them then some Don't do it now, last one, answer a and pigmentation, you were previous, okay, there is a spelling mistake somewhere, it is not previous, submit, what happened to you, the explanation is clear, feel this video happened, what happened to you, the explanation is clear, feel this video 33 comments channel subscribe The Channel and in the comment section you guys tell me. You say, language is some chawal or these people, I will do this, look at the important implementation of logic, tell me the thing, you this code that it is difficult to claim, I will do the same thing, remove the message, it is done, the method of making question matrix etc., how to remove the message, it is done, the method of making question matrix etc., how to remove the message, it is done, the method of making question matrix etc., how to make this dress. The method is only different in the sentences of the job fair, so the logic will remain the same, what should we do here I am filled in the dark like this, on the other hand, what do I have to do in rice, if you want to return the list, then make a list, then let's go for language independence, it will be very beneficial in this. See you in the next video. Good luck bye-bye.
Pacific Atlantic Water Flow
pacific-atlantic-water-flow
There is an `m x n` rectangular island that borders both the **Pacific Ocean** and **Atlantic Ocean**. The **Pacific Ocean** touches the island's left and top edges, and the **Atlantic Ocean** touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `heights` where `heights[r][c]` represents the **height above sea level** of the cell at coordinate `(r, c)`. The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is **less than or equal to** the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return _a **2D list** of grid coordinates_ `result` _where_ `result[i] = [ri, ci]` _denotes that rain water can flow from cell_ `(ri, ci)` _to **both** the Pacific and Atlantic oceans_. **Example 1:** **Input:** heights = \[\[1,2,2,3,5\],\[3,2,3,4,4\],\[2,4,5,3,1\],\[6,7,1,4,5\],\[5,1,1,2,4\]\] **Output:** \[\[0,4\],\[1,3\],\[1,4\],\[2,2\],\[3,0\],\[3,1\],\[4,0\]\] **Explanation:** The following cells can flow to the Pacific and Atlantic oceans, as shown below: \[0,4\]: \[0,4\] -> Pacific Ocean \[0,4\] -> Atlantic Ocean \[1,3\]: \[1,3\] -> \[0,3\] -> Pacific Ocean \[1,3\] -> \[1,4\] -> Atlantic Ocean \[1,4\]: \[1,4\] -> \[1,3\] -> \[0,3\] -> Pacific Ocean \[1,4\] -> Atlantic Ocean \[2,2\]: \[2,2\] -> \[1,2\] -> \[0,2\] -> Pacific Ocean \[2,2\] -> \[2,3\] -> \[2,4\] -> Atlantic Ocean \[3,0\]: \[3,0\] -> Pacific Ocean \[3,0\] -> \[4,0\] -> Atlantic Ocean \[3,1\]: \[3,1\] -> \[3,0\] -> Pacific Ocean \[3,1\] -> \[4,1\] -> Atlantic Ocean \[4,0\]: \[4,0\] -> Pacific Ocean \[4,0\] -> Atlantic Ocean Note that there are other possible paths for these cells to flow to the Pacific and Atlantic oceans. **Example 2:** **Input:** heights = \[\[1\]\] **Output:** \[\[0,0\]\] **Explanation:** The water can flow from the only cell to the Pacific and Atlantic oceans. **Constraints:** * `m == heights.length` * `n == heights[r].length` * `1 <= m, n <= 200` * `0 <= heights[r][c] <= 105`
null
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
null
1,510
hey everybody this is Larry this is me going over Q for stone game for after reason did coke contest so yeah so the explanation for this one is that it's game theory which is always a little bit tricky I think with this one specially if you're doing in Python or other languages it might not be as intuitive I think of you to understand the other stone games which I think you should probably then this one becomes more easy to understand but the idea is and I don't want to explain a lot of the game theory because you know that's the basic that is a prerequisite for this problem and that is the stuff that you know that is the tricky but the idea is that for yeah so basically one is a winnable state but that means that zero is a not winnable state because if you're starting and as I'd say I'm Joey loss if you had won while one goes to zero so that means that it is a winnable state because you can take one item and then go to zero and then similarly two you can only make one so two honey goes to one so this is not winnable and I have some typos but yeah and this is some basic thing the four is the first case we're different because for it's also a square right so you could go to zero meaning you win right so it's winnable and then with that reason 5 well 5 will try to go to well you up to positive moves now I try to go to 4 which is winnable or one which is winnable right so it just means that this is not winnable because wherever you go the opponent will be winnable right and that's kind of pretty much it and that's why a lot of people during the contest a to very quickly the only thing that you have to maybe do a little bit optimization in Python just to make sure that so you cannot easily do this top-down because n is 10 to the 5th and top-down because n is 10 to the 5th and top-down because n is 10 to the 5th and dad maybe you're just you may get Stack Overflow someone like that so justified upon himself and that's the only thing that makes a little bit tricky he's my solution I actually learn the contest which you can watch out to it this I got this formula pretty quickly but I thought that it wouldn't be fast enough to be honest and it turns out that there is and I don't have a proof with this though I did one a lot of testing that it turns out that because a lot of if you write this out most of these states are not winnable or so most of the states are winnable and the only a few in that winnable States so if you do an optimization based on that observation then it'll be fast enough in most languages if you don't then seems like only C++ is fast enough or C++ like only C++ is fast enough or C++ like only C++ is fast enough or C++ like so jaw flapping is also probably fast enough like that languages that are faster than C++ only code or around that faster than C++ only code or around that faster than C++ only code or around that range should be good enough which is what I struggled with because in Python without this optimization it takes least for me it took about nine point eight seconds I have a screenshot somewhere but which I joined the contest during one case was taking way too long so I didn't think that was gonna be fast enough but apparently it is fast enough and that's why I spent a long time cuz I was trying to come up with a pattern for this problem instead of just submitting it and you live and you learn but yeah but although I won't say there's a simple problem it's a simple problem once you already work on your prerequisite or your foundations so if you're having trouble with this problem I recommend looking at the earlier stone game problems just to get an intuition of how the game theory part works and once you get that I hope that this problem will be straightforward as a result yeah let me know what you think and hit like money to subscribe when drumming on discord and all that stuff stay tuned for the me coding portion Wow people are really fast today okay oh I'm just really slow today square number people really fast oh that's just not right maybe too slow anyway I suspect would be too slow good hmm still gonna be too slow I think it's fast enough I would not be happy miss any obvious patterns what's intruder books you don't get it still shouldn't be fastened after that's why no really I really thought up here whoo that's a we thought that doppio easier to be on I hope you had a good time watching this video let me know what you think hit the like button to subscribe one join a discord and I will see you next farm bye
Stone Game IV
find-lucky-integer-in-an-array
Alice and Bob take turns playing a game, with Alice starting first. Initially, there are `n` stones in a pile. On each player's turn, that player makes a _move_ consisting of removing **any** non-zero **square number** of stones in the pile. Also, if a player cannot make a move, he/she loses the game. Given a positive integer `n`, return `true` if and only if Alice wins the game otherwise return `false`, assuming both players play optimally. **Example 1:** **Input:** n = 1 **Output:** true **Explanation:** Alice can remove 1 stone winning the game because Bob doesn't have any moves. **Example 2:** **Input:** n = 2 **Output:** false **Explanation:** Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0). **Example 3:** **Input:** n = 4 **Output:** true **Explanation:** n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0). **Constraints:** * `1 <= n <= 105`
Count the frequency of each integer in the array. Get all lucky numbers and return the largest of them.
Array,Hash Table,Counting
Easy
null
108
so we're looking at question 108 converting a sorted area to a binary search tree so let's go over the question really quickly so given an area where elements are sorted in ascending order converted to a height balance bst so for this problem a height balance based uh bst is defined as a binary tree invested depth of two subtrees of every node never differ by more than one uh simple enough so given a sorted area you could come up with an area which goes like this um and then since uh it's um it's a binary search problem you can always think about uh tree problems as recursive problems because the way we will be approaching this problem is that we will uh look at the given array and then we'll initialize the root uh with the value that is at the mid index and then anything to the left will be used to construct the left side of the subtree and anything to the right of the middle index will be used to construct the right side of the subtree uh the time complexity of this entire solution would be of n because you're going through every single um every single index in the provided area and you will be constructing the tree with that and um and the space complexity would also be of n because you're constructing a binary tree binary surgery which is uh which would occupy uh off n space because we have to add every single node uh so let's get started and we know that it's a recursive algorithm so uh you would create a helper method where you're passing in the area itself and then you want to pass the index that you want to start with and the index that you want to end at so it'll be nums dot length minus one okay and then right after you would initialize the function and you pass the return value will be your tree node helper um and minimums end start and end so if the start is greater than the end you know that there are no more nodes that need to be assigned to the tree so you just return now and then you would look at the mid so the mid would be the index that's right in the middle i'll let that right divided by two is it left or right now we have used a start and end okay so that'll be the mid note and then when you're initializing the root you would be using the value which is admitted index in the nums this area that's provided so you'd add mid okay so the root the left side of the root you would have to call the recursive method on that with helper uh with the same array and the start would be start but still remain the same and the end would be one index before mid um yes and then without right would be it would be constructed using anything after the mid index or would be num and then with plus one and what do we have uh end yeah and then in the end you would just return the root cool so let's run this and see if there are any compilers yes there are uh where is that outright semicolon all right so the first test case passes and many possible answers to the question and you see that the solution passes um and everything is good so let me know if you have any questions regarding the solution and in the comments below
Convert Sorted Array to Binary Search Tree
convert-sorted-array-to-binary-search-tree
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_. **Example 1:** **Input:** nums = \[-10,-3,0,5,9\] **Output:** \[0,-3,9,-10,null,5\] **Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted: **Example 2:** **Input:** nums = \[1,3\] **Output:** \[3,1\] **Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs. **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in a **strictly increasing** order.
null
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
Easy
109
226
I am always amazed how many different type of problems you can make with binary trees right since it is a non-linear data structure you can play non-linear data structure you can play non-linear data structure you can play around with it for much in one such problem invert a binary tree you have to mirror a binary tree rather than flipping it upside down I know the name is a little confusing but that is what inverting a binary tree in this problem actually means so what can we do about it Hello friends welcome back to my Channel first I will explain you the problem statement and we'll look at some sample test cases going forward I will tell you how you can go about approaching this problem because in the beginning it feels very overwhelming then we will try to form the most obvious recursive solution and then I'm gonna show you a solution that is iterative and very easy to understand after that we will also do a dry run of the code so that you can understand and visualize how all of this actually works in action without further Ado let's get started foreign first of all let us quickly make sure that we are understanding the problem statement correctly in this problem you are given a binary tree and you have to invert it and then you have to return with a new tree correct so this problem is pretty straightforward right and it is asked in a lot of different ways it could be asked that okay mirror a binary tree or flip a binary tree so what is actually happening over here let us look at our first test case so in our first test case you can see that you have a binary tree in front of you and you have to invert it so inverting actually means that you can assume that there is a mirror right over here and then you have to see Its Reflection how will the tree look like so if there is a mirror then what will happen both of these elements will get flipped correct so the inversion or the mirror or the flipping of this binary tree it will actually start to look like this so you can see that root remains at the same place and both of these nodes have swapped so in this case this tree will be your answer and you have to return this similarly let us look at one more test case so in this particular test case you can see that your tree has expanded a bit right and once again to invert it you can assume that okay you have some kind of a mirror over here and then you have to look at the reflection of the screen so try to think what will happen both of these nodes will get flipped and all of these nodes they will also get flipped completely correct so for this particular test case you can see that in my revert Note 4 remains at its current Place node 7 and Note 2 have swapped and so are all the nodes that were in the most bottom level right so if 9 was at the extreme right it has come at the extreme left so for this particular test case this entire tree will be your answer and for all your edge cases for example if you have a null node that means no tree is present then yeah obviously you will have to return a null as your answer because you cannot Flip or invert a null tree right for now if you feel that you have understood the problem statement even better feel free to first try it out again otherwise let us dive into the solution okay so let us take up a sample tree correct and you have to invert it before you even start writing or thinking about the code first of all you will try to think that okay how will I iterate over the structure because you will have to Traverse through entire elements right and then you have to invert them so whenever you see problems like this if it's an array what is the first thing that comes to your mind you will need to decide that okay how will I go through my array you will start from the first element and then travel all the way to the end correct similarly if you have a linked list then you will start from the head node and keep on doing a next if it's a stack you will do push and pop operations and in a queue also you will do push and pop operations right so give it such kind of a tree how do you Traverse a tree correct so you can Traverse a tree in many different ways there is in order traversal pre-order there is in order traversal pre-order there is in order traversal pre-order travel file post order term if a level order traversal correct so many different techniques so first of all you need to find life okay how do I even begin to Traverse this tree but try to think what do we have to do in this problem you have to swap notes at each level right so two will come at the place of 7 and 7 will come at the place of two similarly for the last row as well this entire direction of the nodes will change right so that tells you something what you can do is you can start going level by level and start to swap the notes probably that can help you for example if I am at the root mode then I don't have to do anything and I can just write down 4 over here right now what you can do now you can say that okay now I will go to my second level and whatever is at the second level I will swap it so that means you're gonna swap 7 over here and then 2 over here so you can see that this going forward you will go on to the third level and then you will perform some sort of works correct so that is the basic idea how you should begin attacking this problem you know that you have to Traverse this tree and you might think that okay a level on a traversal technique might be helpful to actually arrive at your answer right and since this is a tree data structure trees are notoriously famous for recursion right so first thing that should come to your mind is okay what if I try recursing at each level that could be some approach right so let us try to form a solution using recursion on the right you have a sample tree that is represented from the root correct and then this route is passed in as an input parameter to the function inward drill recursive so what we're going to do over here if we will go step by step and then populate this function you're going to see how straightforward this is in a recursive function what is the first thing that you do first of all you need to have a base condition right so for this particular problem if you have a null tree then what will be its inversion it will be a military again right so that can be my perfect base condition so I add a condition if root equals to null just simply return null correct and now try to think how does recursion in a tree actually work suppose you have a tree that is represented by root and then you have some left subtree and you will have a right subtree correct and the general idea of applying recursion will be that you apply the recursive technique on this route then you will try to apply the recursive technique on the left child and the right child and once all of this is completed you will ultimately get your answer that is the idea correct so now in this problem you took care of the root value correct and what do you have to do you need to determine okay what will be my left child and what will be my right child so I have two variables three node left and three node right and now we have to populate some values to it so first of all I will apply recursion to the left node or the left subtree so this is the place where I apply recursion and assign it to the left of root and then I will apply the same recursive technique on the right subtree and I will call this my right node correct so what will happen is the entire recursive technique it will get applied on the left subtree and on the right sub tree and what will happen is this will keep on recursing until you reach the very end and when it eventually Returns what do you need to Flap the left and right Children of the node correct so what this will do is it will have three with one and one with three similarly when the right tree recursion completes it will swap six and nine with six correct so this will now propagate up and then it's gonna swap two with seven and then seven with two right so you will see that okay the recursion has ultimately completed and then it goes all the way back up and once it goes back up you simply need to return the root and once the root is returned ultimately you will have your complete inverted binary tree so this is how a recursive solution looks like and I know it is pretty straightforward it is really easy to understand and visualize correct but I don't like recursive Solutions in general because recursive Solutions are a little hard to debug you need to actually write down and see all the values to understand what is actually happening so definitely if you think we can go back to our original approach where we were going level by level and let us try to use a level order traversal technique and see if we can come up with the solution once again I have my same sample tree in front of me that we have to invert correct and this is the queue that I'm gonna use for my level Auto traversal technique if you're new to level Auto transfer techniques I will highly recommend you to check out my video on level Auto traversal first that is going to simplify things very much and this is going to simplify your understanding as well not to level or a traversal I will still try to make sure that you understand what is actually happening so how do the level of transfer work I have this queue in front of me and what will I do I will take the root of this tree and I'm gonna add it to my queue correct and now what we usually do is we try to pop out elements from this queue and then look at its child node we add these child nodes to the queue once again and then we will keep on popping out from the queue so that we know that okay we have traversed the entire tree right so now that we have a element in the queue just pop it out and then what you're gonna do is you will look at the child nodes so this node has two child nodes two and seven 2 is on the left and 7 is on the right so what I'm going to do is whatever node I popped out just swap both of its child nodes so what will happen is 7 will get in the left node and 2 will get in the right node correct and following a level or a traversal technique what you're gonna do you are gonna add both go ahead now you see that your queue is not empty so you are going to pop an element as soon as you pop an element 2 gets popped out and that means we have to work upon this once again what I need to do is whatever is the popped element just swap its child notes so what are the child notes of two they are one and three right so I am just gonna swap them one gets to the right and three gets to the left correct and now once you're done with it you are gonna add these two modes to your queue move ahead now pop the next element that is in the queue that is seven so seven gets popped out that means we have to process this seven now right and once again what will you do you will just swap the two child notes so if I swap both of them 9 will come to the left and 6 will get to the right correct and both of these modes they will get added in my queue correct now your queue is still not empty so you will keep on popping these elements one by one but none of these nodes have any children so you don't have to perform any swapping and ultimately this queue will be eventually empty and once it is empty you need to stop right and now just compare both of them you have actually formed a inverted tree right or you have found out a mirror you can see that 2 and 7 were swapped and all of these numbers were also swept right so you can safely say that with this level on a traversal technique you are easily able to find your inverted tree now let us quickly do a dry run of this approach and see how it works in action on the left side of your screen you have the actual code to implement this solution and on the right once again I have the sample tree that is passed in as an input parameter to the function inverter tree correct oh and by the way this complete codes and its test cases are also available in my GitHub profile you can find the link in the description below moving on first of all we add a condition just to check if our root node is null if it is an empty tree just simply return an empty tree because you cannot invert an empty tree correct create a queue that we will use to pop out every element and the first thing that we add to this queue is the root node so as soon as I add this node my queue starts to look like this correct because 4 is now in the queue and next what we will do we will start a while loop until my queue is completely empty and in this queue we are going to process each element so first of all what do we take out a node from our queue correct so 4 gets popped out and then as you know we have to swap both of its child nodes so I use a temporary variable to swap both of them so 10 people should know dot left and then I will assign node dot left to node dot right and node.right left to node dot right and node.right left to node dot right and node.right will be equal to 10 so what does this do it swaps 2 and 7. correct and then once you're done with swapping you need to add both of these child notes back to your queue right because you have to process further elements so now when I will add these nodes two will get added to my queue over here and 7 will get added as the next element right so once again you see that your queue is not empty and this Loop will run again so this time 2 will get popped out and what you're going to do again give us five bits notes so both 1 and 3 will get swapped out and then these 1 and 3 will get added to the queue for further processing so you can see that this will keep on happening and ultimately your tree will be inverted at the very end you just return your root and that will be your inverted tree the time complexity of this solution will be order of n where n is the total number of nodes in the binary tree and the space complexity of this solution will also be order of n because you need some extra space to store that queue and have all the elements in there I hope I was able to simplify the problem and its solution for you as per my final thoughts I just want to say that when it comes to problem on trees I know that recursive Solutions seem very small and pretty straightforward right for example in this case but recursive versus iterative first of all an iterative solution is easier to follow and easier to debug so whenever you get a chance try to come up with an iterative approach then you can actually see what is happening throughout your code and also when you are coming after the recursive solution you take up some memory in your CPU because you have to maintain that reversal stack somewhere right you are not maintaining it in your code your CPU is doing it for you so if your input test case is very large then certainly you will get a stack Overflow exception and that is because all of that recursive memory that gets stored and you know that it is not easy to debug right so how many other problems have you seen where a reversal solution seems very obvious and writing an iterative approach takes some time but did you find that hey with the iterative approach you are able to visualize it better while going throughout this video did you face any problems throughout tell me everything in the comment section below and I would love to discuss all of them with you as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you I also have a website study where you a website study where you a website study where you can find other such problems also let me know what problems do you want me to solve next what do you want to learn next until then see ya
Invert Binary Tree
invert-binary-tree
Given the `root` of a binary tree, invert the tree, and return _its root_. **Example 1:** **Input:** root = \[4,2,7,1,3,6,9\] **Output:** \[4,7,2,9,6,3,1\] **Example 2:** **Input:** root = \[2,1,3\] **Output:** \[2,3,1\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
427
hey guys welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you've not liked the video please like it subscribe to my channel and hit the Bell icon so that you get notified whenever I post a new video so without any further Ado let's get started uh problem is construct quad 3 very easy problem we are given a matrix in Cross n so it's a square Matrix which has zeros and ones we want to represent this grid with a quad tree so we are given a grid and we have to represent that Grid in a quad tree so it's clearly clear from the name so we have generally binary trees right so binary trees means there will be two children but here there is what quad means four children so here each node will have four children okay so return the root of the quadri which we is representing the grid so now let's understand uh basically uh how this tree will be represented uh this quarter is a tree data structure each internal node has had four children okay so as I said there will be four children's and also each node will have two attributes one is the value generally we have value only but here there are two attributes which is value that is the value of the node if one then it means true if 0 it means false is leaf is the second attribute which is if it is true it means the node is a leaf node and if it's false it obviously it means that the it's not belief node and it has four children okay so this will be some uh this will be the structure of this quadri node that it will have value is leaf and there will be these four pointers which will be representing the four children's these will be four children we'll understand what top left top right bottom left bottom right means so let's understand here within uh with this test case I have taken this test case here which is uh hit this one second example so see basically this grid is given okay uh this grid is given to us grid is given and we have to convert this grid into a quad tree so when I am saying we have to convert it into quadri we have to return the root of this tree root of the tree okay so how we can convert this into quadri C in the problem they are give they have given that see these points if the current grid has all the same values it's like let's say you this is the current grid which we have right this is the current grade if this current grid has all the same values which is not obviously but let's say if this grid has all ones then what we have to basically do is we just need to create a node quad node right quad node we will create its value we will set to the value which is there in the grid so if let's say all ones are there so value will be one it will be a leaf node because all the values are same so if all the values are same is leaf will be set to true so if easily if will become true and all these pointers bottom top left top right bottom left bottom right will be none will be set to null okay this is the case this is the first case where all the values of the grid are same whether the value can be 0 or all the values can be one so if all the values are same we will make value as the whatever values there in the grid easily if will be true and all the four children's will be set to none this is first step but as we can see here right in this problem we do not have all the same values in the grid so that means that we will have to create a node so what we will do in that case we'll have to create a node this will be the root node and this root node will have a value it will have is it will have a value it will have is leaf and it will have four pointers basically which will be the pointers to the four children and what four children will be there this grid will be divided into four parts this is the first part this is the second part this is third part and this is the fourth part that is top left this is the top left top right this is top right bottom left bottom right okay so we will be dividing this grid into four parts what will be the root value let's see that so if all the values in the grid are not same then it will be divided into four like it will have four children the root will be the node so here see if the current grid has different values uh set a value to any value so here value so set it to anything one not zero your wish and is leaf will be set to false because easily if will be true if all the values are same since all the values in this grid are not same so the root we'll be having is valid leave value as false now the question arises what will be the pointers here what will be the values for these four these pointers top left top right bottom left bottleneck so here so if you see guys see here this is the biggest bigger grid which we just saw this is a bigger grid and when we have to find the children those will be smaller grids right these are smaller grids mechanism will be same only right for example let's say I'm finding for top left I have to find for top left so what I will do this is my top left I will see whether all the values in this grade are same or not all the values are same one all white or values are one right so I will make a node that is quad node that quad node will have value as what value as 1 which is the values in the value in the grid easily if will be what will be 2 because all the values are same okay and then these four values will be what null right because this is the first condition that if all the values are same then the leaf value will be true value will be the value of the grid and all the four children will be set to null so for this all the four values of those children will be null so this will be the node this node we will return and we will add it in the root nodes top left Okay so this is how we will proceed so basically here what we will do recursion we will in recursion what we do we work on the bigger problem and the smaller problems we will send to recursion okay so basically what I am trying to say here is what I'm trying to say here is let me just copy uh this grid okay so what we will do is right C what we will do is we will be we will check first of all let's discuss step by step right let's discuss step by step the approach now let's discuss the approach now so I hope you understood the problem let's see the approach so first of all we will see whether all the no all the values that is all the values in Grid are same or not because it everything depends on this if all the values in the grid are same or not okay if they are same we will make a node for that node value will be the values which are same let's say all the values were 1 so value will be 1 is leave will be true because all the values are same so it will be at least and the four children will be null this is in the case if the grid values are same but here in this case if you see obviously the grid values are not same I sum are one some cells have one some have zero then one zero like that so in that case we will make a root node which will have value as any value one or zero anything you can give is leaf will be false because it's not a leaf right and for the four children right for the four children we will divide this grid into four parts we will divide this grid and we will do recursion the same step the same thing we will do recursion for this grid and for this grid so this is how we will approach this problem okay I hope you understood the approach there is one optimization also to this approach we which we will discuss at the end okay but before let's see the dry run of this approach okay let's see the diagram of this approach for the optimize approach I won't be showing the Tyrant that you will do as a task yourself but I will show dry iron for this one because it's important to you know understand the concept Ryan you can do by a single code also yourself so see what we will do first of all like let's say we have this we let's say this is your x-axis and let's say this is your y axis okay and we are have to uh here since we will check first of all whether all the values in the grid are same or not so we will start from the 0 comma 0 let's say this 0 comma 0 we'll start from there uh so let's say this is your here this is our y okay so this is your X and the let's say this is our y so uh you will be let's say we start from 0 comma zero so what will happen um first of all we will check whether all the values are same or not okay let's say all the values are same or not so for example uh see here no all the values are not same so we will make a node in which let's say we create a node which value we will set as let's say one you can set 0 also is leaf will be set to false okay and this is the second step this is the third step fourth step will be to make a call on C what will be the steps like let me just write it so after we check whether all values are same or not so if they are same okay if they are same so we'll do different thing if they are not same so we will do different thing so if else will be there if it's same else not same so if it's same we will make a new node we will make and we will return that new node and that node will be having value let's say all the values are one so value will be one leaf will be true and uh all the children will be for none but if it's not same so that is in this case all the values are not same so we make a new node we will give it value as let's say one is leaf will be false and for the children now I will do recursive call so is for top left let's see for top left okay for top left so let's say this these coordinates are X1 comma y1 let's say these are X1 comma y1 okay so the coordinates for C we were checked we were initially giving 0 comma 0 that is the starting top left coordinates we were giving of the grid top left of the grid that is these this is what top left coordinate right similarly when we will divide this grid into four smaller grids we will be giving the top left uh coordinates only in the recursive call so here top left will be this then top left will be this one and top left will be this one in the recursive call so basically recursive function will be something like this is your recursive function it will be like uh the root the current uh starting point that is X then y and the length as in like how much you have to go like for example in the bigger grid you can go till the whole length of the grid then since this is now smaller so your length will be divided by half because earlier your length was this now since you have divided the grid so it will be L by 2 now the length of the this grid right so these three will be the parameters in the recursive function so here see for this again if you see now in the recursive call let's say now we have this grid which is great just focus on this grid in this grid now see all the values are same so what we have seen we will first of all check whether all the values are same or not if all the values are same so we will make a new node and value will be one whatever the value is of the grid value is one year one is leaf will be true and all the children will be set to null and this node we will return so for this one we will return the node and it will get stored here in the top left of the bigger grid okay this is our recursion will work all right now this was for the top left now discuss let's discuss for the top right so for the top right we have to give the coordinates of the this top left corner right like this is the top left top right grid but the coordinates will give this one right so what will be these coordinates if this is X1 and y1 so this will be X right X1 comma y1 plus let's say this is 8 right so y 1 plus 4. okay y 1 plus 4 because if this is your starting this is your X on the X only right X is this one this is a x but y you are going 4 spaces ahead four spaces ahead right this is your Y axis so for this coordinate four spaces are head in this direction that is your coordinates will be X comma y plus 4 this will be your coordinates for this one okay so in recursive call you will be passing X as this y plus 4 and length will be what the total length which was earlier divided by 2 because this will be the total length similarly if you see now for this grid so for this right this is the same case as this one but this is different top right in the top right values are different they are not same like these so again here recursion will help we will divide it into again the grid right so this will be one grid this is a second grade third grade and fourth grade so in this way your version will work okay I hope you under understood like some I hope you got some idea about this let's see the code once and uh it will be better with code so see we have this function right construct and we have created this recursive function helper function in which we are passing the grid which we have the initial coordinates 0 comma 0 which we are taking this top left coordinates top left of the entire grid okay and the grid size which is the length that is this one this length or this because this is a square Matrix light so it will be n cross n that is the length will be C now let's see the recursive function so as we discussed these steps first of all we will check whether all the values in the grid are same or not so for checking that we have created this function same value in which we go to the grid we just iterate in the entire grid and we check whether all the values are same or not if all the values are same we return true otherwise will return false okay so if all the values are same so what we did if all the values are same we just created a new node right so we will create if all the values are same we will create a new node it will have the value of those value whatever value is there in the grid and the leaf will be true okay the degree will be true so basically here this node they are just taking two values okay here they are just taking two values otherwise if the uh if it's not the same value okay that is all the values in the grid are not same then what we will do will make a root node which will have uh this is what once again let me just close this so yeah we will have this root node in which the uh this value will be false and uh is leaf will also be false and the all the children we will assign values by doing the recursive call so in the recursive call for the top left let me just close this so for the top left right for the top left 0 comma the current let's say this is X1 comma y1 so those will be the coordinates for this top right X comma y plus 4 uh will be the coordinates that is X One y one then X1 this will be y one plus length by 2 so 4 is what 4 is 8 by 2. and this is the total length of the grid the smaller grid so obviously that will be length by 2. similarly so in this way you will populate the children so this is the uh this is the code I hope you understood some part of it and if you are not able to understand please see the explanation again and try it on yourself let's understand the time complexity for this okay so see here time complexity is what initially what we have it agreed okay we have a grid on this grid what you have we are doing first of all we are have this function same value right for this uh we are traversing this right we are traversing this so how many calls we are like how many cells are there for each cell right we'll be doing the same we'll be doing that thing so it will be n Square cells right and every time the size of the entire grid is getting smaller right so if total the size of the grid was like eight length like one side so uh in the next one it will be decreased by two half by divide by two right so that means there will be log of n levels right log of n level so initially if grid was one now in the next level there'll be four smaller grids right as we saw here there will be four smaller grids and then there will be four more smaller so that reward like for this one again there will be four smaller right so here let's say if the total cells it total sells and for each grid total cells are reduced by four let's say right but there will be how many calls four calls so total calls at each level be n Square right and similarly here let's say here the total cell got reduced by 8 but since there are eight calls there will be eight calls so it will be eight so n Square calls will be there for each level and how many levels are there login levels so n Square log n will be the time complexity for this all right and space complexity will be login which is the recursive stack because here this will be a recursive stack right so space that much space will be taken so now we will discuss how we can optimize this approach right how we can optimize this approach that's also very important so optimize okay so if you see here in this code what repetitive work we are doing what we are doing we are every time we just do we check right whether it has same value or not this is some repetitive work checking same value if it's same value because see uh let me just quickly paste the tree again so this grid again so see when you check for the first grade when you uh check for whether it has same values or not you go to this entire grade right iterate in the entire grade after that when you divide it into smaller grid again you go to these cells first initially for the uh this whole grid right you've got you have gone to each cell and for in individual smaller grids you are again going to these cells to check whether they are same or not this is some additional work right repetitive work repetitive how we can avoid this checking whether it's same or not how we can avoid it is C let's understand that so it's a good optimization just hold on so what you will what we will do right we will do the recursive calls first that is recursive calls first so from recursive calls we will get the top left node like node value top right node value that is this thing we will get oh sorry top left we will get in this one the node value which is basically the node which is representing this grid we will get here then top right node which is representing this grid we will get here bottom left we will get that is the node which is representing this grid and bottom right we will get so these four we will get okay we will get now see now let's say if this grid was all one is great all one's grid was it was like having all once in that case these smaller grids will be Leaf nodes why Leaf nodes because they will have same values so they ultimately will be Leaf nodes and also they will have same value one so value will be one for the individual smaller children and each Leaf will be true right I hope you understood this why these children will be the smaller grids will be leaf so we will check right once we got these four values we will check whether they all are leaves right we will check now this is very important understand guys so we will check whether all these four are leaf and have same value if they all have same value and all are leaves it means the grid the total like the bigger grid have was having the same values so what we will do we will just return a node having the value as whatever these value is like let's say one and since all the values are all the smaller gates are leaf and have same value so obviously this entire grid was also a leaf right so Leaf will be true otherwise if this is not the case else just return any value comma false because it's not a leaf so with this approach right with this optimization we are only going to each cell once we are not repeating going again in that case time complexity will get reduced to n Square space would be same that is log n so I hope you understood this uh let's see the code for this once I know it's a tricky problem but it's very easy if you have understood what they are trying to say so let me show the code for the optimized approach so here see what we are doing this is a base case right if length is one meaning that we only we have oneself so obviously for that one the leaf will be true and value will be the value of that cell okay value of that cell and the leaf will be true so we will do the recursive calls and if all the nodes which we get are leaf right all our leaves so if there is a check if all are leaf and the value of all of them are same like all the values are same then we will just simply return a leaf node we'll make the leaf as true and we'll just give the value which is of these Val these nodes like one or zero otherwise if not the case then obviously they have different values and all that so we will just return false and top left top right bottom left bottom right okay here automatically these values will be null because we are not sending anything right automatically the children value will be nut so I hope you understood the problem and the approach guys I have tried my best to uh you know explain it let me know in the comments of any doubt if you found the video helpful please like it subscribe to my channel and I'll see in the next video bye
Construct Quad Tree
construct-quad-tree
Given a `n * n` matrix `grid` of `0's` and `1's` only. We want to represent `grid` with a Quad-Tree. Return _the root of the Quad-Tree representing_ `grid`. A Quad-Tree is a tree data structure in which each internal node has exactly four children. Besides, each node has two attributes: * `val`: True if the node represents a grid of 1's or False if the node represents a grid of 0's. Notice that you can assign the `val` to True or False when `isLeaf` is False, and both are accepted in the answer. * `isLeaf`: True if the node is a leaf node on the tree or False if the node has four children. class Node { public boolean val; public boolean isLeaf; public Node topLeft; public Node topRight; public Node bottomLeft; public Node bottomRight; } We can construct a Quad-Tree from a two-dimensional area using the following steps: 1. If the current grid has the same value (i.e all `1's` or all `0's`) set `isLeaf` True and set `val` to the value of the grid and set the four children to Null and stop. 2. If the current grid has different values, set `isLeaf` to False and set `val` to any value and divide the current grid into four sub-grids as shown in the photo. 3. Recurse for each of the children with the proper sub-grid. If you want to know more about the Quad-Tree, you can refer to the [wiki](https://en.wikipedia.org/wiki/Quadtree). **Quad-Tree format:** You don't need to read this section for solving the problem. This is only if you want to understand the output format here. The output represents the serialized format of a Quad-Tree using level order traversal, where `null` signifies a path terminator where no node exists below. It is very similar to the serialization of the binary tree. The only difference is that the node is represented as a list `[isLeaf, val]`. If the value of `isLeaf` or `val` is True we represent it as **1** in the list `[isLeaf, val]` and if the value of `isLeaf` or `val` is False we represent it as **0**. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** \[\[0,1\],\[1,0\],\[1,1\],\[1,1\],\[1,0\]\] **Explanation:** The explanation of this example is shown below: Notice that 0 represnts False and 1 represents True in the photo representing the Quad-Tree. **Example 2:** **Input:** grid = \[\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,1,1,1,1\],\[1,1,1,1,1,1,1,1\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\],\[1,1,1,1,0,0,0,0\]\] **Output:** \[\[0,1\],\[1,1\],\[0,1\],\[1,1\],\[1,0\],null,null,null,null,\[1,0\],\[1,0\],\[1,1\],\[1,1\]\] **Explanation:** All values in the grid are not the same. We divide the grid into four sub-grids. The topLeft, bottomLeft and bottomRight each has the same value. The topRight have different values so we divide it into 4 sub-grids where each has the same value. Explanation is shown in the photo below: **Constraints:** * `n == grid.length == grid[i].length` * `n == 2x` where `0 <= x <= 6`
null
null
Medium
null
1,615
Hello hello everyone welcome to write and analyze so in this video you will act deal promise mixture 16 mins you need to find maximum retail pack take it medium then please do apachya video android watching and depression long tilak pisces Fruit Predictions is 551 Number of Citizens Should Deal with Roads Connecting Ray to Cities Well Organized Always Interview for the Connection Between Themselves So Let You Rot the Guide PIN Jelly Road Connecting Her Through City 100 24 2012 That Will Do From Time to Time And Friends Thank You To Take Any Fear Of Two Cities Such Units In The Fruits Of Living And Approaching City Limited Number Of Total Number Of Maximum Do A Song That Will Different Maximum Land Of The Giver Network Aa Ka Song New Hai Net Fabric One Person On 36231 Dual Character Certificate is one insomnia simple candy crush letter to the match were so let's with examples of scientific loot 0123 fourteenth 46 number 203 pure road information this ribbon dozen road from drut off positive vibration 0 share0 tweet0 0 daily ruby ​​equal to road share0 tweet0 0 daily ruby ​​equal to road share0 tweet0 0 daily ruby ​​equal to road 120 Vaishnav A At This Time Sadho Information Unit's Answer Gautam Buddha Reaction On That Improve Deposit Closed Andar Must Want Pt. Amazon Two In One Two Three Four 209 Not Manufacture Prayer Of Lord Sweetcount What Is The Rodi Patthar Patna City Plus And It Is Painful If Rotting Tree Senior Commandant is marked that Bigg Boss first select 19000 Andhera 3021 Vikas Note Sarkar Road between two and that and Ravana attack Pawan entry that both the road typing 153 for the road increase till 232 account is 181 center and it will be Suji Beg Padharo Ray Similarly for Example Two Nature Of Breast Cancer Breast Enlargement Clear So This Can Do It In The Group Love Of Conservation So Manju Tags Page 10 And You Can Share All Avengers Infinity War Doing A Loot So Let's Beach Center Forward member also per stratfor 512 is me too protective android information and need to find the number of road to connect with silver city scan page number 90 you to maintain and it is vitamin e so surprise gift dynasty's must connecting city-2 600 video. com On the connecting city-2 600 video. com On the connecting city-2 600 video. com On the day of 200 units, certificates will always be with you. Travel Let's Take Every Rhodium Bharosa Commission Superhit Full Length Information So Let's After Oo Yes Definitely Pomegranate One Service Electricity Connection From Two Cities And So Will Make End Semblance Of Dadar And 120 Million Readers Every Day Tomorrow Morning Duty Akram Bhai 20202 Pregnancy Therefore General Suitable 102 Empowerment Half Hour Preparedness Sexual Booty Shoulder Dabangg Status MP3 Audio Call 100 Grams Boiled and Sprouted to the Video then subscribe to the Page Torch Start Pimple Sanghs of all parts of tweeting time jab max kar do loot which friend if a computer time America runtime hisearch dictionary app hua tha sundha par meet you next 9 newsroom se me so no blogger thanks for watching play list powder videos 225 more Feedback thank you to
Maximal Network Rank
range-sum-of-sorted-subarray-sums
There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`. The **network rank** of **two different cities** is defined as the total number of **directly** connected roads to **either** city. If a road is directly connected to both cities, it is only counted **once**. The **maximal network rank** of the infrastructure is the **maximum network rank** of all pairs of different cities. Given the integer `n` and the array `roads`, return _the **maximal network rank** of the entire infrastructure_. **Example 1:** **Input:** n = 4, roads = \[\[0,1\],\[0,3\],\[1,2\],\[1,3\]\] **Output:** 4 **Explanation:** The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once. **Example 2:** **Input:** n = 5, roads = \[\[0,1\],\[0,3\],\[1,2\],\[1,3\],\[2,3\],\[2,4\]\] **Output:** 5 **Explanation:** There are 5 roads that are connected to cities 1 or 2. **Example 3:** **Input:** n = 8, roads = \[\[0,1\],\[1,2\],\[2,3\],\[2,4\],\[5,6\],\[5,7\]\] **Output:** 5 **Explanation:** The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected. **Constraints:** * `2 <= n <= 100` * `0 <= roads.length <= n * (n - 1) / 2` * `roads[i].length == 2` * `0 <= ai, bi <= n-1` * `ai != bi` * Each pair of cities has **at most one** road connecting them.
Compute all sums and save it in array. Then just go from LEFT to RIGHT index and calculate answer modulo 1e9 + 7.
Array,Two Pointers,Binary Search,Sorting
Medium
null
141
foreign Loop in a linked list so let's do that so let's say we are given a linked list which might contain a loop like this you need to find if there is a loop or not so a link list might have a loop might not have a loop you need to figure out whether it has a loop or not so how does a loop work in a linked list remember in a node you only have one pointer so it's never possible to have two nodes linked right this is never possible that will have two nodes linked so how does a loop work here Loop will work only if like they are connected in a cycle like one point to the other point should be this right that is the only way it can never happen that it's like this they both point to the same so because same nodes two cannot originate this kind of stuff is never possible right so there's a difference between graphs Loop and a linkless loop so those of you have done graphs would know this is very much a possibility in graph but it's not possible in linked list so what we can simply have is a set of all the ones that are visited so I visit this I put it in the set I visit this put it in the set so on so forth if I ever get a node which is already visited then I know that it's a loop so I can have a set or a map kind of thing or any storage which tells me what are the unique elements in it okay so I put this whichever I am going through by iterating I just put it in the set and I check before putting have I already seen this element if yes then I'll just say it's a loop okay but why should we buy if that's what I'm asking why they have to meet anyways I'll prove that don't worry about it so for this I'll write a quick simple code we simply have a set and I'll say while so let's say I have my pointer head while head is not equal to null you keep on going so you check first if you are set already contains head that means it's a loop and you break otherwise you just add current head to the set and one head equal to Heads next does this make sense create a simple set whatever node you are visiting add it to the site keep on going if before adding you see that it's already there that means I've already visited this that means it's a loop and I'll break can you tell what is the time and space complexity here we are taking an extra on space this is the problem time is still when we are just going over it once but set a space is when this is the worst so we need to improve one space and we can do much better than this that I'll talk about so again we use slow and fast pointer approach and let's see how so let's say I start two pointers here slow and fast and we'll do our general thing that is fast should move two times slow should move once so a fast move two times it reaches here slow moves once it reaches here then fast moves twice it reaches here slow moves once it reaches here now can you see that both slow and fast have entered the loop in this particular case can I say now they'll never leave the loop like if I keep continuing moving fast moving slow they'll just stay in this Loop they cannot ever go out if it has a loop let's look at the distance between slow and fast pointer okay right now from one side the distance is one two three four nodes and from the other side it's like one node in the middle now let's take one more step move the fast pointer twice and slow pointer once and see what happens so fast pointer moves twice one two and slow pointer moves once here now if you see the distance from the one side between them has become 2 and from the other side it has become three right by because one guy took two steps ahead the other guy took one step ahead so although the direct distance between them has increased because it's a loop the other side distance has reduced let's extrapolate it let's go one more step what will happen this will become three this will become two then this will become 4 this will become 1 then this will become 5 or from one side the distance will become 0 and they have actually met can everyone see that distance will be slowly closing off in One Direction and they'll have to meet at some point or the other I'll repeat it quickly so I'm saying when they entered the loop this was fast this was slow from this side the distance is one from this side the distance is three now when this guy takes two step ahead and these guys take one step ahead the distance increases that's obviously true right if one guy is fast one guy is slow the distance increase but because it's a loop the other side distance decreases by one because it decreases by one we can say it will end up being 0 at the end so it's not just about one making two steps other making one step even if one of them was making three steps and other was making two steps still they would have met right because the distance will be again closed by 1 unit if this guy took three steps ahead this guy took just two steps ahead that means still the distance between them will be closing right but this cannot be said with 4 and 2. why changes of two units can you see like if the initial distance is let's say one node and three four nodes it will change by two units so from one it will go to three from four it will go to two so it might not ever get to zero can everyone see that yes if slow is 2 fast is 3 it will work right why it will work because the Gap difference that happens is of one not exactly jump difference should be one actually it's related to co Prime uh but for that you need to go a little bit deeper into modular arithmetic but I'm just saying if someone asked you is two and one the only speeds that are possible the answer is no even when we do three two four three five four these are all also possible okay there are some more but for that we need to get into detail of modular arithmetic so we won't do that but at least this much is very easier to spot right so basically what you do is you keep on running slow and fast pointer if they ever meet that means that there is a loop okay so simple idea
Linked List Cycle
linked-list-cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**. Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** false **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Easy
142,202
236
all right let's talk about the lowest common ancestor of binary trees so you're given a binary tree and you want to find out the lowest common ancestor so uh here's the simple example so this is a tree and you are given a root and then you need to have what p and q for a full target so five and one is actually the one the children of three right so you want to find an ancestor which is three but it has to be the lowest one so imagine like this is five and one and there's an initial seven will connect with the three and you still have to return three because i am one is the children of the three and then they actually find it right so this is pretty much the idea so again uh what is just i mean just for example like pq right five and four right so uh the route is three right so you traverse the left and traverse to the right and then to see if you have it or not then you don't have it then you traversing on the left right and then five by okay five you do have it but how about the four right so you want to traverse the left and right and then to see okay now you find it and then what is the lowest ancestor which is by itself right so you return five so uh the algorithm uh looks pretty simple so uh just using a recursive solution so i'm just going to call it and you'll be able to follow along so if the route is actually put or no right i'm going to return now right so i need to traverse my left using the recursion so i'm going to see if i have my root which is equal to the paq right the root of left here right so if i find it so if root is actually to the p or root is actually equal to q which means i find it right so i will return root so this is my ancestor right fold either left or right so just think about this right bottom one right and actually x3 right over here so three does not equal to p that's not equal to uh that's not equal the q right so i traverse for the left and right so root of left is equal to five root of uh root on right is actually equal to one so i will return what the root so which is what which is 5 and 1 just fine one for the left and then right but the problem is what if the left is actually good or no if left is actually to know you do something right and then if you're right it's actually good you do another thing and everything else which means left and right are not of no right just for example in this case five and one is a children of three right and i already find it right i really return five and one for this right so the parent the answer's parent should be all right so what happens for left and right are the no so for example this one so i traverse from the three right p and q is actually five and four right so i'm passing the pass in the root of left and right alright so again for the router right you just recursively call this uh children and then you actually return no because you cannot find it right so uh okay so when you cannot find it the right is actually good no and then the left your in the left is actually equal to five right because you find the right so you'll return the root which is five so uh in this case left is five and then y is no so in this case i know my right side is no and then everything else should be on the left right everything has to be on the left so you'll return that and then you should be return the first one you find so imagine like the p imagine the p is not five p is actually two p saturated two right so you're just traversing on the left and right so this is no right the right no so let me do it right now and then the left uh five by the side equal to two right so i will traverse the left and right again and then now i find that this one is what this one is actually equal to the p right so i would just say okay this is p and i will traverse for four right so this is the idea right so you have to find the lowest ancestor so if left is null then you'll just return right and this is pretty much your idea so uh what happened oh yes sorry oh there you go all right so let's talk about the timing space the space is this one and this is actually like what constant right space is constant and then for the time you do have to traverse every single one of the nodes to see if you have p or q inside the tree like your return one and your return uh true i mean the root or not right so for time is open for the space is constant and again what if the node is not inside the tree so uh again so for this one this is actually really simple i when i traverse 11 right and my right return null right and my left return 5 right and then in this case i already know my phone is underneath of five uh yes it's underneath of five right so i don't have to keep traversing for the rest of it so if you look at the code you will be able to understand i don't have to because i already returned five in this case right so i don't have to traverse and i know for the 304 is actually underneath of my 305 so i will return right away so uh in this one this is uh this is okay but what if you have a p so p is actually equal to phi right q is actually equal to one what happens if there is like nine over here and then you don't have a p inside the tree then you will get an arrow right p is not in a three so if you want to traverse a tree which does not exist either or p or q this question will be even harder so uh in this case this is considered median so i'm not going to talk about how you solve it because i am not 100 sure uh the only thing you have to know is that you either check there's a tree not uh i mean does p and q exist in the tree first then your traverse will ancestor later so this is my first approach but i might be wrong but whatever but this is not the pressure related but this is the thing you have to think about what is the tree no that's not in the tree right all right so for the for this question solution this is pretty simple and i'll see you next time bye
Lowest Common Ancestor of a Binary Tree
lowest-common-ancestor-of-a-binary-tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)." **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1 **Output:** 3 **Explanation:** The LCA of nodes 5 and 1 is 3. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4 **Output:** 5 **Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[1,2\], p = 1, q = 2 **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` will exist in the tree.
null
Tree,Depth-First Search,Binary Tree
Medium
235,1190,1354,1780,1790,1816,2217
786
Hi guys welcome back to my channel cpp code and today we will do the question number 786 of the code what is the smallest prime fraction given in the question you are given a sorted integer which is an array containing one and prime numbers okay let's get the integer Jars of array R are unique We are given an array We are given a vector In which the elements are all the prime numbers And one is also given to us So we are given that along with that We are given an integer Jar K What is the function of k? We have to do this. Look, for every i and j where i is both smaller than the length of error. Okay, we consider the fraction er r of i divided by er r of j. We have to compare the fractions. Look, we have to consider. In this we have seen what is to be returned, smallest fraction of return is considered. Look, we see from the first test, what is to be done, see, it is becoming a fraction. Look, the fraction to be considered in sorted order is that it is becoming a fraction, 1/5 of this. A fraction is being becoming a fraction, 1/5 of this. A fraction is being becoming a fraction, 1/5 of this. A fraction is being formed 1/3 2/5 1/2 3/5 2/3 What we have to do is to formed 1/3 2/5 1/2 3/5 2/3 What we have to do is to return the third small fraction, okay third small which one is this first small second small third small 2/ 5 Okay, we have to return this, we will 2/ 5 Okay, we have to return this, we will 2/ 5 Okay, we have to return this, we will do this, see how to do this, first of all we will have to create a priority, how will it be, we will create a pair of pairs, we will also create a pair of pairs, see how we will create this, first we will type define that. Let's take what will happen by typing, instead of writing such a big pair, we will simply keep a small name, we will enter it properly by typing pair int one, so we will not put int here, we will put double. I will tell you later why we did double and its. After this, we will keep one more pair, okay, we will name it p and now we will name it p, okay, we will name it p and now we will make one in it, we will make m, we will take the corner vector and one which will be the cutter greater function ter function. Par passing it is not int, PP has come in it, okay, now we have made our heap, now what will we do in it, see, first of all, we find out the size of its R, E 10 = A find out the size of its R, E 10 = A find out the size of its R, E 10 = A R, okay, we have found the size. So see, first of all, we will not have similar things in it, we will push them in priority, but how will we push, see, first we will select our forest, okay with forest, first we will insert f and insert it because this is the smallest fraction. Right, what will happen after that the next fraction will be 2/5, we will insert this, fraction will be 2/5, we will insert this, fraction will be 2/5, we will insert this, then the next will be 3/5, we will insert this, then the next will be 3/5, we will insert this, then the next will be 3/5, we will insert this, see how, we push for it, we will start from zero and where will we come? From how far will it be n is fine, it will be up to n-1 fine, it will be up to n-1 fine, it will be up to n-1 and we will push it in pairs. We will push it in pairs. How will we push it? If we want to push in pairs then we will have to put curly braces. Look into this. First, we will push the fraction that is there, now see 1/5, when we will push the fraction that is there, now see 1/5, when we will push the fraction that is there, now see 1/5, when we divide it by 5, then it will not remain 1/5, it will become 0.2 not remain 1/5, it will become 0.2 not remain 1/5, it will become 0.2 to keep that close to us and we will have the value of f. Yes, we will send one more thing, what will we send? We will send the index of both of them. Look, first we will put this in this A R of I off and error in that, we will put Er A Myve. Okay, first of all we will put all these elements in this. Okay and we will do this also, like see, the division of these two will come to zero, why will there be an integer above and below also, an integer, so instead of one, we will make one double. Okay, now after this we will add one to this. And f two things, these are our indexes, we will push them, okay one will have index, a what will happen to one, n My, okay n-1 index has been pushed, now okay n-1 index has been pushed, now okay n-1 index has been pushed, now after this we have pushed, now we will not in this Which is ours, let's pop its elements till K-1, not in this Which is ours, let's pop its elements till K-1, not in this Which is ours, let's pop its elements till K-1, how to pop, look, I, in this also, we take A, E, 0, and A, where will it go from K to one, we have to pop, neither from K to K, two. We will run a loop, okay look, what should we do inside the loop, first of all we will store the top which is ours, peep one, okay, after we have stored it, after that we will pop it. After this, we will check if we have done it, if it is what it is, which is s of seconds, which is seconds of seconds, if we will subtract one from it, then we will move it back one index and it is increased by the number of our s of seconds. If it becomes bigger, then we will push it. If s off means look, if our index which is on our left and if it crosses our index on our right, if it becomes more then we do not need to go further. Look now. Look, if this is how our index is lying, then we will know what to do, then we will put it in it, but how will we push it in it, we will push it in it will be a little bit messy, see, pay attention, first of all, we will make it double. Make this double we made a [ we made a [ we made a After this, we will put the index of this one. How will we put the index of this one? Okay, and the index of the other one will be ours. We have also put the index of both of them. Okay, now look, the indexes of both have been put. Now let's make space after this. Let's do a little like this, let's complete it. Yes, look, we have created it, we have pushed it, okay, after this we have taken out that many elements, after that we will come out of the loop and directly we will return. What will we do, we will return. We have to return a vector of int, we will return whatever we have, which will be the first of the second, okay, we will put that in the first index, and after this, what will we return second? Do the same. We will give second, okay, we will return second, let's see, we may have made some mistake in this, we may not have made any mistake in this and first and second minus and first minus are okay, now we do this, run submit and see that the compiler is coming on this line. I am coming, let's see, yes, look, I have applied the cell, wait, okay here also I have applied semi calculus, let's go, see, it is accepted and it has also been submitted, look, what have we done in this, see, the question is a little bit crooked, a little bit, that's it. In this, we had another approach by which we could do that too, but what would have happened with that would have been our time, we would have to put each one of us one by one and after that we would maintain the maximum size of one of us and keep it at the same size. And the element on top of it would have been ours. We could have done the smallest element of the next element like this but this is the complexity of the approach. How will we do it? Look at how we did it. Now we have made a heap. We have made a min heap. Min heap is this. After we have pushed the elements in the min heap push the elements along with their indexes because this will be pushed s this will be pushed as the double value okay after this we have pushed the indexes along with this and after that we have pushed a And put a loop so that we have taken out the main elements which we have, okay, we have taken out the main elements, how in that, first of all, what did we do inside our loop in the answer, first of all, we stored the top which is in it, after that If its top is the second of its top, then it is okay, if we do a minus from that and it comes more, that means, if its left index is small, then only then we will push it, okay, so we have pushed all this. In that we also sent the index. After this, it's okay. If it comes out of the loop, then we will simply return a vector. What will be the vector which will be our top two indexes? We will have our top two indexes which will have the value of A RR. It will be okay, after going to that index, we will put the value coming in our vector and return the same, okay, this was the question, if you have any doubt then ask in the comment and let's meet, see you in. Another Video With Another Amazing Question Till Then Take Care Thank You
K-th Smallest Prime Fraction
search-in-a-sorted-array-of-unknown-size
You are given a sorted integer array `arr` containing `1` and **prime** numbers, where all the integers of `arr` are unique. You are also given an integer `k`. For every `i` and `j` where `0 <= i < j < arr.length`, we consider the fraction `arr[i] / arr[j]`. Return _the_ `kth` _smallest fraction considered_. Return your answer as an array of integers of size `2`, where `answer[0] == arr[i]` and `answer[1] == arr[j]`. **Example 1:** **Input:** arr = \[1,2,3,5\], k = 3 **Output:** \[2,5\] **Explanation:** The fractions to be considered in sorted order are: 1/5, 1/3, 2/5, 1/2, 3/5, and 2/3. The third fraction is 2/5. **Example 2:** **Input:** arr = \[1,7\], k = 1 **Output:** \[1,7\] **Constraints:** * `2 <= arr.length <= 1000` * `1 <= arr[i] <= 3 * 104` * `arr[0] == 1` * `arr[i]` is a **prime** number for `i > 0`. * All the numbers of `arr` are **unique** and sorted in **strictly increasing** order. * `1 <= k <= arr.length * (arr.length - 1) / 2` **Follow up:** Can you solve the problem with better than `O(n2)` complexity?
null
Array,Binary Search,Interactive
Medium
792,1672
844
That's what guys welcome to taken to live Nivedita and this video we are going to solve back space string compare switch problem what is your friend tinde rakha SAT what do we have to do this again must have seen a tractor whenever there will be joy neither that element You have to remove that character along with it, before that your character will also have to be removed. What do we have to do with both these operations? We have to perform on both the settings, after that complete both and check whether both are equal or not. Both of them get equal marks, what will we do, will we start the run, will we sprinkle water in the opposite direction? Let us first understand this problem as an example, what did Edifice Chief Harshit Wright give you here, out of these two, have we given you, now we have kept our hands straight, sorry here, now this is shady. If there is humor, then here we look at A here that see what will you do from here, do you guys understand this problem, if it is here, then let it be, B is, let it be, but here, what is he saying in such a condition that you Here you have to do 19, remove the first character, remove it, then you will learn that this is the fashion, now you will do some editing and remove it, otherwise what is the defense here, what is your ANC, let us check here that this What will you do after that, then hate and the character before that, then this item will be removed, then here it is not fast, what happened to you, AC is done, then both of them, what will you do to return it, you will start here right then. Here you will see that we will leave this LED, we will leave this BJD away, then what to do in Harshit condition, we are removing this character, the seventh one before this will also have to be removed because of the publisher, then what should we do in present condition? The tractor before that will have to be removed, this one will also have to be removed, this has been noted, child, this has been removed, this has been noted, child, your intestine has become right, become interesting here, we will see for this after this, so we will leave the surgery but there is a lizard in it. What has to be done is to remove this one, the cancer before that will also have to be removed, then we will see the deposit for D, let it remain like this, disgusting, what will we do, come, we will remove this one and also remove D. Both the memorandums have become interesting here. Both of them have s, so what will we do in this condition, we will start the return, then let's see, this is acid, what will we do in the festival function, remove this also and remove that, then we will give like serial, still we will do this here. So meanwhile, my party is left here and on the other side it is not there at all, so what will we do, if we do the return forms, then we will see how to solve this problem. Ok, see here, the problem is what is our problem, what will we have to do whenever there is a hash. What to do in that condition is to remove both the preceding character and half inch together. For the lights problem, let's see whether your mean will be our focus. Do we have to check all these index abstinences? Is it okay to check all the indices? What to do on all the indices? If we want to straighten it, we will also get hips, so what will we do, we will remove that character and we will also remove the previous tractor on it, so what will we do, we will take eye zero and an injection, we will check. If you click on it, you will check what is it. If it is not there, then let it be, then we will check it on one, we will make it further, we will check again whether it is here also, yes, is this not true? Go ahead and organize this IPL here, you will organize it on this index that this house is in this condition. What will you do, correct this index, the interest behind it is I, right here, what I have to do is remove two characters from this index or not, remove both of them, remove them, then what will we do with I, right? My loot is here now, what will we do from here, we will remove this character from here and the previous one by injection two by two and now what will we do here, you will bring on intake, okay if one jaundice comes, then actually one what will happen here. After removing this, if there will be any AC left, then what will happen there, zero one will be that the tax will be checked for this is not your goal, this is fashion, we will keep away the additive of yours, both of these are gone, then look for this, I will do the chart from here, I will check, remember. Is it or not? Remove the eye on the mouth next. Okay, so you will chat here. This hatred will move forward. Then here it is regional. What is the situation, what will we do in the mission. With the injection behind this, we will remove two characters, both of them. We have removed it, we came here with it, if it is dead then you will bring it here so that if you remove it now, will it be left? So now on whom did I come to this place, what will we do, we will take it to the back also, okay then we will do it for SP, if not, then both of them have given their AC, we will check, if there is like or cycle on 29th, then you will start money. Will you do his court case? What will happen if your location is green? Your Jio index is fine. From here, in that condition, you will be connected to the one behind. No, we will hit minus one. If it is not possible, then what will we do with its mark? Current index. We will just remove it, okay, we will not go back because - otherwise it will we will not go back because - otherwise it will we will not go back because - otherwise it will go - but there cannot be any go - but there cannot be any go - but there cannot be any light, so you will do it from here, it will be of our appointment, whenever it is equal to zero, what will we do below it will be a tractor on the media. OK, this is your SIM scan. For example, let's see this is also the city. Yes, baby show and auspicious and here's something, now what should I do, it has come here, will you check whether it is there or not? Let's move ahead. It will think like this. What is not there, he will ask, come, what else is there, bring the word I here on One Takes and remove it, remove that, dynasty Africa, this will be it, right, this and half inch, this will be I, side on One Takes, now here on two. They came here, if you bring them, then you will do this thing of luxury on the forest for this, then you will get laughs, then remove this, you will remove this also, now you have become a scientist leader, you will do this for this because I have come, check on this ID that this The article is not abstinence, will you do it for the state, yes, no, it is disgusting, so what will you do, you will remove this and remove that, remove both, going to the previous index, what will we do, we will remove both of them from here, take two tractors to their After that, what will we do, I will look at this or what will we do for this, you will see the fashion, we will move ahead, what will they do, we will remove both the characters, go to the previous index and remove 2 characters from here, both of them will be removed, final. What will become of your intestine? Pimpri has become. This is what Randhawa will start. If you have seen it with your partner, then how will you solve this problem? How will you code? You have seen it in your voice mail. I am explaining to you that I have come here and found the truth. First of all we will see for mess that I listen size should be there and what will we do add it on an index what is the harm first and check the size is this yes you got that you will see is not against is i0 will be i0 what will you do in that condition Remove only one cutter from I index. At this time Katrina herself will be there in Meerut, then what happened if she trampled here, there will be a mark of only one cutter that you will check in it. If there is no duty on import, if there is any other iodine ji, then that condition. What will we do in I? The icon behind the index will be played on the reminder. Its two character sets are grouped here by two. Then Ai So now what will we do here I - Ai So now what will we do here I - Ai So now what will we do here I - Man Kare Lekin Hum I - Mangal Means Jo Aap Man Kare Lekin Hum I - Mangal Means Jo Aap Man Kare Lekin Hum I - Mangal Means Jo Aap Friend I Hai, just the one behind him. You are taking this text here, you remove it there, you are not mooding it, no, you are not a fool, like here, finally, what will you do, you will free it - - what will happen from this, that now - - what will happen from this, that now - - what will happen from this, that now after removing, the next untouched thing will be the next item. But it will be done for him, do this if this condition is not being fulfilled anywhere A but yes is not getting it, like this, then you will make this cross out plus, then here you will equip it and do it for the team as well. That I will start from SDO, I will look at the team quarter, if I don't have hands, I will check that there is no ID on this index, I will remove 02111, the other one is Girdharganj, that will be below that, what will we do below that, the previous one will go to the next one. We will remove the tractor, removed it, then I will do - - and if this condition then I will do - - and if this condition then I will do - - and if this condition question is not being met then I will do plus and file, what will we do here, will we specify A, will we check, will the tax be equal, will we return to, will advise, if we are convinced, then it is done. You have got the solution, see here, we have not created a solution for the oven space, here it is there and no one time complexity, and the oven is physical activity light, so we have not used anything extra here, let's drum up Ajay here. That Anushka submit is ok then the comment is done thank you
Backspace String Compare
backspace-string-compare
Given two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character. Note that after backspacing an empty text, the text will continue empty. **Example 1:** **Input:** s = "ab#c ", t = "ad#c " **Output:** true **Explanation:** Both s and t become "ac ". **Example 2:** **Input:** s = "ab## ", t = "c#d# " **Output:** true **Explanation:** Both s and t become " ". **Example 3:** **Input:** s = "a#c ", t = "b " **Output:** false **Explanation:** s becomes "c " while t becomes "b ". **Constraints:** * `1 <= s.length, t.length <= 200` * `s` and `t` only contain lowercase letters and `'#'` characters. **Follow up:** Can you solve it in `O(n)` time and `O(1)` space?
null
null
Easy
null
701
good okay hey what's up guys new right here this is uh Jesus okay one more time hey what's up guys Nick white here I detect Cody stuff on twitch and YouTube check the description for all my information join the discord you know all that stuff it is in the description so this problem is called insert into a binary search tree I don't know how I didn't do this I thought I did all the binary or search tree or just tree in general problems on lead code and made videos for them but streaming right now and I actually noticed that we didn't do this one so let's just do it really quick knock it out of the way I mean I just did it and it was not too bad so if you guys don't remember what a binary search tree is it's a sorted tree if you don't know what a tree is I'd say learn that first but it's a sorted tree where there's binary is if you don't know a binary is its zeros and ones there's it's a base to number system and so binary search is trees have two children nodes can have up to two children nodes so you have zero one or two children nodes and the children the child node on the left side if we look sue min here every child node on the left side of a parent node is going to be less than the parent node every child on the right side of a parent node is going to be greater than the parent node so you can see left here is less than two right here is greater than two left less than seven is greater than four right and you look at these it's going to be sorted so the things on the left are less the things on the right are greater that make sense right so let's just look at the problem what do we have to do so given a root node of binary search tree and if value to be inserted into the tree insert the value into the binary search tree or turn the root node of the BST after the insertion okay so we're given the root of a tree and a value to insert into the tree it is guaranteed that the new value does not exist in the original tree so the value that we're inserting into the tree doesn't exist in the tree already note that there may exist multiple valid ways for the insertion as long as the tree remains a BST after insertion you can return any of them okay so the way to do this is actually not too bad we just did this a second ago but I decide let's make a video you could do this iteratively or recursively and you can kind of imagine this is not being too difficult the recursive solution is actually much easier but we'll do it iteratively in case you like that more so first thing is first there could the root node could be null and then a lot of tree problems the root is null so we just want to check okay if the root is null so if the root isn't all we want to insert a new node into the tree and since the root is null the new node would become the root there's no other nodes when there's only when there's zero nodes and you add a node that's gonna be the root of the tree right the first node in the tree is the root so what we're gonna return since we're returning the root node in the new tree is just going to be the one value we insert there's nothing in there already so we just insert a value it's gonna be the only value so we just return that as the new root node so we just return a new tree node of Val right that would be the root of the new tree after we do it now otherwise we're going to have to take our value depending on what it is look at these examples and find the right spot to put it in the tree right so if we look at this value in this example five right where does five be oh we can't just put it anywhere because they're sorting right so we have to go we look at four in since five is greater than four the things to the right are always greater then we have to go to the right of four right so we Traverse to the spot where we want to insert it and then we end up putting it in its correct place right does that make sense so in here you know like forward you know like this is here oh yeah here's a valid solution for that right here this is it so you know you could see that it's you go to the right you got seven which is greater than four and then you go to the left of 7 which is five that's fine so this is also vowed tree okay so you got some examples there so let's just do it this is the iterative solution so basically what we're gonna do is we're just going to make a tree node called current node and I'm going to set that equal to the root current node is just a like kind of a temporary node that you this is a common thing you do in linked lists or tree thing problems where you just make a trip current node and you set it to either the head or the root and you Traverse to where you need to go and then you can modify the data structure using it as some kind of like temporary so we're just gonna have any loop while true and we're just gonna do a loop here and basically we're going to find where we need to go right so we're gonna use our current node to find the place where we need to go and then we're gonna set either the right or the left of that current node to our new node with the new value that we want to insert right so if we're traversing using the current node is a temporary node to get to where we want to go we need to find where the value should go right so how do we check where the value should go well we can say okay if current node is you know you can do less than or equal to it greater than or equal to the value if current node is greater than or equal to the value that we're looking for and then else meaning less than the value we're looking for if the current node is greater than the value we're looking for then actually let's just let's do it like this let's do less than or equal to because okay if the valid thing about this way if the value is greater then the current node is the root right now if the value is greater than the root we want to go to the right if it's not then we want to go to the left so if we want to go to the right we could just do a check okay if current node dot right exists meaning it's not equal to null if we can go to the right and we'll start traversing to the right and we'll just say current node is equal to current node dot right so that's starting to traverse to the right to find where we need to go otherwise if the current node right doesn't exist and the values greater than the current node like so if it was just a root four and you're adding seven to it right and there's nothing to the right of four well then that's where it's gonna go right you've actually found a point where you can add your new node so we're just gonna say current node the current node has already gotten this else condition here means current node is where it needs to be to actually set the new value so current node right is going to be equal to neutrino tooth now so we found where the node needs to go and then since it's a while true loop we can actually just break out and in the end this is modified but we already had a root in the beginning we're not going to be changing the root so we're just going to return the original root at the end since we're actually just looping finding where we need to go and adding the new node right so otherwise the current node is greater than the valor the val is less than the car note so we want to go to the left right so if we just have to do a check okay there has to be a left node to go to the left start traversing to the left right so if current node out left is not equal to null just like how we did it up above then we just say okay current node left is equal to no current node is equal to current node out left sorry doing this live has a lot more pressure than not doing it live current node left otherwise all we're gonna do is we're going to that means we found where we need to go right if the value is less than the current node that we're at then in there's no node to the left of it then this is going to be less than it so it's going to go to the left of it so just like above it's the same thing as above we just say current node I left is equal a new tree node of the new value and yeah that's pretty much it you break out of it and yeah that's it so it just traverses to the correct point like if you look at it this is this should be fine is this solution hopefully nope this is the mistake I made the first time as well got to put value and you have to say not equal no too much pressure dude do I redo this video now no not redoing the video if people are watching it's just more pressure there you go 100% hundred percent cray so this you go 100% hundred percent cray so this you go 100% hundred percent cray so this isn't the only way you can do it you could do it but we can look through an example if people don't understand it you know maybe people don't understand so basically you're setting the curtain right if there's no node the new value you're adding that becomes the root you make the tree node you return it if there is a root then you set the current temporary node to the root so example this example 4 we set it to 4 we look at the value we say have a while true loop that just gonna go and go we say ok Carnivale is 4 less than or equal to 5 yes it is ok is there a right node 2 4 yes there is so we just Traverse current node is now 7 ok 7 is now current node next loop is current node val less than or equal to Vout 7 less than or equal to 5 no so we're in the else okay we're in the else then we're gonna say ok is there left node 2 7 no so then we are in this condition and we just say 7 dot left is equal to 5 and you can see that's a valid solution right there so there's your example I don't want to take too much time up on this video the recursive solution is so much easier than the iterative so here's the recursive solution right here all it is if the root is null then you return the new value just like how we did in the iterative solution and then the only difference is you can do it recursively the whole time by just saying if the root Val is greater than the value then you just say root dot left is equal and you keep recursing it just keeps for cursing until it gets to the point so instead of resetting a current node in a while true loop it just keeps recursing over and over again until it finds the correct point to actually insert the node and then it finally returns a root at the end so that's pretty much it recursive and it really easier than they Durrett of but both good to know thank you guys for watching that's pretty much it for this video this was live you could see all the people I don't want to open their messages because maybe there might be something bad that I don't want on YouTube so thanks for watching appreciate you love you and I'll be doing some more videos so thank you for watching I'll see you in the next one see ya
Insert into a Binary Search Tree
insert-into-a-binary-search-tree
You are given the `root` node of a binary search tree (BST) and a `value` to insert into the tree. Return _the root node of the BST after the insertion_. It is **guaranteed** that the new value does not exist in the original BST. **Notice** that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return **any of them**. **Example 1:** **Input:** root = \[4,2,7,1,3\], val = 5 **Output:** \[4,2,7,1,3,5\] **Explanation:** Another accepted tree is: **Example 2:** **Input:** root = \[40,20,60,10,30,50,70\], val = 25 **Output:** \[40,20,60,10,30,50,70,null,null,25\] **Example 3:** **Input:** root = \[4,2,7,1,3,null,null,null,null,null,null\], val = 5 **Output:** \[4,2,7,1,3,5\] **Constraints:** * The number of nodes in the tree will be in the range `[0, 104]`. * `-108 <= Node.val <= 108` * All the values `Node.val` are **unique**. * `-108 <= val <= 108` * It's **guaranteed** that `val` does not exist in the original BST.
null
null
Medium
null
1,335
solution to day 16th of October lead Cod Challenge the problem that we have in today is minimum difficulty of job schedule lead code 135 this is a hard level question on lead code and I totally feel the same the problem is based on the concept of dynamic programming but it is easier than yesterday's question so I'll be explaining you this question as well as the algorithm to go about it why the presentation so let's quickly hop on to it so here in this question you given an array and this array specifies the difficult of each job that is given to us the number of days tells you the number of days that you have in total in order to perform these jobs and the difficulty of a particular day is defined as the maximum difficulty of job done on that day for example all these tasks are to be completed on a single day so what would be the difficulty or of the entire activity that you are doing the difficulty of the entire activity would be equal to the maximum difficulty level of for the jobs that you are committing on that day so what all jobs are you doing on that day 6 5 4 3 2 1 and what is the maximum element out there is six therefore the answer corresponding to this array turns out to be six now let's increase the complexity of the example instead of one day let's assume we have 2 Days in total now how are you going to perform these jobs so there are multiple ways out either you can break this entire array into two parts and the point of breakage would be somewhere here what would be the total difficulty for executing these jobs assuming the point of Dage is this point so we have only one task to be completed on day one so let me just write day one over here and we have these many tasks that are to be completed on day two so what is the maximum difficulty task that you doing on day one it is six so let's write six over here the maximum difficulty task that you are doing on day two turns out to be five so the total overall difficulty for this particular schedule turns out to be 11 so one possibility of answer turns out to be 11 let's assume more possibility of answer that could exist and in instead of assuming the breakage point over here let's assume the breakage point is here so on day one you are doing two tasks six and five on day two you are doing four task 4 3 2 and 1 so what is the maximum difficulty out of these two 6 and 5 it is 6 the maximum difficulty out of 4 3 2 and 1 turns out to be four so the second possibility of answer turns out to be 10 is lower than 11 that means it's a better solution so we will go ahead and update our answer with 10 let's proceed ahead next we have as breakage point is this one and in the on the first day we will be doing three Tas 6 5 and four the maximum difficulty turns out to be six uh on the second day we'll be doing three tasks 3 2 and 1 the maximum difficulty turns out to be three the sum of six and three turns out to be 9 is lower than 10 as a result of which we'll update our result let's assume we are doing the breakage point on this particular day this is our breakage point and we are doing the first four tasks together 6 5 4 and 3 the maximum difficulty is six over here on day one the maximum difficulty on day two is 2 so 6 + 2 gives you 8 is lower than 9 so 6 + 2 gives you 8 is lower than 9 so 6 + 2 gives you 8 is lower than 9 the answer gets ofd data to it let's shoot for the last case that we have and let's assume the breakage point is somewhere over here and on the first day you are doing these many task what is the maximum difficulty it's six what on the second day you're doing only a single task which is one so 6 + 1 only a single task which is one so 6 + 1 only a single task which is one so 6 + 1 gives you 7 is better than 8 and the answer corresponding to this particular schedule rule is 7 which is Le which is least out of all possibility that we have derived if you have understood this much of logic then 70% of algorithm is much of logic then 70% of algorithm is much of logic then 70% of algorithm is done and dusted ahead let's increase the complexity of the system let's assume instead of two days we have three days that simply means we have to divide this array into three parts that means there will be two point of breakages and where those two points would lie this is what we need to identify identifying the maximum element in those contiguous sub arrays is really simple and straightforward the main complexity arises while identifying the point of breakages so let's assume we have broken the array from the previous example over here so this is the first point of breakage that we identified the second point of breakage we are we going to do that so if I reiterate on this particular array then uh if I ask you where will you do the breakage you will do the breakage over here I'm not iterating over all possibilities of answer I'm just telling you the final result in this case if you want to explore more you can create those by themselves so from the previous example we created the first breakage point over here and we extended it further and the second point of breakage would come over here the maximum element that exist on in this sub array happens to be six that means these are the tasks that you're going to perform on day one and the maximum time that is going to take is this 6 one similarly on day two you will do this second task that will take two units of time and day three will correspond to this one in total what is the overall time taken to complete this task or the overall difficulty level 6 + 2 + 1 which is difficulty level 6 + 2 + 1 which is difficulty level 6 + 2 + 1 which is 9 so what is a takeaway from this entire analysis what are the variable parameters that you could identify that should be part of your DPR there are two variable parameters that comes into consideration the first one is number of days that you're currently considering in the entire system and the second one is the point of breakage where you are dividing the array so a DP array will have two indexes the first one would be number of days for which you're Computing the overall result and the second one would be index now let's look at the coding section and conclude the question I'll be using memorization technique along with recursion top down approach of dynamic gramming to solve this question and let's see it so in the first go what I have I done I have created the DP AR and the DP AR will have two parameters in it the first one is the number of days that we have obviously we increase the size by one so as to consider uh the total days as D into consideration and the second parameter that we have represents the index where that will be equal to job difficulty the number of elements that we have in the job difficulty AR I have written a specific Corner case at line number three I'll talk about it later in the while going through the algorithm but let's walk through the code part first I trade over the entire DPR fill in it with minus one value and moving ahead I have written a recursive helper method which basically accepts four parameters the job difficulty array the DP AR the number of days that are currently being considered and the last one is the index from which we are starting the operation also there's one important point that I forgot to miss in the presentation for the base case that we discussed over here when the D value is one the algorithm is really simple you iterate over the entire array and you find out the maximum element so this forms are base case for recursion and this is what I have written over here when D equals to 1 what do I identify the maximum element that exist in my array and I set it as the result returned by this recf call moving ahead if my DP at D for D days in and for this particular index is already computed in the past I simply return that value of basic technique of memorization otherwise I go ahead and identify a create a variable left Max initialize it to zero I create a variable result that will actually s the result and I have iterated over the input array of job difficulty array and the point of breakage that I have considered happens to be the variable I and I go up till job difficulty. length minus D + job difficulty. length minus D + job difficulty. length minus D + 1 moving ahead you identify the left Max from the array towards the left of the breakage point which is equal to math. Max left Max Comm job difficulty at the is index you identify the right Max by making a recursive call on the DFS helper method you pass in job difficulty you pass in DPR and you reduce the number of days by one because you have done one point of breakage already also you increment the starting index because I is index is where you broke the entire array so remember this is really important once you have identified these two values left Max and right Max you sum those up and compare it with your result value and finally you select the minimum one out of these two once you're out of this for Loop you set it at the DP of D comma index and let's try and submit this up accepted also I talked about another case that I wrote at line number three uh this is a corner case wherein uh you are given the job difficulty array of size three and the number of days value is greater than the size of your array in those cases you have to return minus one so this is one corner case that was specified in the question itself in example number two this is what I have written over here with this let's wrap up today's session I hope you enjoyed it if you did then please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded I'll see you tomorrow with another fresh question but till then goodbye take care
Minimum Difficulty of a Job Schedule
maximum-candies-allocated-to-k-children
You want to schedule a list of jobs in `d` days. Jobs are dependent (i.e To work on the `ith` job, you have to finish all the jobs `j` where `0 <= j < i`). You have to finish **at least** one task every day. The difficulty of a job schedule is the sum of difficulties of each day of the `d` days. The difficulty of a day is the maximum difficulty of a job done on that day. You are given an integer array `jobDifficulty` and an integer `d`. The difficulty of the `ith` job is `jobDifficulty[i]`. Return _the minimum difficulty of a job schedule_. If you cannot find a schedule for the jobs return `-1`. **Example 1:** **Input:** jobDifficulty = \[6,5,4,3,2,1\], d = 2 **Output:** 7 **Explanation:** First day you can finish the first 5 jobs, total difficulty = 6. Second day you can finish the last job, total difficulty = 1. The difficulty of the schedule = 6 + 1 = 7 **Example 2:** **Input:** jobDifficulty = \[9,9,9\], d = 4 **Output:** -1 **Explanation:** If you finish a job per day you will still have a free day. you cannot find a schedule for the given jobs. **Example 3:** **Input:** jobDifficulty = \[1,1,1\], d = 3 **Output:** 3 **Explanation:** The schedule is one job per day. total difficulty will be 3. **Constraints:** * `1 <= jobDifficulty.length <= 300` * `0 <= jobDifficulty[i] <= 1000` * `1 <= d <= 10`
For a fixed number of candies c, how can you check if each child can get c candies? Use binary search to find the maximum c as the answer.
Array,Binary Search
Medium
907,1886,2000,2027,2188,2294
1,420
hello and welcome to another video in this problem we're going to be doing build array where you can find the maximum exactly K comparison kind of a long one and so you're here you're given three integers N M and K and you want to consider the following algorithm to find the maximum it's going of walk through what this algorithm is essentially doing so it's setting a maximum value at1 and a maximum index attive 1 and has a search cost it's looping through the array and every time you find a value that is bigger strictly bigger than the maximum value you make the maximum value equal to that you make the maximum index equal to that index and then you increment search cost so it's essentially saying like every new biggest number you find let's set our biggest number to that and then every new biggest number we find let's increment our search cost and so we want to build an array that builds that has the following properties array has exactly an integers and every single number in the array is between 1 and M and applying after applying the mention algorithm to array the search C should be equal to K return the number of ways to build array under the conditions as the answer makeer large uh we can compute it module 10 9 + large uh we can compute it module 10 9 + large uh we can compute it module 10 9 + 7 so honestly this problem is a lot um there's a lot to kind of like go over but once you figure out what to do it's actually not super hard um but let's kind of look at these Solutions and trying to get some intuition so here we have our first uh problem so n equals 2 means the array has to be length two m equals 3 which means the elements have to be between 1 and three and k equals 1 meaning the search cost has to be one so for the search cost to be one it essentially means that the first number we encounter has to be the greatest number because if we have something like this then the search cost would be two right because the search the numbers are Stu at negative 1 so we'd get this which would be the biggest number which would give a search cost of one and then here would be search cost of two so essentially search cost is just showing like where does the biggest number have to be and so in this example the biggest number has to be the first number and you can have numbers equal to it so if the biggest number is like one you can have one after it or you can have numbers that are smaller after it so if the biggest number is three you can have like 3 1 32 3 three totally fine right you only increment the search cost when you find any biggest number so these are all of the outputs now let's look at the next one so = 5 which means that array has to be so = 5 which means that array has to be so = 5 which means that array has to be length 5 m = 2 which means we have to length 5 m = 2 which means we have to length 5 m = 2 which means we have to have numbers 1 through 2 and K = 3 so have numbers 1 through 2 and K = 3 so have numbers 1 through 2 and K = 3 so for k equal 3 that means we have to find like three biggest numbers so essentially we need to find like one biggest number and then a bigger number but because uh m is two the numbers can only be one and two so we can only get two biggest numbers so basically I guess you can check for this if you want to like preemptively to make this a little bit faster um if K is greater than M then you don't have a solution so you can just return because k equals 3 means we have to find three numbers and M is two so we only have two okay so now let's uh actually um let's actually look at the last example so N = 9 m = 1 K = 1 so what example so N = 9 m = 1 K = 1 so what example so N = 9 m = 1 K = 1 so what does this mean again so Nal 9 means we have nine numbers m equals 1 means they all have to be one and k equals 1 means uh search cost has to be one so essentially if every number has to be one this is fine because this is going to be the first biggest number we find and everything else will be the same so the search cost for this rail will be one and notice these constraints are relatively small so we can have a solution that's pretty inefficient and that's what we're actually going to do we're going to um code up something reasonable that will pass and then I'll just kind of talk about um what optimizations you want to make if you want to code that up um but I'm not going to show I'm not going to code up like the super most optimized thing cuz I think that just going to take like an extreme amount of time and I just want to make something reasonable that you can come up with and then I'll kind of explain a little bit how you could optimize if you want to uh yeah so we're actually going to code this up notice we don't actually need to return the ray so it's going to be kind of nice so we're just we just need to figure out the combinations we need and so because we can use like a lot of these states we're actually going to code this up using DP right and we're going to try to figure out like it's kind of tricky to figure out the states for DP but we're going to try figure out like what are the minimum States for DP okay so let's start off with uh like what we need for DP right so for DP we need first thing states which is like usually the tricky part of a hard problem right try to figure out states that will actually you know represent everything and still not be too many so we need States we need base case and cursive case so what do we really need to know for the states here right so we kind of want to know so we're just going to calculate how many arrays we need but we don't actually we're not actually going to like store these arrays we're just going to calculate right so for the states um what do we want to have well we probably want to have some kind of like an index of where in the array we are in right and then it's pretty easy to add up possibilities we can either multiply possibilities or add them or something so we need to figure out the first thing is yeah like where when we're building these arrays like what element are we actually on right and then what other things do we need so we probably need to know uh what's the biggest number we've used so far and is that enough right if we have an index and the biggest number youed so far so the biggest number use so far will tell us like how many like if we want to use something bigger what if that increments the search cost so we are going to need to know that but is that it like is that going to represent everything well we all we also need to know um like what is the search cost so far and the reason is that you need to know that instead of just the index and the biggest number use so far is let's say m is 100 K is 100 uh and or I guess 50 something right and N is 50 so the biggest number use so far in the index don't tell you everything alone because let's say we have something like this so let's say we have one six the biggest number you so far would be six but we can also have like a bunch of other conditions right we can have like one 12 six one two 3 six and so on right and so one 12 3 six and stuff and one 12 six like those are fine all we need to know is the biggest number use so far but we also need to know like how many more C like how many search costs have we actually done so like in 1 12 3 six our search cost is four where in six our search cost is two and you can even have arrays of the same length right so you can have one two so just knowing the length isn't enough because you can literally just have like one16 where the search cost here is two and the search cost here is four because we need to figure out like how much search cost do we still need right so these are the states we need the index the biggest number so far and The Surge cost so far and that's going to kind of tell us everything we need to know okay so for the base case there're actually a lot that I came up with maybe some are redundant but I tried to come up with like a lot of cases that you can just early terminate right and so this is not going to be like the most efficient algorithm there are definitely optimizations but at least I made some optimizations for early terminations it's not that bad okay so obviously one base case is like if we've have if we have I numbers right like our if the index we are on equals n so if index equals n right we fill out their whole array what do we want to return well we want to return did we end is our search cost equal to K so that's what we're going to return search cost equals K right because if it's less than k then we that's not a valid state right and uh if it's like greater than K it's not a valid State we need our search cost to be exactly K right that's one of our conditions like if we scroll back up here um we need the search cost to be equal K once we fill that out so that's one now let's look for some early terminations so what are some early terminations we can have well if our search cost is greater than K like if our search cost used is greater than k then obviously this is no good so we just want to return zero for this one so for all these we're going to zero and let's think of some other ones so the other uh the other condition is what if K minus our search minus our current search cost is actually greater than M minus our biggest number so like let's say k here is 100 and search cost is let's say we've used one so far and our biggest number so far is like two but then m is only like 10 well if we need our search cost to be 100 and we only have m equals 10 we can only have eight more numbers here so we're never going to like this is never going to work right so we can kind of like use this equation to figure out like can we even have enough numbers here like even if we increment every even if we keep incrementing by one right we just have like 1 2 3 4 and so on up to M can we even do that enough to equal K and if m is way too small and K is too big then that means this is going to fail so if this is false we can also return or if this is true we can also return uh zero because we just can't have a solution and there's one more that I thought of and let me know maybe some of these are dant these are just the ones that I thought of so the last one I thought of is K minus search cost so far is actually greater than nus I meaning like so we have some cost so far right and then we have some spaces left in our array so let's say k once again is like 50 our search cost is one and our array is only length 10 well we need search cost to be 50 but our array is just too small right so if the array is too small even if we increment by one every time same kind of thing if our a is too small or our m is too small we're never we going to be able to get that search cost so all these can just be early terminations so these three conditions are going to be early terminations and we can just return zero for all of them they might be more and some of these might be done I haven't done like an insane amount of test because there are a lot of variables here so it's not super easy but essentially these are the ones that I thought of for early termination so for all of these we can just return zero and then here we're going to return one if our search cost is K okay what about a recursive case so what values can we try right like let's say this is possible what values can we try well we can actually try any value we want so essentially what we need to do is we can try any Val like we can try to put in any value we want so we need to loop from 1 to M because these can all be valid possibly and then what are going to be like our DP updates so our DP is going to be index plus one right we're going to like go to the next index and then we need to have this biggest number used so far so the biggest number used so far is just going to be a Max of the biggest number used so far and this like Loop number so we'll call that like whatever uh Cur or something right so it's going to be the max the biggest number you so far and Cur and similarly the cost will be the old cost or it will be cost plus one if the current number we're using is going to be uh greater than the biggest number you so far right so let's say our is like six and we add a seven then our cost will go up and if we add anything six or less it will stay the same right so cost will either be cost or Cost Plus One depending on if we had a bigger number or not and that's essentially it and then so if you think about it anytime we add a new number at some index we're just going to add that number let's say we add two and then we're going to add the number of states to build the rest of the array so we're just going to like add all of these up we're going to try to put in every single number and add up all of these for the array and that's pretty much it um and yeah like I said we can definitely have anything because there's like a lot of things that are valid right so if we have one six you can definitely make these smaller and then bigger right so you can even put it in like a one you can make this anything you want as long as like I said these conditions are fine and then you can have like a seven later and so on so like it doesn't really matter what you have you should be able to put in one through at least there is going to be there are going to be states where you are going to be able to put in one through like let's say k let's say our length of the r is like 50 m is 50 and K is like I don't know 10 or something right there's going to be like a lot of possibilities for this to work and so in this case for this third number uh this can be literally anything as long as it's you do need K to be 10 so I think it needs to be like anything below something in the 40s right cuz you still be you do need 10 increases and we have two here so it's going to be like 42 or 43 or something but literally anything from 1 to 43 would work and if K was something even smaller like let's say k is only like three then like this could literally be any number and so that's what we're going to kind of to do we're going to uh try every number and then we're just going to have a bunch of early terminations when something doesn't go right and so this is going to be kind of how you do this and then as far as the optimizations you make I'll just talk about briefly um since we are doing DP of index plus one if you actually code this bottom up because you're only doing index plus one you can have like a space optimized bottom up uh because like you are only going uh when whenever you do memorization or bottom up and you are only looking at like the next element across you can just like space optimize it and Only Store the next element across instead of the entire index so that is like or the it's like one of them there's like a bunch but yeah that is like a general Trend think about when you recurse like how far down you're recursing and if you're only recursing one or two elements instead of storing an entire array you can just store that element and then just go backwards but let's actually code up this memorization and we'll go over the code and stuff complexity so we're going to have a visited array and we are going to have a mod because this number can get really big so we're going to mod 10 and 9 + 7 store so we're going to mod 10 and 9 + 7 store so we're going to mod 10 and 9 + 7 store that as a constant variable then we're going to have our DP So Def DP we have an index our biggest value SE so far in our current cost and then we're going to have the base case of if I equals n that means we are going to check these are cost equal K right so for cost equals K we're going to return one otherwise we're going to return zero okay now we're going to have all our conditions for early termination so if cost is greater than K we can't have it or k - cost is greater than have it or k - cost is greater than have it or k - cost is greater than minus biggest can't have that or k Minus cost so remember this is the one that m is too small and even if we tried to increase M would be too small and this is the one that even if m is big enough we don't have enough space in the array so all of these we can return zero now we're going to check uh obviously our cach so if and you can actually I don't know if it's faster it might be you can actually use a cache decorator I haven't really done that a lot but you can just have like add cache in Python and then that will handle like your visited and stuff so if you want to do that you can do that as well that's already like implemented in um but I'm just going to use the visited instead so if I biggest cost visited return dived my biggest cost okay so we're going to have our result equal to zero and then we are going to Loop so for Value in range we can have anything from 1 to M so this is um is exclusive so we're going to try it so we're going to say let's add our old result right so we're going to add our old result um plus DP of so res equals our old result plus DP of the next index and then remember our biggest is going to be Max of biggest and the new value whatever is bigger and our cost will be so cost if value is less than or equal to biggest else cost plus one right so if the new value is bigger than biggest then we add one to the cost okay and then we are also going to mod it here so we're going to take this and we are going to mod it um yeah mod okay so we're just going to keep it as small as possible um and then we will store it and the result finally say visited biggest cost res return and then we should be able to just return thep of 0000 without having to mod it because we are modding here already so we're storing the values as small as possible um and yeah and I think that should oh yeah so our Z zero is because I should start at zero the biggest value should be you can make it like negative one because these values are but zero would also work cuz these values are from 1 to M so anything is bigger than zero as well and then our starting cost is zero so we can try to run that if you have any errors we don't but I think this probably isn't too bad like it's definitely not one of the insane hard problems and like I said uh this is okay but there are definitely optimizations where there's like a prefix some version as well but this is good enough um for like a hard problem weing to go with it um but yeah so let's talk about the time and space complexity for this one and also I think this is like the most intuitive one to code up as well so a lot of the like card problems are like super optimized stuff is like kind of hard to come up with so I would just more focus on just try to actually have a solution that's pretty reasonable which this one is so uh let's think of the time and space and all that stuff so essentially what are we doing right so we do have all these early breaks but they won't necessarily happen so we are looping right so usually for DP you want to think about like what are your States and then is this constant time or not so for our states we are looping uh for n and then We're looping M cost right so this biggest can be uh 1 to M the cost can be 1 to K and then the I can be 1110 so n * m * K now this is can be 1110 so n * m * K now this is can be 1110 so n * m * K now this is constant but here we have a for Loop that we are looping from 1 to M so we are taking all of this and we're multiplying by m again so this is M2 that's going to be uh n * m^ 2 so that's going to be uh n * m^ 2 so that's going to be uh n * m^ 2 so instead of cost this going to be K right because cost can't be bigger than K if it's bigger than K we will just return straight away so we're not like continuing there so it's going to be n * continuing there so it's going to be n * continuing there so it's going to be n * m s * k for the time m s * k for the time m s * k for the time and the space we can just think about like our cache and uh what's the farthest we can recurse so obviously the farthest we can recurse is only n so that's not a concern right like for every we're going to be recursing n levels deep for every new index that's nothing compared to the cache size so our cach size is n * m * K our cach size is n * m * K our cach size is n * m * K right because I can go one to n um biggest can go 1 to M and then cost can go 1 to K and like I said you can optimize the space to uh to instead of using this DP i+1 you can do and in using this DP i+1 you can do and in using this DP i+1 you can do and in place uh if you did bottom up you can actually optimize the space to be I think it's like m * K and so that's think it's like m * K and so that's think it's like m * K and so that's totally doable and then there is another solution with like prefix ons that's uh harder to come up with maybe I'll do a video on that but I think this one's like the more obvious one and for a reasonably tough hard problem I think this one's like clear to understand clear to get to so I kind of like those kind of solutions one um yeah so that's going to be it for this problem actually and if you liked it please like the video and subscribe to your channel and I will see you in the next one thanks for watching
Build Array Where You Can Find The Maximum Exactly K Comparisons
find-the-start-and-end-number-of-continuous-ranges
You are given three integers `n`, `m` and `k`. Consider the following algorithm to find the maximum element of an array of positive integers: You should build the array arr which has the following properties: * `arr` has exactly `n` integers. * `1 <= arr[i] <= m` where `(0 <= i < n)`. * After applying the mentioned algorithm to `arr`, the value `search_cost` is equal to `k`. Return _the number of ways_ to build the array `arr` under the mentioned conditions. As the answer may grow large, the answer **must be** computed modulo `109 + 7`. **Example 1:** **Input:** n = 2, m = 3, k = 1 **Output:** 6 **Explanation:** The possible arrays are \[1, 1\], \[2, 1\], \[2, 2\], \[3, 1\], \[3, 2\] \[3, 3\] **Example 2:** **Input:** n = 5, m = 2, k = 3 **Output:** 0 **Explanation:** There are no possible arrays that satisify the mentioned conditions. **Example 3:** **Input:** n = 9, m = 1, k = 1 **Output:** 1 **Explanation:** The only possible array is \[1, 1, 1, 1, 1, 1, 1, 1, 1\] **Constraints:** * `1 <= n <= 50` * `1 <= m <= 100` * `0 <= k <= n`
null
Database
Medium
1357,1759
565
hey what's up guys this is juan here again so uh let's quickly take a look at today's daily challenge problem number 565 array nesting right so you're given like integer arrays right nums where the numbers is a permutation of numbers in the range of zero to n minus one so it's a permutation so which means that no average number is unique and it's guaranteed to be in a range from zero to n minus one right and then uh your task to find a set right a sequence of number where the uh i mean each element basically as you guys can see so the first one uh the first element will be us we will be starting from a single number right but this number is not uh fixed you could we can start with at any number right and starting from here onwards so we basically will be use the value of this number as an index to find the next number right that's why we have an asset here like nums k num snaps okay and then num nums k right until we have seen a bit we have seen the number we have visited before right and then we need to return the longest length of a set right um yeah so for example we have this uh this one here basically you know uh we can start from the first one right so we have five four zero three one six two right we start from five okay we start from five and then the next one will be a number in the index five which will be which would be what which will be six uh which will be uh zero one two three four five uh yeah it will be first one will be this one right and then the next one is what it's numbs five which is six right so from five we have six right and then from six we have two right so from five we jump to two and then from two we jump back to zero right so from zero but back to five right that's when we stop and yeah as you guys can see we have what this is going to be a one two three four right we have four unique numbers in this one right instead if we start from four right so let's say if we start from this one right so it will be like four uh fourth one right four to one and one to four basically yeah four to one and one two four right which is two in this case and for this one if we jump from three here it would be what uh three it'll be a uh to it pointing to itself right so basically this is going to be only one so now that's why we have four answer four in this case right and here's the constraints right 10 to the power of five i mean so a brutal force but the first way to solve this problem is it's obvious it's easily just try to pick any number as a starting point right and then we'll basically try to loop through right we'll try to loop through the until we have seen the visited set right and then we stop and then we get the maximum amount all of them right but that one it's going to be a n squared time complexity right because we need to try each of the number and for each numbers we'll take o of n time to find the length right of that set and that will tle and how can we improve that right i think the uh one of the observations we need to make here is that you know since the number is in the range okay and it's a permutation from zero to n minus one it means that you know no mat regardless of where which number we start with it will always end up it'll always end up in a circle like for example you know so in this case we start from five right and then we go to five six two uh let me remove this uh this one here in this case we start from five right and then we go six two zero and then five this is a circle right so if we start from zero right from zero we will go to five and then go to six two and back to zero so also circle same thing for six and two right so this will tell us you know what basically as long as we have seen this circle once right then we don't need to let's say we have we try five here right i know we got we go to six to zero and next time if we are trying to start from zero again here we don't need to do it again because we know okay zero is a part of the previously visited circle and start starting from zero we're starting from five we're starting with from any of the node inside the circle we'll always end up with this with the same length right so that's how we improve our performance right by marking the nodes we have visited before in this circle to be visited so that we will not visit it again right so that's base that's the basic idea to solve this problem and let's start coding then uh we have n it's going to be a length of uh nums right and i'm going to have like seen uh right here right everything it's the and then we the answer will be zero right so we start we basically start from any of them we try to loop through each of the numbers but in this case you know we have length right that's going to be that zero i'll just use l here so uh we try to we try this number we check if this one has been seen before so we can do something like this so while not seeing number right and then we do what we mark the scene the mark we mark this number to true right and then we increase that length by one right and then next time we'll just uh keep doing right it's going to be a num equals to nums.num going to be a num equals to nums.num going to be a num equals to nums.num right basically next time we'll be using the value of this number as an index for the next number right and then here we have the answer is going to be the answer the max of the answer dot count right and then in the end we return the answer so that's it right i mean yep because now as you guys can see since we have this scene uh array here each element or each number will only be visited once right so which means time complexity for this one is going to be all of n right because the next time when we see that when we try to visit the uh the number we have visited before in the previous circle then we'll simply uh stop from break from stop from here right and this answer this length will be zero right and it will not be count it will be not be recalculated again and yeah i think that's it for this one yeah pretty straightforward right uh we just need to up observe right observe there every basically every visit or every process will end up with a loop okay and anything any number in that loop will end up with the same length right so that's the only thing we need to know here and there you go okay cool and thank you for watching this video guys and stay tuned see you guys soon bye
Array Nesting
array-nesting
You are given an integer array `nums` of length `n` where `nums` is a permutation of the numbers in the range `[0, n - 1]`. You should build a set `s[k] = {nums[k], nums[nums[k]], nums[nums[nums[k]]], ... }` subjected to the following rule: * The first element in `s[k]` starts with the selection of the element `nums[k]` of `index = k`. * The next element in `s[k]` should be `nums[nums[k]]`, and then `nums[nums[nums[k]]]`, and so on. * We stop adding right before a duplicate element occurs in `s[k]`. Return _the longest length of a set_ `s[k]`. **Example 1:** **Input:** nums = \[5,4,0,3,1,6,2\] **Output:** 4 **Explanation:** nums\[0\] = 5, nums\[1\] = 4, nums\[2\] = 0, nums\[3\] = 3, nums\[4\] = 1, nums\[5\] = 6, nums\[6\] = 2. One of the longest sets s\[k\]: s\[0\] = {nums\[0\], nums\[5\], nums\[6\], nums\[2\]} = {5, 6, 2, 0} **Example 2:** **Input:** nums = \[0,1,2\] **Output:** 1 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] < nums.length` * All the values of `nums` are **unique**.
null
Array,Depth-First Search
Medium
339,341,364
376
hey everybody this is larry this is day 18 of march uh the code farm hit the like button subscribe one join me on discord let me know what you think about this prom uh i struggled a lot with this farm you could look at it by the length of this video um so and on video square i think it goes for too long i actually record um like a short explanation in the beginning so that um so that you don't have to skip ahead too much um though you can watch me sub it live and actually i took a really greedy path that was wrong uh and you can kind of see how i got there i don't know why there's this like bar on the bottom that's what i that's why i refreshed but um hmm awkward but yeah um but yeah so this is regular subsequence it's a form that i struggle with though it's not that hard of a farm according to legal difficulty but sometimes you just have bad days also i need sleep it's four am that's why i've been posting these videos late lately because i've been sleeping at a normal-ish time uh but today i normal-ish time uh but today i normal-ish time uh but today i did not um but yeah but for this problem the key thing to note is and i'll go over the code in a second um but for now we can focus on just you know this thing um the key thing to note is that um well the two kind of the couple of obviously observations the two big one i would say is that you know um there are only two types of lego uh subsequences basically one that goes up down dot or down up dot right so here you know once we have a strategy um we can just prove first which item one and then let's say you know for the symmetry reasons because the other one just is the same pretty much uh at least the proof wise uh we can try the up down one right well what does that look like well you know up down up uh and then down and wait up and then down and then up well the thing is that with these sequences is that you can alway the idea is that you have a um a sequence of increase let's say you're looking for an up and you have a sequence of up like this right well what happens is that you can you actually only run the two numbers from here uh from this longest sequence 5 and 15. um and from then and in a greedy kind of way you always want to take the biggest number on this uh this uphill slope right um because it doesn't ever make sense to take the 10 it doesn't ever make sense to take the 13 it always makes sense to take the 15. given that you know we have this sub list uh not to become like this contiguous sub uh to get this contiguous sequence we always take you always want to take the max and as a result another way to phrase it is that if you're going up adjacent numbers you only want to take the max which is when the direction changes so basically now you're changing this problem to counting the number of directional changes um and with that's um you can that's how you could do it in linear time um so i spent a lot of time because i was trying to do the linear solution on the cut on the explanation uh the end square time i actually go over really quickly um in the video so if you're looking for that i'll just keep on watching and i go with you know the couple of instances like really quickly and then i jumped into the of end times um but yeah so now that we kind of reduce this by you know you can think about this as compressing it and just deleting everything in the middle uh 15 10 5 well we don't need the 10 uh and then we go 16 and 8 and then and this is our answer right um and then again we just put first check you know on a sequence and then just check for the other possible one which is the same idea and then just kind of see which one is longer um and then after that it just becomes implementation uh i actually initially thought it was going to be dynamic programming e um so i actually implemented uh top down uh but you know you can kind of roll that up to for loop especially now that you have this formulation of what i just said about looking at uh adjacent elements and then just keep on going up until you can go up and then go down and then so forth so it becomes uh a vehicle sequence becomes um counting the number of peaks and valleys um which is kind of uh a fun way of doing it but it's true so then you know um and even though this actually does not need memorization so it's not really dynamic programming in that sense um you can actually you know uh use this practice for us as a formulation for how to think about it things recursively and for transition purposes in this case we actually didn't need it but it is a good practice and actually i did not mind that at all um so as we said so this is just you know um let's say we find in the next increasing or refining uh so we have two functions we want to add for this one we want to ask to answer the question find the longest wiggle sequence where the next direction is increasing and then the other one is the opposite where we find the longest vertical subsequence where the next direction is decreasing and then here we just go for the base case you know with indexes that the last element then we return zero if this is the first element we just return one because that's going to be in the list and then you continue to find the increasing um uh the increasing element right starting on the next index and then after that if this is still increasing then we keep on going because uh we want to find the next peak if you want to call it that but you know while it's increasing you want to find the next element that's increasing if this is no longer the craze meaning that if the number of index is now decreasing then we're just now able to return one plus the fi find the next decreasing element uh and there's some symmetry in the fine decreasing uh part and that's basically the idea um for the time complexity analysis also right before i do that notice that this in structure is actually very familiar to the problem that we did two days ago best time to buy and sell stock um so you know so that's why i would urge you to kind of practice thinking about it like this as well so that if you did need memorization then you could do that but in this case note that for every input to index we only have we don't have any branching right we only look at the next element um so this so index is always going to look at index plus one and only one possible outcome right so in that sense because we don't have to make any decision we always return directly um we don't actually have to memorize because it just is essentially it's a for loop in a funky way and as a result this is going to be linear time because the possible index is going to be zero to n each of them does zero uh i mean 001 work and as a result this is going to be over end time in total and it's going to be over and space due to the stack space in total um cool that's pretty much all i have this is tricky for me uh i think it's just because i missed that observation in the beginning uh you could watch me struggle for the next hour if you like uh before i finally got it um but yeah uh let me know what you think about this format because sometimes i do mix it up a little bit and let me know what you think um hey everybody this is larry this is 18th of march hit the like button to subscribe and join me on discord i'm really sleepy that's why i've been not doing this earlier but uh but today i don't know dubious mistakes maybe okay today's form is wiggle subsequence uh hit the like button in the subscribe button join me on discord i usually stop these lives if it's a little slow just fast forward give me comments you know whatever you like okay so what is a wiggy wiggle why did i say wiki wiggle uh wiggle sub sequence uh okay we turn the link the longest break goes up sequence yes actually it's really cool okay so basically you want to see you couldn't start going up down uh can you tell just a no van of course uh i guess n squared is very rv wait see sub sequence um i mean i guess n square is very obvious in just like you could do dp or something like that uh i mean it's not that obvious but it is like an iftp on the index and up or down and then maybe you can do that without it anyway huh maybe that's it maybe that is actually now that's still n square uh i mean some of it you can even uh depend on how you want to save because uh you can take advantage of the fact that each number is less than a thousand and then you know but that's still n square ish uh or at least a thousand square ish um you if you do a dp so how do we get this in linear time uh you know i guess this is the follow-up guess this is the follow-up guess this is the follow-up but yeah but i think it's not that interesting maybe for me anyway uh to get to n square dynamic programming i think that integral dynamic programming state is you can do this in a number of ways one is just the index and whether the last number direction is going up or down um and you could also do that on the range of the numbers which is also up to a thousand um and then also up or down index and something like that um so you can play around there and square is pretty uh okay um the question is hmm can you do this in linear time my guess if i have to guess with linear time is and this is maybe a little bit cheating in the sense that it's kind of like you look at a complex thing you kind of work backwards to kind of see if there's a solution um and assuming that there is because there's the follow-up there is because there's the follow-up there is because there's the follow-up um you know i might think about you know the two only two things that i you know usually come to mind with the subsequent stuff is usually either a queue or a stack and like i said it's a little bit cheating to kind of work that way i think what my usual workflow is to kind of see if i could ask or answer a question in a better way but um but yeah and i suspect that it's possible that it's going to be one of those like either mono stack or mono key or something like that so basically the idea for me is okay given this 10 right yeah given this 10 what is the previous number that is bigger than it right um and then you could ask both questions which is given as 10 was the previous number that's bigger than it um and then that would kind of get you that mono stack uh and then you could kind of um stores the solution on each one i think that's roughly it i know that i'm not explaining it that well i think i'm still just working through the solution um but i would say that with mono stack or mono q in both cases um you know it's about asking the right questions and i think the right question for me is okay given let's say um an array of numbers and this is not a good one to be done very sleepy uh you know let's say you have this array you know we look at a given number and then you ask yourself okay uh there are two questions that you could ask what is the longest length of a wiggle sequence that ends here where the last direction i was going to say operation the direction is up and also direction is down right so we start we ask those two questions and we can you solve that i think with just a mono uh mono cue um from that and then i think that should oh sorry mono stack um i mean i call it mono stack but it actually like i've been saying mono stack because um i've been having a lot of practice lately or maybe not lately just in general um maybe not that lately but it actually is just a stack where it turns out to be monotonic uh i guess that probably that was monotonic but i think what the more important focus is that um you use a stack right and i'm gonna you know because basically let's say you're trying to figure out what is the last number let's say you have a stack right and this is how i ask it usually for mono stack which is that okay you know let's start with let's start from the beginning let's have one right and let's put let's ignore the wrinkle part for a second and just keep on asking ourselves what's the uh what's the last number that is bigger than this number right well if it's one uh but it's just 1 and then you have 17. well 17 is bigger than 1. so what does that mean right that means that all the numbers that are to the right of 17 um there are two scenarios right um to divide 17 let's say we have a number that's smaller than 17 let's say it's 12. well if this is 12 then 17 is going to be the small uh the biggest number or sorry then the next number that's bigger than 12 so then you know so then this then one will not be the answer um and then the other way is bigger than 17 so let's say it's 20. well if this is 20 one will also never be the answer right so in that case we can pop up the stack and that's kind of the invariant of the problem that's the kind of how i think about these problems and then yeah as you kind of go build you go five is uh good uh and then you have 10 pops to five uh and then you have 13 which pops to 10 and so forth uh and then as you kind of look at it that way um as we kind of keep on popping smaller numbers you'll notice that it is a monotonically decreasing stack because of the thing that you're doing so it's a it's um it's a result of the operation you're doing and not necessarily that you're going you know you're looking at a problem and be like oh let's have a mono stack right um the way to think about it is okay there's this probably that we want that's invariant right and where in here is that um is that the top of the stack is um the next number that can be a candidate and maybe the part of that is also uh that you know the entire stack only contains possible candidates right because at any time you know uh and then where did oh this five is this five at any time these are all the possible candidates right all the other numbers um that are in between like 13 it cannot be a possible answer for numbers to the right of the five and that's basically what then varian is and that's what we try to do with these stacks um but yeah and so all that being said you know let's create the answers um let's just say okay let's see right so that said this is a little bit tricky putting it together um but these are the ideas and these are the building blocks that as long as you understand that you can work out the rest maybe slowly maybe quickly depending on how much you practice but these are the key points for this problem and i know that took me a while to get there but this is not that easy i would say for me anyway so yeah so now i have two stacks let's just say big stack and smaller stack maybe quite bigger stack just to be consistent so bigger stack that's what we notice contains um contains numbers to the left that might be bigger than this number and then this is the same contains numbers to the left that might be smaller than uh this number maybe next number is a better way to phrase it but yeah so then now we just go through the um and maybe we just have answers uh well answers up and answers down why does it go that way so yeah and this is you know uh the best answer uh where the last operation is up or last direction i keep on saying that and there okay so now we have these things together um we can go okay now we could go for the list one at a time uh so for x and nums i just like right you're writing x because it's consistent for me it's a one level thing and you can buy you know use a better number right um let's go for it uh so what and this is very tiring because it's just go uh it's just going for the scenarios which is okay let's just say um you know just making sure that okay what is the best answer where this number is the last i mean i think this is just uh yeah this question here right so okay maybe i'll just copy and paste because i'm yeah right so yeah so if the last number is up you want to look uh um if the last number is going up you want to go down so that means that the previous number that you look at will be bigger right uh next direction is down or this direction uh yeah next direction the next direction we're going to do is down which is this direction that we're going to do which means we're looking for a bigger number so then so here we use the bigger stack right so biggest if length of bigger stack is equal to zero then uh what do we do um well then we um we append this to the bigger stack or we append x to the bigger stack because now this is the biggest no i guess the way that i usually do it is while this is greater than zero and um because stack of negative one is uh smaller than or equal to excel does that to be strictly smaller than i guess so eventually i'll do it what no okay i think it has to be non-zero so no okay i think it has to be non-zero so no okay i think it has to be non-zero so yeah for equals then we remove so actually we have dot pop and then at the very end we do um we put it in but before we do that i guess we want to check um and so down is equal to um well we have to check for us if the length of the biggest stack is zero then we append one that's basically a base case uh the one is just the number that we have now otherwise enter down a pen um how do we store the biggest stack um maybe we have to store one more thing on the bigger stack but basically bigger stack uh the top number uh that plus one say and now um yeah candidate's number and maybe the index yeah let's do the index uh basically we just have to keep i mean we're storing the number which is fine but we actually have to store one more thing so that we know what to look up um and basically here let's just say let's set this to zero and then here um this is the index so we want um the answer up there right because basically this is the index of the top of the stack and then we look up you know the previous um answer where it is entering up is there uh and then here we do we put in the index which uh we have to do by adding making it uh enumerate i'm really tired usually i'm gonna know faster but yeah but this is that's basically the idea uh and then we can do the same thing for the small for the other side um so yeah basically we're looking for a smaller number because you know like we can ask ourselves the same question just to be sure um what is the longest thing with the last numbers up that means that the next direction is up if we're going up we want to look for a smaller number right so that's basically the idea here hmm i this may be wrong actually because i think um i mean this is conceptually right but it doesn't give us like i don't i'm not actually i'm unsure that this gives us the right answer it gives us huh well at least i have to think about how to prove this because um what happens is that we have a stack of these things but we actually want to um we have to prove a property that i have to figure it out in a little bit um because basically the thing that i'm thinking here is that okay right um you know let's look at this bigger stack for a second um bigger stack could contain something like um and i'm instead of doing the index i'm going to do the best score right like you know um you know it could be something like whatever we know that it's going to be a decreasing sequence or is going to look like that but it's not clear to me that given this sequence um that the score the results for this um you know the longest length it's going to be strictly increasing right or strictly decreasing rather because you can imagine that this is you know maybe this actually has a longer length if we and we want to connect to the 12 instead of the nine right but it may be that's not the case but we would have to prove and convince me of that so let's play around that or keep that in mind um and then that's kind of let's finish typing this and then kind of play around with some ideas uh some cases for this um yeah and then now we just return the max of you know answer down and sew up um let's see if it works first uh okay so it works on that one wish they have a press a button to do all the test code one but i guess that's fine i think there is uh there is an assumption that i made that i'm not proving and i'm a little bit skeptical about it so we'll see if these kind of tells us such that out first um also we definitely print out the wrong thing i don't hmm i don't know i didn't notice it the first time obviously but yeah this is clearly wrong right um hmm i mean we kind of saw it here it seems like the linear solution will probably have one more thing uh and this is going up this is going down hmm there's one this is one that's good wait i go down push up first okay down right uh and then here why is that did i mess something up no so the up score in so this the up score here should be a 2 but it is not so the smallest stack should be zero opposite of one that looks that sounds good oh i forgot to push the smaller stack so okay so that is uh an obvious mistake i think i was just too focused on the possible bug that we were talking about that i didn't get it okay so that looks good um hmm i'm going to print the but as i said i don't i'm not convinced that um you know what i said is correct or that this code is correct um but how do i prove this that um that the best value is strictly decreasing right i guess it makes sense actually because in a greedy kind of way the number you always want to connect a number to the number that is immediately um because you always eliminate pos uh because there's no choice because you always pick the number that's closest to you which by default will give you the max answer and as part of the stack and you can and if you pop additional one it can only well did okay i guess i could prove it by scenario analysis so i don't think i'm going to necessarily do that but the idea is that um you could prove you just go for the scenarios which is kind of what i've been doing in my head where um you know if you have maybe something similar to this where if you have a 10 um or you know you have a sequence that's like let's just try it 15 10 uh 15 10 five um you know we have enough and let's just say here you know you have some answer um you know this is the length of the longest thing and i think you can kind of maybe prove that this is not possible because by definition if by definition every number that's here will have um will be we'll be using uh the top of the stack as a prefix i think um yeah i think that's the case which makes it why that this is strictly increasing we can actually play around with this um i think like to be honest if i was in the contest i probably would submit it because uh a five-minute penalty is probably uh a five-minute penalty is probably uh a five-minute penalty is probably worth doing it but i want to just print out real quick print let's see x and down of uh um oh this is terrible uh let's call it i don't know item for item and answer or not enter stack make this a tuple and then we can make this a list i think i did the length the other way but this looks like what we said is true which is that this should be uh strictly decreasing oh sorry this is the answers will be strictly increasing uh for the length because um you know you always take like for example in this case um you would always take if you would always stick to 5 you would take the 5. if you cannot then you take the 10 for the same length but you would never want to take the 10 over the 5 and because this is um because the length is um monotonically increasing um that should be an invariant in the problem as well okay i think i'm convinced let's give it a submit uh watch i'd be wrong about it after all that i think i couldn't submit okay there we go oh no wrong answer by a lot actually maybe i was wrong about the invariant um let's give a look now that invariant holds so i just have oh no um this is wrong so maybe not so that invariant doesn't hold which is what i was worried about um so we have to make some modification to this um to get the proper answer so this is going down what does that mean right if this is a smaller number well i think i'm just trying to think whether uh or when does it make sense to push this maybe it doesn't make sense to push this and that's why we're getting the wrong answer um because for every number that is i think yeah maybe i have to ask myself i wasn't sure um but i think as part of the stack we have to ask ourselves right um okay for example uh we have a new number coming through um you know let's actually copy and paste this real quick this is kind of a tricky problem but let's copy and paste it here uh you know that's about this right um and we ask ourselves the question right that's about uh i don't know a smaller number let's say one well the next number is one going in right uh what does that mean well if this is a one um we never we don't want to put this in if this is a one we never want to use this number anyway because we can get better results here um if this is uh if this is small if this is bigger than one so if this is a three say uh we also don't want to use this number because well it's not relevant to this number so i think now we just have to um maybe from that invariant that we try to figure out uh we have to actually check that the number that we're inserting has a bigger uh strict value so then here we're keeping that invariant that when we insert a number or we insert a sequence we make sure that's um that the number the we give a longer sequence as well so let's try that um it's only a hypothesis but yeah so the index we put keep track of the index which is why we have to do this mapping here um so instead how do we check okay so i guess this is the la the score i guess score is the last ends down um so if so we know that from here that we popped everything that's already uh smaller than it so now we just have to kind of keep doing this as well or we just have to check that if this is um greater than or i guess equal to just in case i think if you go to it's okay um if this is good too uh then we get to push this otherwise then we just kind of ignore pushing it on the stack um okay i think i could buy that um or if length of the bigger stack is zero i guess uh and then we have to do something similar on this side but that before that let's see if it gives us a better answer it should still give us the wrong answer unless we're really lucky but should give us a uh an answer that's bigger than dirty in either case i guess not well i mean this is also a possibility that it just doesn't change the answer because um it happens on the other stack so okay so let's also put this here then just for symmetry sake and also that it would be more correct yeah hmm 57 so this is definitely the improvement that we're looking for but it's still clearly not the right answer hmm that's not great did i is that makes up the stacks no it seems okay let's also print out the smaller stack hmm this isn't no it's not entirely done with this i was wondering if it was just one of those things um hmm mistakes were made i should have gone to sleep a little bit earlier and do this refresh mine um and this looks like it makes sense to me if it's a bigger number then it would tick it wouldn't make sense to take any of the other smaller ones okay why is it 50 was it 67 then oops oh no did i lose to a test case oh no i think it's on the pace sir nope uh oh i guess i could just go back and then copy in this and i should have just done it and square way would have been much faster but so i was wrong about my invariance uh and that is sometimes just the thing with greedy problems is that uh you're wrong with the greedy um because this 15 how does this even work i guess let's print out both maybe what does this stack represent anymore oh yeah these are just numbers so 000. i don't even see the uh there's the 100 but i think that is i have a maybe logic error here i think that's why i was wondering why so the question is i was wondering why 100 is here and i think what happens is that um you know when the 100 came up which is i don't know where oh here say it cleared up all these numbers right which is not great because we want to consider you know we want to consider these other numbers and popping all of these is not good because so one of the invariants that i was wrong about ace for the longest path is that um yeah we're looking for a bigger number but we also want to consider not just the biggest uh the bigger it's a possible bigger number but a number that allow us uh the longest sequence right because let's say you know this 57 i guess comes in later uh we want to be able to use some of these other numbers so i think that's the part that i messed up um and then the question is how do i fix this at least in linear time because now another way to think about it is that the 100 is still uh a candidate for a new sequence but so is you know 76 for example because you can imagine that you know you have a 100 and then like 99 90 you know keep on going 99 100 and so forth uh and you know you would never go back to 76 so that it does become bigger um good i'm too tired for this as you can kind of see my eyes so this is a problem that monostag is not dish sorry fam that i'm struggling a bit you know it does find a way but i think it does destroy some of the lookups which is why it gives us the wrong answer yeah i mean during the contest i would definitely have done the end square way but why is this two oh i guess it's just one direction okay hmm like this 12-3 we give it up on it way like this 12-3 we give it up on it way like this 12-3 we give it up on it way too quickly right because somehow that was right actually but and that's because it's yeah but hmm there's some interaction between the up and the down that i'm i thought would be independent but maybe there's some interaction there sorry fam i have to think about it a bit um hmm the core part it is that um i'm trying to think about how this interacts do we always want the longest sequence that fits if so then what happens is 101 right because let's say you know i think the core problem is let's say you have these two candidates and the next number is a 50. well if the next number is a 50 this was uh i think this was i took it for granted a little bit in my invariant earlier because i think i was solving it for kind of a different problem uh because i didn't get the longest length point but let's say that's your stack if you will um and that's a valid or that should be a valid stack because let's say you're you have a 50 you know 50 the next number is 50 right well in theory the 50 could you know match here for the to continue this length um but it could also match the 100 to continue and we have to make that decision and it could go either way uh it's not super clear that um it would have it one way or the other in terms of decisions and also the answer is you know obviously if you have say 80 is the next number well then you then what do you do right do you still like do you consider oh yeah maybe or even a better example slightly better example next number is 99 right well none no any of these will not be considered and then over 100 is the one that gets considered as the next possible answer um so we can't throw away the 100 item that's what i'm saying hmm i don't know now i'm not so sure that i can do it well not i mean maybe it can be done in any time but i'm not sure i can do a linear time because anytime you have two decision then it becomes a little bit awkward because you know like you can think about another case where you know let's say this is i don't know 20 and then you know you have 120 and then 10 right um well if you have a number that's incoming how do you decide between you know which degree right so then now you have these decisions where even if you have greedy you have to choose between them in a uh a sorted kind of way which is you know at best and again if you do something like that um so i'm missing one observation that makes greedy work i suppose decided that i have to take advantage of the numb since you could less than a thousand um and this linear time thing is kind of bone hmm and so yeah you can see that even i get stuck on uh these problems um okay i think i have another way of doing this with dynamic programming actually not i think about it okay that's this is why greedy is tough because you can um you get the you can get the wrong answer no matter what um okay um i think an observation that um you can make is that let's say you know let's say you have an increasing sequence let's say at this number right so in a way of increasing sequences um you basically only keep two of these right so basically yeah and you can maybe this is a little bit better but yeah one way to think about this is that okay let's say you have an increasing sequence for every chunk of increasing sequences you only keep two right um so i think that's the way that um i would think about the recurrence uh because i think initially my n square naive solution is that okay you know it's for oh and this is actually this is increasing sequence my initial n squared solution is that okay for five let's keep on going to find you know bigger numbers or whatever uh all the way to the end of the list and then that's gonna be n squared but turns out that probably you just have to look at um you know in this case the 15 because this is you know this is all going at least if you're looking for an increasing because um because you know the 10 and the 13 and the 15 it doesn't matter right um because the 10 and the 13 it doesn't matter because uh you're basically compressing them so basically we're just looking at we can save the work by looking at adjacent uh elements so i think that's the big observation that i missed for a long time so let's kind of get back to it so then basically now we have two sequence that we can do right so let's say fine increasing maybe uh index um so if index is equal to n let's say n is equal to length of nums uh this is actually for me going to be similar to um similar to uh buying stock over you know buying and selling stock uh dynamic programming so i basically have to find an increasing which is fine um the longest increasing um subs the longest regos sub sequence where next direction is increasing right so yeah otherwise uh and we can yeah we might have to play around with the numbers here uh so that we have a base case but yeah if index is equal to zero well then let's just return one plus fine increasing of index plus one uh and this is just you know yeah uh okay this is just a base case if index is equal or is greater than zero so else um we want to uh yeah if the numbers of index is greater than or equal to because if it's equal to then we compress it anyway uh if you can index minus one then we return find increasing of index plus one yeah else we return one plus fine decreasing index plus one right and we can also in a similar way uh do the same thing for uh for fine decreasing right and the reason here is that um is that if the two numbers that are uh you know if the next number or if this current number is bigger than or equal to the next number the previous number then you kind of the idea to think about is that now you're compressing them into one and you're not counting the extra one and here if the opposite then you would find one plus to find decreasing that's basically the idea like now you compress them to one number and now you start the beginning of decreasing in this number so that's basically the idea um yeah and you can probably guess that this fine decreasing part it's going to be very symmetric as a result and yeah actually options i was going to say i don't know that there are any subprime so now we just find max of fine increasing of zero and find decreasing of from index zero maybe this is enough we'll see okay i was just usually i would say that um you can take advantage of sub uh um uh sub problems so that um you know you cache the results but i think this is totally deterministic and you don't do any branch outs right um so i don't think there is anything to take advantage of let's give it a quick submit cool uh so you don't even need this i mean i was gonna say it's dynamic programming because i was you know going in i was thinking trying to phrase this in a way such that um such that i can you know do a recursion but now that i think about it um i guess i don't really have to uh cool and this is going to be linear time because yeah like literally all of these are just in go to index plus one and then and you know or you want to think about it in dynamic programming index has you know n possible inputs and each does all one work and we don't even have to cache right it just goes to the next one um so this is over n times i think that'd be funny if i'm wrong no i mean we don't do any branching so it's going to be yeah this is our run time and this is of n space uh due to stack space um and you could actually convert this to a for loop now that i have it this cleanly um and it should be okay um cool um i'm not going to explain this too much more because i'm going to re-record if this because i'm going to re-record if this because i'm going to re-record if this video has gone too long so i'm going to re-record this uh the so i'm going to re-record this uh the so i'm going to re-record this uh the explanation in the beginning so if you're watching this now um the explanation is actually in the beginning because this has for longer videos this is what i do um and if you're watching here uh that's all i have you know thanks for watching thanks for stopping by hit the like button hit the subscribe button join me in discord have a great night uh i'm gonna sleep really well at some point and yeah stay good stay well and to good men to help i'll see you later bye
Wiggle Subsequence
wiggle-subsequence
A **wiggle sequence** is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. * For example, `[1, 7, 4, 9, 2, 5]` is a **wiggle sequence** because the differences `(6, -3, 5, -7, 3)` alternate between positive and negative. * In contrast, `[1, 4, 7, 2, 5]` and `[1, 7, 4, 5, 5]` are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero. A **subsequence** is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Given an integer array `nums`, return _the length of the longest **wiggle subsequence** of_ `nums`. **Example 1:** **Input:** nums = \[1,7,4,9,2,5\] **Output:** 6 **Explanation:** The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). **Example 2:** **Input:** nums = \[1,17,5,10,13,15,10,5,16,8\] **Output:** 7 **Explanation:** There are several subsequences that achieve this length. One is \[1, 17, 10, 13, 10, 16, 8\] with differences (16, -7, 3, -3, 6, -8). **Example 3:** **Input:** nums = \[1,2,3,4,5,6,7,8,9\] **Output:** 2 **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] <= 1000` **Follow up:** Could you solve this in `O(n)` time?
null
Array,Dynamic Programming,Greedy
Medium
2271
287
hi guys welcome to tech grant so today's problem is find the duplicate number it says that given an area of integer of num containing n plus one integer where each integer is in range of one to n itself and we need to find the duplicate integer and it says that there is only one number in this particular array which is duplicate so we need to return that it says that you can use all the problem with the run complexity less than of n square definitely will do that and constant space also will solve it in constant space how can you prove at least one duplicate okay and without modifying the add in nums so we will not modify the array nums so when you approach or when you get question like these i feel the best approach to take is the bucketing logic of array and that is what we are going to do here um if nothing is present then i think they are expecting a minus one so we'll do that what we'll do is we'll create a result array because it says that without modifying the array so okay so the result will be end of this and num start length and what we need to do is and the key part here is that it is the value is in range of 1 to n itself so it does not go beyond that so this length we can make it as plus 1 so that is the thing or actually it will be in length of n plus we are not required so what we can do is we can just traverse the array here and we will um say in integer value in nums and the result that we have created this valve so this is how we implement the bucketing logic so each number that is coming here will put it in the bucket of our results so initially if you see this result that we have that result array will be suppose i have to implement this so this is of length five so initially my result array will look something like this it will have five zero this will be the zeroth position this is first position second third and fourth so this is length five now when i say i will traverse this list so i will go to one first so one is and i say result of val so result of one plus so this will be incremented to 1 next i go to 3 so i will increment 3 to 1 next i go to 4 i will increment it to 1. next i go to 2 i incremented to 1. again i encountered 2 so i incremented it to 2 and now i just need to check that which is the duplicate so duplicate will have count greater than 1 so i will just go through this and i will say for and i equal to zero i less than the results length and i test and if you have something where result of i is greater than equal or it's greater than 1 so you return that number so if some value is written it's greater than that so you return that it's position basically so here you return the second position because second positions value is greater than one so you return i if nothing is found then in the end you can say just return minus one so that should be it expected this oh sorry this is stupid so that's it is marked as medium but i feel it should be like uh an easy kind of problem there are other some of the problems only code which are marked as easy which is much tougher than this one so that's it for the video see you in the next one bye
Find the Duplicate Number
find-the-duplicate-number
Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive. There is only **one repeated number** in `nums`, return _this repeated number_. You must solve the problem **without** modifying the array `nums` and uses only constant extra space. **Example 1:** **Input:** nums = \[1,3,4,2,2\] **Output:** 2 **Example 2:** **Input:** nums = \[3,1,3,4,2\] **Output:** 3 **Constraints:** * `1 <= n <= 105` * `nums.length == n + 1` * `1 <= nums[i] <= n` * All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more** times. **Follow up:** * How can we prove that at least one duplicate number must exist in `nums`? * Can you solve the problem in linear runtime complexity?
null
Array,Two Pointers,Binary Search,Bit Manipulation
Medium
41,136,142,268,645
1,207
Everyone today we are solving question number van 207 unique number ok we have to return true if number of akrens of h value make it unique means every value which is given to us inside akrens ok if I find out its frequency and the frequency of every element like this So what I have to do is to return True and False. Okay, so let's see in this example, how many times is Van coming within this type, three times. Okay, so their frequency is 3 2. How many times is it coming? Tu three kitni bar a raha hai single time single isko 3 ki frequency kitni bar to kitni element se different elements vaan tu three is ok and the frequency of all three is different its 2a 3 kitni hai van ok toh no value repeat kari frequency What to do for that, if it is true then it is returning false, what numbers should be given in it, WAN and if you are ok, then what will be the frequency of WAN, because what will be the frequency of WAN, we have to basically find out the value of both. Frequency should not be repeated basically. Okay, so first we will find out the frequency for each value and if we find out the frequency then how much were the other frequencies. Okay, what is the frequency of 2 and 3. frequency of 2, what is the frequency of 2 and 3. Okay, so basically what will we do, we will make a converter. Okay, what will be stored in this, the value of the key which is inside us, okay, what will be stored here, the frequency, okay, once we get the frequency, what do I have to do to check, how much should all these frequencies be, basically they should be different. Okay, what will you do for this, we will do it for one side, okay, if we make one side, then what we will do first is make the map, okay, so what will we need to make the map, as many elements are present inside each, as many different elements are present in it, for that I will know the frequency, after the form is made, what will I do after that, I will start mapping and whatever the frequency of each element, I will include it in the set. Okay, like how many vanes are there, okay, so that means after three, include it in the set. What happens because what is set basically does unique characters, so as soon as I have a map pointer, what was its frequency, but if it looks at the van, it will input here, then we cannot input because what is there in it is always fine inside the uric acid. So now if you look at why we are getting true, in which case we are getting the true variety, what is the size of the set here, do not take the case of four yet, in this case the size of our map means if the size of the set is equal. If I tell you the size then simply return it, meaning what is the unique number of frequency, I will get it ok but like look at this, if I say four pieces are included inside, ok then the frequency for four is 21, I will shoot you inside like When I try to include it inside the map, then van is included, what does it mean, basically there is a frequency here, how much frequency was there, we are declaring the map, we are finding out the frequency count, then we must have got the map, okay where Till then after that what are you doing and start the map means I am starting to do travis from here okay so the second of IIT is basically doing it for days our frequency is doing it for days okay so by checking the frequency inside means frequency I extracted it here inside the frequency variable and set it by including it. It is okay if the size of the set is equal. What is the frequency of all the numbers from any number? It is okay and if the size is different, thank you.
Unique Number of Occurrences
delete-nodes-and-return-forest
Given an array of integers `arr`, return `true` _if the number of occurrences of each value in the array is **unique** or_ `false` _otherwise_. **Example 1:** **Input:** arr = \[1,2,2,1,1,3\] **Output:** true **Explanation:** The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences. **Example 2:** **Input:** arr = \[1,2\] **Output:** false **Example 3:** **Input:** arr = \[-3,0,1,-3,1,1,1,-3,10,0\] **Output:** true **Constraints:** * `1 <= arr.length <= 1000` * `-1000 <= arr[i] <= 1000`
null
Tree,Depth-First Search,Binary Tree
Medium
2175
875
Hello Friends Today I Will Discuss The Problem Latest Find Such Problems Series We Walking On This Is The Medium Problem And Used Oil Problem Shimla To The Medium Problem Quality And Subscribe Medium Problem Solve Problems On Tuesday To Solve This Problem Name Ko Love And Subscribe The Amazing Ghr Banana Hai Tags English Meaning of Song and Face Ok Sorry If Soon June 5 Dec 09 Second All Super Is To-Do Note You Can Second All Super Is To-Do Note You Can Second All Super Is To-Do Note You Can Decide Her Banana Par Aarti Equal Of Cake Apne Voice Mail Like You Can Meet At A Speed Language on Give Bananas You Can Decide Shyamapal Banana Diet Ke Banana Monday 500 to 1000 Hum Ek Want to See Sholay Comedy Subscribe Now to Banana Solid Straight Roll Banana Subscribe Widening Energy Deficit Ko 2383 98100 That Civil Only at and Complete Faran Payal Irrespective of how many time he marks Saturday and only then will go to expect fennel time it will take two lakhs from this point to words for this 24 August 6 7 4 Hazan Sweets Entertainment The Fire Gun Point He Black Magic In Banana Pass Its Glory But Still Want To Curse All Leading Role Solitaire Minimal Interior All Leading Role Solitaire Minimal Interior All Leading Role Solitaire Minimal Interior Kids Picture Demand Speed ​​At Which Width Banana Demand Speed ​​At Which Width Banana Demand Speed ​​At Which Width Banana Subjects E Can Get All The Banana Twitter Has 400 Units All The Banaras Boys You Members Were Present Content You R Patel's Aap Soye Gaye Edison Voucher Entry Favorite Intellect That This Fight Is Equal To Idli 100 Ki Nilesh Kyun Dene Also And Where Are Pimples Us Jor 560 Tripathi Awadhesh Prem Mez Pe Wrong The Time Table 2013 subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page That Surgical Straight Systems Points of Minimum Speed ​​Aa Crotch Increase The Hidden You Minimum Speed ​​Aa Crotch Increase The Hidden You Minimum Speed ​​Aa Crotch Increase The Hidden You All The Black Lips Can Compute The Leading Role Banana Zindagiyan This Report You Can share the same thing you do subscribe my channel like this is the number of subscribe is 5 and okay sorry for my Italy speed is father inch of left for the giver name loot's posthumous okay and see exam aspect is Umpire let's unite for what is the value of white maximum volume polythene was this suicide note 10.1 volume polythene was this suicide note 10.1 volume polythene was this suicide note 10.1 points 229 in shift meeting dad file also but 828 dial 100 g 285 maximum time candidates will be only and well guard they are also printed in this Should think youth s developed mode a question developed mode a question developed mode a question awards like me for three years and stand by this point verification suav vidmate value and spoke a function with stunning and weather for this particular with values ​​are telling a what is my speed immediately took voice values ​​are telling a what is my speed immediately took voice values ​​are telling a what is my speed immediately took voice mail Meeting Speed ​​for mail Meeting Speed ​​for mail Meeting Speed ​​for Distributing Sweets Weather This After Returning from Truth Video to the Possible Candidates in More Return of the Day Mukhiya Waqt All the Best Next Flight Finding Out So Let's Do I've Created an Option Na How Much Time Will Take You to This Website To Increase The Scene Turn Off But Freel That Soda Water Modified Cars Islamic Radicals In Fatty And 10 Years I'm Still E Always Wait For Every Time A Peeth Ne Total Time Total Wisdom Total Time Pintu 108 All The Banana 500 Total Plus Two X Is The Time To Bigg Boss-1 Solid X Is The Time To Bigg Boss-1 Solid X Is The Time To Bigg Boss-1 Solid Wallpapers And After That Indian Minister Not Withdraw Terror Total Time Is The Cost Of The Money Is Not But Possible Condition I Can Access All The Banane Chintu Time Fix Total So Sainik 12345 This Possible Scenario Of Mid On this acid not mine and a lot of time to become the president and in the next life Video subscribe this Video then subscribe to the Page if you liked The Video then subscribe to the Page
Koko Eating Bananas
longest-mountain-in-array
Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours. Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k` bananas, she eats all of them instead and will not eat any more bananas during this hour. Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return. Return _the minimum integer_ `k` _such that she can eat all the bananas within_ `h` _hours_. **Example 1:** **Input:** piles = \[3,6,7,11\], h = 8 **Output:** 4 **Example 2:** **Input:** piles = \[30,11,23,4,20\], h = 5 **Output:** 30 **Example 3:** **Input:** piles = \[30,11,23,4,20\], h = 6 **Output:** 23 **Constraints:** * `1 <= piles.length <= 104` * `piles.length <= h <= 109` * `1 <= piles[i] <= 109`
null
Array,Two Pointers,Dynamic Programming,Enumeration
Medium
1766,2205
246
hey YouTube Welcome Back uh today we have this problem it's called Uh through parametric number so we're given a string nums which is represent an integral written through if the number is a stop romantic number a subramanic number is a number that looks the same when we rotate it for example we have this 69 and we return it will be also 69. we have 88 130 it will be also 88 but we have 962 when we rotate it will be not 962 of course so um how can we solve this problem so let's just think about how can we first of all let's just think about how we can solve this problem before we do that let's just think about um what are the numbers that can be rotated for let's just think like let's just I'll create an object I already rotated nums so let's just think of all the numbers that remember this is zero a free state zero it will be zero the same also I guess one every one into P1 and maybe we have then two if rated two to not be two also three also four also five and fourth eight six we get nine if we rotate um 8 we will get also eight if we rotate 9 we will get six I guess these are all the numbers that we can rotate these are only the only numbers that we can rotate so the thing that we want to we have two conditions if you can see like there is number that when you read it if you give me the same number like 0 and 1 and 8 and there is other numbers like six and nine when you rotate them they give you different number so in order to solve this problem it will be quite a straightforward solution in my opinion but let's just first think about we have two cases we want to think of these two cases so first of all I want to know if the number it's like if these three numbers if one of the numbers have these three numbers okay we can just continue rotating that there is no problem but what should we do if we find these six and this nine what should we do so for this example let us take this an example this one when we rotate it the six become nine and the nine becomes six whatever return with the same number because when you rotate it will be uh which is the full number this six million to be the first and the line will be six and it'll be with the first so the thing that if we have these two numbers we want to make sure that then the left has the value of the uh of the right so if six have the value or the left has the value of the right of six has a value of nine of the element of value of six so it will have nine and the lift has uh is equals to the value that equal to six that means we can rotate so let's just put this into code to think about it so I'll create a loop okay I'll see that lit oil equals zero I um no electricity because it will be we have left and right because we have this condition so I'll say let lift it will be equal zero and right it will be equals numbs the length minus one number again and um I will say um left is less than or equals right and our list will be lost Plus and right it will be minus and I just put those faces so I will say that okay let's uh const uh left character equals nums Dot character it Nom Noms num the character eight um I will say number corrector at lift and the right one will be equal to C so right now we have the right character and the left character and we said that we have only two cases if the left character has a if the lift character's value equals any values of the what we have right now that means we can just go directly so also say if not list character in rotate numbers okay so we have this lift I'm saying that if this lift character is not in the rooted nums if it's not in it and um Okay so before you know you should know what is the difference between an in and off so physically in is that we are looping through values and off we're moving through keys so um when we Loop right now I'm just saying that like that if we don't have this value in this in the in this object or the this one the lift character the rotate nums of left character doesn't equals right with it and false otherwise we'll turn true so let's just talk about what's going on here and specifically in this I guess because all of you will be confused about why this is happening so I'm seeing it right now if left character in the rooted norms so if these lift characters are in values and specifically we'll talk about these three ones yeah no these three ones if this one that means we can rotate it okay let's see this is not the case so what should we do oh sorry oh I made a mistake what should we do I say okay so if it's not the case that means maybe we have the other keys so if the rotate the lifts e doesn't equals rooted right that means it's not we can't swap at all so yeah that's it let's just uh in this work or not okay it was wrong Ansel why it is wrong answer I guess it did something wrong give him a minute um it will be right minus and left to plus and I have left and I have right and I'm saying if not oh sorry I should put this into um if not left and the characters or rotate or maybe because rotate I guess this has a problem of lift character doesn't equals right mm-hmm why it's this is not working let's just think about what the thing that I have done wrong so let's just think so that I have the routine um because it should be string or something I guess it will not make any difference um oh I guess it will be different maybe just because the number and the value you send it will be let me just see I guess because it doesn't string but this will not okay it works because the okay so it's a quite important lesson about double script that when you push the when you put the values of something that should be string because you can't do a number because if it's a number it will be um so right now let's just go quick through specifically this line because I guess this all the meat and butter lifts actually so bread and butter so basically we have this one we're seeing the if left okay so for example let's just take this one as an example first and let's just say okay so we start a number so right now left will equals uh sorry 88. and uh eight and right will equal also eight okay so we will just say okay if um if it's not left in character rotate so let's just go through here no lift it in character with it's eight and it's both so that means yeah it's in there so okay if it's in there this is not true so we just we don't even ignore the last one and we continue looping so we continue looping we will just be left will be uh the next one until it will be the next eight and uh right it will be uh I just read what right will be um right will be back I guess it's uh okay right and relatively equals to left I guess in this one because yeah and no right would be big enough yeah whatever it's not the case right now so when you go to the second eight also we'll do the if statements and we do and the this one also it will equals true not false so we just ignore it however when you have this one okay because this is the whole thing actually the Second Step so we said that okay if left the in Roti so let's see that we have this is uh six and nine and we have left and right Okay so we'll see that if left uh character in doesn't it's not in rotate so let's just see yeah it's not there okay so if uh if rotated flipped the character doesn't equals right so let's just see here so this is when you lift it will equals right because you have um six so there's a six it will give us nine and right still give and write is equals to nine so it's just it will it's this statement is not full so it's not returning full so we continue looking into we finish the loop and we'll turn through so um that's it this video I hope my social sounds quite good I hope my description is quite good if you like my content make sure to subscribe and hit notification Bell so you'll never miss a video and see you in future problems
Strobogrammatic Number
strobogrammatic-number
Given a string `num` which represents an integer, return `true` _if_ `num` _is a **strobogrammatic number**_. A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down). **Example 1:** **Input:** num = "69 " **Output:** true **Example 2:** **Input:** num = "88 " **Output:** true **Example 3:** **Input:** num = "962 " **Output:** false **Constraints:** * `1 <= num.length <= 50` * `num` consists of only digits. * `num` does not contain any leading zeros except for zero itself.
null
Hash Table,Two Pointers,String
Easy
247,248,1069
867
hey everyone welcome back and let's write some more neat code today so today let's solve the problem transpose Matrix we're given a 2d integer array and we want to return the transpose of that which if you don't remember like your linear algebra and stuff is pretty simple actually they even colorcoded it for us to make it pretty simple here you can see we have a square Matrix and each row ends up becoming a column sort of second row is now the second column third is the third column and the order of values of course does matter that is preserved so the first one stays here a second one becomes a second value in the column third one becomes the third value in the column so I think that's the simplest way to think about this problem when they say here you can think of it as flipping it over its main diagonal what they kind of mean is over this diagonal each value is kind of being swapped like here it's being swapped with itself so no change here these two values are swapped the middle one stays the same these two are swapped as well and then last one this stays the same and if you were to do that you'd notice that it does end up looking like this before I kind of get into how I'm going to solve the problem one thing to notice is that we're not necessarily going to be given a square Matrix every time the second example kind of illustrates that so in the second example which is a bit more interesting we have 1 2 3 4 5 6 so basically we were given a 2x3 Matrix now the result is a 3x2 matrix because again if you think of it in terms of turning this row into a column well of course the column is going to have three values in it 1 2 3 so it's going to be three and of course we only have two rows so we're going to end up having two columns and then we're going to have the four five and six here so just keep that in mind this is also why we cannot solve this problem in place of course we pretty much have to allocate extra memory at least in the general case if we had a square Matrix we might be able to solve it in place but that's not guaranteed so don't even worry about trying to save memory now how am I going to solve the problem kind of how I drew this out the first thing we're going to want to do is allocate space if we have a matrix where we have two rows and three columns we're going to create a matrix with three columns and two rows it's going to be empty initially but that's what we're going to do and then we're going to Traverse the input Matrix pretty much how we usually Traverse Matrix row by row what are we going to do though with every value we have this value at row0 column 0 well we're going to end up putting it in the new Matrix at row 0 column 0 next we're going to have this second value at row 0 column 1 where are we going to put it in the second Matrix we're going to put it at Row 1 column zero pretty much the row and the column are swapped that's literally the main observation you have to make next one is going to be the same this one is at row 0o column 2 so we're going to put it at Row 2 column 0 the same thing with the second row we're here Row one column 0 we're going to put it at row 0 column one exactly the same with the rest of them the only thing is we're swapping the row and the column just like we kind of did when we declared this Matrix in the first place the number of rows and columns are kind of swapped in terms of time complex we know we have to iterate over the input Matrix let's say it has n rows M columns so that is going to be the Big O time complexity in terms of memory that's also going to be the same n by m we do have the same number of cells in the output Matrix but in many cases we don't include the result the memory that it takes to create like the output so depending on how you want to think about it might also be considered to be constant memory let's go ahead and code this up now so the first thing I like to do with these Matrix problems is just get the dimensions so the number of rows and columns is pretty easy to get we get the length of the Matrix and the length of the first row will give us the number of columns then before we even start iterating like with nested Loops over the input Matrix which I'm want to do like this we want to actually declare the result Matrix in Python it's a little bit different than many languages think of it this way so we are declaring the first row and how many values are going to be in the first row it's going to be the number of rows in the input Matrix actually so what we can do in Python is multiply this by the number of rows so if we had five rows in the first Matrix we are now going to have five columns because the row here has five values therefore it has five columns and how many rows are we going to have in the output Matrix basically it's going to be the number of columns in the input Matrix so this is one row how many rows do we want this many rows this is called list comprehension in Python so we're going to do just like this so for the number of columns we had in the input Matrix that's how many rows we're going to have in the output Matrix and we know that we're going to return the output Matrix so I'm just going to fill that in out here one last thing for us to do we are traversing The Matrix now but we're not populating the output Matrix how should we do that we know if we're at the current row column position this is the value in the input Matrix where should we place it in the output Matrix pretty much with the coordinates swapped so in the resulting Matrix instead of saying row column here we're going to actually swap these two we're going to put column first and then the row second that's all you have to do this is the entire code let's run it to make sure that it works and as you can see on the left yes it does and it's pretty efficient the run time is kind of random I could run it a couple more times to get the percentage beats higher but I'm not going to do that if you found this helpful please like And subscribe if you're preparing for coding interviews check out n code. thanks for watching and I'll see you soon
Transpose Matrix
new-21-game
Given a 2D integer array `matrix`, return _the **transpose** of_ `matrix`. The **transpose** of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[1,4,7\],\[2,5,8\],\[3,6,9\]\] **Example 2:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\]\] **Output:** \[\[1,4\],\[2,5\],\[3,6\]\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 1000` * `1 <= m * n <= 105` * `-109 <= matrix[i][j] <= 109`
null
Math,Dynamic Programming,Sliding Window,Probability and Statistics
Medium
null
476
its binary format is one zero one so how do you get the binary format I hope you guys know that so if I given a number four two plus zero is one two by three is eight okay here it should be two power two also so let me just all right this is two power three so two power two is four two power three is eight so if a number is 5 its binary representation will be four plus one will be five So what at position four and one you give up it one and the remain bit will be zero so it's basically zero one there is nothing but one zero one so binary representation of Phi is one zero one you have to return integer such that filter bits of the panel representation of the given number if you flip the bits of 0.01 it will give you of 0.01 it will give you of 0.01 it will give you the one zero two zero one zero so zero one zero is nothing but it represents zero one zero so that means two power one is active so it is on the problem so first what we'll do is and a given constraint they have said the minimum number that can occur is one there is no zero so we'll have a variable called mask okay we'll check this to one until this integer Mass becomes greater than Phi we will do the left shift operation by one so first we have mass mask left Shield by one two or with one will give you okay it will give you one zero so if you do one left shape by one position so one will be lift your back one position so one zero if you do or with one or operation again so one zero or operation zero one two one and one zero will be one so it will give answer as one so what means as I said you have to make the integer mask because every bit in this mask should be one that's right if you do left two by one it will give you 0 as a bit over here in the right significant bit but to make it when you do the order pressure so one month so one represents at 1 2.0 to month so one represents at 1 2.0 to month so one represents at 1 2.0 to four one so it will be three is three less than five yes so again lifted The Mask by one so one left two by one so left shift by one means one zero or with one that will give you one so one will represents four plus two plus one that will be nothing but seven so is seven less than 5 and this one is so you have the mask as one now what will it do with the given integer one that is nothing but representing seven here why am I doing why do we need to do the xor operation here as you know xor means so if you zero one so alternating bits will give you answer as one and the same bits will give answer as you that is what the xor means right so why do we need X out over here operation or with one until it is one we have the flip in the given number one to zero right and zero should become to flip this one to zero if you do xor with one will be same so that will be 5 to 0. fine got it since we have one over here we need to xorbit one since it is same both the bits are same it will become zero so one will reflect to zero and then next coming to zero with one it will be right because all limits in the mask with zero will be xor with one will give you one because zero should be 5 to 1 so that's why we do the Exon operation so Y X or operation whichever bit is one we have to do the foreign so that by an example you will get the fluid so now if you do angles of operation one can solve it one will be 0 1 because different width and one example one will be zero so zero one zero there is nothing but two we have to return this answer so at first we will have a variable plot mask initial is to 1 y because as you know is a minimum number possible so why this mass is less than the given number one position you do all operation with one fine to this at last you have to return because XR operation okay so we will submit this foreign
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
502
Hey hello today I'm looking at the question fire 100 Oh to IPO so the question is really long there is actually a tldr in the question so just to read this first to sum up we want to pick a list of at most k distinctive projects from the given projects trying to maximize the capital gain final capital and that we want to output that maximize the capital so what are the projects for each project i there are two elements which are the pure profit P I so it's not revenue we don't have to deduct any kind of cost it's pure profit that will be added to the capital and the minimum capital CI that's needed to start the corresponding projects that's not actually subtracted in the end it's actually just a threshold once we are big enough we can get the contract and you know the since the P I is the profit so it's a cost that's already deducted from there so yeah that's pretty much the these two things describing our projects initially we have a character that's W when we finish our project at the obtain the profit will be added to the capital so that we can potentially grow larger and to be able to get some new contract and locking that potential additional profit into the capital and the grow larger to get larger contract so that's a pretty much have this questions laid out looking at an example we have k equal to 2 meaning that we can do at most the two projects maybe before something like the you know the IPO timeline and now initial capital is actually zero the profits are one two three four the three different projects and their capital requirements the it's not the cost it's the capital requirement to obtain that profit the associate profit is zero 1 so we don't have any initial capital that's the so the first prod this on the only one that we can do and to obtain it is profit so once we finish that we add one to W so now our total capital is now one looking after the remaining two projects their requirement capital is one so we could do either one of those obviously we will go for the one that's yielding the larger profits so we'd go about to the third projects after we finish that now a total becomes four and we have done two projects so the maximize the capital it's gonna be four so that's this example pretty cool that with no capital we could do something and get profits making money out of singer so anyway so just based on this example you can see that the choice here among the available projects that we can do since that this these are requirements it's just a special to test the doable not it's not actual any kind of cost for all the projects at any given time when we need to make a choice among all the projects that we can do we will definitely do the one that years the highest profit because once we do that the capital in our capital can go grow higher so maybe unlocking some other projects that were potentially we're it's more profits so basically what we want to do is to each time when you finish a project or you get to start of projects we look at all the projects that we can do in our current capital is larger than the required capital we pick the one with the largest profit and add that to the lower total capital once we do this K times we're done so it's going to be a full loop or you know a loop that's run in K times and each time we will look at all the options that balloon our capital structure and pick the one that's with the highest Highness the Prophet so definitely we can use a priority queue to hold the set of projects that we can actually do and it's going to be a maximum for a priority queue so that the top elements is going to be the doable project with the highest profit but once we raise the now own after we finish the project our capital grows we want to grow the set of project so we can do on the priority queue we can do so by pulling the next cheapest you know capital less than most least capital demanding projects that so that was originally undoable just put that into an hour consideration set so for that reason we could have another priority queue to hold the undoable projects sort of using a min prior to queue based on their capital so that once we finish our project we try to look at the not doable project from the prior time and just pull the least expensive one at least their capital demanding one and put that into if we can do it now we move that basically into an hour consideration set once we do that once we you know updated the consideration set which try to pick the next one that's yielding the most profit so two priority queue that's pretty much how to solve this and it's pretty intuitive and straightforward the reason why greedy works is that this is not cost but this is cost that we're going to take the difference if this is cost and revenue the problem will actually become much more interesting so here it's a really simplified yeah and greedy just works because among all the projects that normal capital allows us to do there's no reason to go for the projects that years to when we can do a projects year three because of this one this value here it's not as subtracted about from the W all we do is to find the highest to P and to put that on to W so that's why greedy words so with that out of the way let me let's start cut this all right so the consideration set priority Q is easy because that's just going to be the priority Q of the profits so it's the easier one the other one that has to have a top on the priority Q which is going to be the capital and the end of the profits because when we sort it with sort of based on the capital in the increasing order so it's a min priority Q once we pull it we want to grab the second element which is going to be the profit and put that profit onto the second priority Q so there are going to be two priority Q 1 is just going to be containers it's going to be integers the other one is going to be a pair so let's define a type let's call this and the default priority giving in C++ is maximum so that works giving in C++ is maximum so that works giving in C++ is maximum so that works fine for the profit prior to kill but for the least capital demanding project projects prior to kill we need a mean prior to Q so we need to provide our comparator so it's going to be just public operator and it's going to take two pairs two tuples we want to have this in D we want the first to be larger than the second so this compared to be used by a maximum priority Q will become the main priority you as tricky yeah so that's the comparator so now we basically just gonna initialize this prior to Q first grabbed a number of projects and we're going to initialize this in a vector of apples so this is basically just creating the underlying container for the projects for priority queue and we're going to move this onto until onto there and just do one may keep you file operations it's gonna be a linear time this is creation is also linear queue the elements on there is going to be this pear apple and the underhood container is a vector of the eye and the comparator is this self defined one let's just call this fried project sporadic you and to construct this we do this we're passing actual instance for the comparative because I couldn't passing a class here class is not first class object so and then just move this vector of projects onto here also so what actually called me keep I think to make this thing a heap ordered so that's this project priority queue we're gonna pull the least capital demanding projects from this priority queue and push that push up on to the consideration set so that's this prior to give the other priority queue we use is it's just the pure profits maximum priority queue that's all the projects that we can consider in looking at that the maximum profits let's just call this feasible and yeah so that's initially empty because in the case that we have zero money if there is no projects with zero capital requirement there's nothing gonna be feasible so it's totally empty in the beginning so the looping condition is that while we haven't done K projects yet we got to do this what are we going to do is to try to pull the projects that we can do into an our consideration set so while this is not empty and that the you know cheapest that the least capital demanding projects it's a requirement is less than the current capital that we have but W what are we going to do is to pop this and push this onto feasible no I'm sorry feasible I should copy this I know yeah put profit on to the this priority Hugh and pop it off so after this while loop we can just find the most rewarding projects from feasible and add that profit on to the capital so what why it's did I delete anything I just no idea why that happened yeah so just continue so we want to do is to increment the W by the largest profit we can do now so that's from feasible and then 4th Ave this out because we couldn't do duplicates duplicated projects so that's that I think they were just one thing that we need to handle that so if the piece will become empty that means we haven't finished the K projects yet but we have no projects we can do then the W is the one that we should return there's no way we can increment W anymore so that's why we returned it here otherwise we would try to pop off something from nothing there's no way we're gonna be doing that so that would cost Pavan yeah so that's pretty much the code I think let's just do some quick checking yeah looks okay let's see No miss Barrett this is first anything else why would I have that okay this time it seems so let's try to submit this that's working uh okay so let's look at the Ron time so here the construction of this is a hold off hand because we push an element's onto this vector so that's order of N and here the hiccup I would take out of them I'm not sure if it's moving or copy I'm not as safe as possible expert so but anyway the time required for this to become he bothering should be a linear time to with respect to the number of elements so that's order of and there here it might be a time thing to say that it's a K multiplied by something but actually no because this wire loop that will be terminated early and the most number of time that this wire loop you know multiply a you know in its entirety of this key repetition of this model the total is just going to be popping everything out so it's gonna be n log n so this while loop it's gonna be in logging in total so that's this because in the worst case will pop up for every project from this fire to kill onto the feasible and the fees ball we do the pop it's gonna potentially we push this so it's a it's two multiplied by n log n because we push this and pop this the facebook girl as large as the order the total size that's that and here the Pope here only runs at least at most K times so yeah so the total run time will be sorry so the total wrong time would be 2n plus a plus 2 n log n yeah so chopping the constant this in linear turn is overshadowed by the n log n so yeah it's if K is relatively smaller compared to n this becomes a n log N yeah all right so that's a that's the time complexity analysis the space is obviously linear this one is linear this two is potentially linear maximum and in the worst case so yeah so that's this problem two priori q12 continuously grabbing the least the capital demanding projects so that once we do some projects this can potentially be something we can consider so we grab the least that capital rip demanding one at a time until we until the thing that the least demanding it's something that we couldn't do so we use that for that reason the second is for the current doable projects we want to grab the most profit avoiding awarding projects so that's the use for another priority queue yeah so that's this there is just something that we could do this a little bit simple so that the for the projects we just sort that entirely here we're just trying to avoid the full sorting the other way is just using one project I'm providing you the feasible and just do a full sorting of this projects you know in the restaurant also just creating this I sort this vector you won't even do - we just have a you won't even do - we just have a you won't even do - we just have a iterator and so the next time you will come up with the least demanding because the you know you Traverse with the iterator gonna work - here I'm trying to iterator gonna work - here I'm trying to iterator gonna work - here I'm trying to avoid doing extra work but based on the runtime it's actually slower compared to a sorting I think so but it doesn't really change that the fact is gonna be in log n because if you sort it's in log in there so overall the runtime should be similar it should be this similar yeah I should say the time complexity should be the same territory there's no sir ethically better it's just a based on the data you have so you could potentially behave differently so that's this question today for use of two priority queues
IPO
ipo
Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only finish at most `k` distinct projects before the **IPO**. Help LeetCode design the best way to maximize its total capital after finishing at most `k` distinct projects. You are given `n` projects where the `ith` project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it. Initially, you have `w` capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of **at most** `k` distinct projects from given projects to **maximize your final capital**, and return _the final maximized capital_. The answer is guaranteed to fit in a 32-bit signed integer. **Example 1:** **Input:** k = 2, w = 0, profits = \[1,2,3\], capital = \[0,1,1\] **Output:** 4 **Explanation:** Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. **Example 2:** **Input:** k = 3, w = 0, profits = \[1,2,3\], capital = \[0,1,2\] **Output:** 6 **Constraints:** * `1 <= k <= 105` * `0 <= w <= 109` * `n == profits.length` * `n == capital.length` * `1 <= n <= 105` * `0 <= profits[i] <= 104` * `0 <= capital[i] <= 109`
null
Array,Greedy,Sorting,Heap (Priority Queue)
Hard
null
63
in this video we'll be going over the memorization approach of unique paths too now let's go over the dot process the recursive approach was inefficient due to overlapping recursive calls we can avoid overlapping recursive calls using memorization which means caching so what do we need to cache in each of the recursive call we are trying to find the number of paths at the current cell on the current find the number of paths to reach the bottom right corner at the current cell rc this means we can cache rc with the number of paths now let's go over the pseudo code so we're going to create a 2d matrix memo to cache previously calculated results so the rows represent r the columns represent c and the values represent the number of paths now we're going to fill memo with negative one this is to prevent the case where we are we have found zero ways to foul uh to reach the bottom right corner we have failed to find uh we have failed to find a path on the top left to the bottom right this can most like uh maybe due to obstacles so we're gonna implement the top down memorization approach then we pass in our memo so it's a cache now what's the base case if memo rc is not equal to negative one which not equal to the default value that means we have found we have already found the number of paths for the current cell we do not need to calculate it again so we can return email rc then we need to cache this so we're going to put the sum of the recursive two of recursive calls inside the cache and then we can return the result now uh let's go over the time and space complexity so let's go to 2mn plus mn where m and n are the number of rows and columns so the first mn is to fill the memo of negative one and the second one is there are m times n possible states with r and c now let's go over the space complexity let's go to first is our memo so m mn and then plus of m plus n which is our recursive call stack memory our total uh space complexity is go to o of m times n so this one's for mimo and this one's for recursive call stack memory now let's go over the code we are first going to create our cache so let's move these two are uh move these two out the number of rows and the number of columns now we're going to create our memo then we're going to iterate 0 to fill me move negative 1. i'm going to pass in so first pass in the total number of rows and columns and then the memo itself and we need to update our method so if memo rc is not equal to negative one we have already calculated the result for mimo rs for the rc so we can just return the result the cached result now we're gonna now we want to cache these two results inside memo so we can just place a sum inside here and we can return it let me know if any questions in the comments section below we will be going over the bottom up approach of unit paths 2 in the next video
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
1,361
hey everyone welcome back and let's write some more neat code today so today let's solve the problem validate binary tree nodes we're given n binary tree nodes numbered from 0 to n minus one but that's not necessarily their value but the value is pretty much Irrelevant in this problem cuz it's not like a binary search tree it's just a regular binary tree we're also given two arrays left child and right child so each of these arrays is going to be the same length as the number of nodes in the tree because suppose that these are our arrays in index zero we're saying that the zeroth node has a left child of one and a right child of two in the first position here we're saying that the first node has a left child of neg -1 and a right child left child of neg -1 and a right child left child of neg -1 and a right child also of ne1 now Nega -1 is a replacement also of ne1 now Nega -1 is a replacement also of ne1 now Nega -1 is a replacement for null in this problem because we know the nodes are numbered from 0 to n minus one so if we have a negative 1 here we can basically assume that this node one does not have a left child or a right child the second node has a left child of three and a right child of ne1 and the third node has a left child of negative 1 so no left child and a right child also of1 now what we want to determine is do all of these n nodes form exactly one valid binary tree we have to use all of these nodes and they have to form exactly one Val valid binary tree now what is a valid binary tree well there are two main characteristics here first that it has to be connected a single connected graph just by looking at this one we can see that it indeed is connected and the second thing is that there can be no cycle in the graph so here we see that there is no cycle now it's a little bit tricky because trees are technically undirected and I think the definition of a tree is kind of weird the way it's presented because obviously this Edge is not undirected it is going from the parent to the child but basically if you assume that this is an undirected graph like what if I introduce a an edge going from here to here uh still this does not have any Cycles if we assume the edges are directed but if we assume the edges are undirected then this definitely does have a cycle and this is definitely not a tree so we would want to return false for this example so that's kind of how we are going to determine if this is a valid binary tree or not first it has to be connected and how do you think we're going to determine if it's connected well probably we will start at the root because we're going to run some traversal on this let's say DFS you could probably also o do BFS if you wanted to but we're going to run a traversal now we don't know like starting from a leaf node we're definitely not going to be able to reach all of the nodes in the graph but we know theoretically if it's a valid tree starting from the root we definitely should be able to reach every single node so that's one way for us to determine if this is a connected graph now at the same time why not also determine if there are no Cycles in the graph how would we do that though because it might be a little different with a tree rather than a regular graph right well actually it's not by starting at the route we can keep track of which nodes have already been visited we visited the zero okay now we get to one we visited the one we get to two we visited the two then we get to three we visited this guy as well so in doing this in keeping track of the visited not only can we determine if there's a cycle because if we were to like if there were an edge from here to this guy here then we would end up visiting this one twice we would detect it's already in the visit hash set that's what we usually use for DFS to determine if there's a cycle and if that were the case then we know there is a cycle but in this example there's no cycle but at the same time we can use this visit hash set to determine if the graph is connected because theoretically by the end of the DFS the length of this hash set should be the same size as the number of nodes that were given so that's how we can determine that so basically we're just going to run a DFS starting from the root now how do we determine where the root is in this graph well basically we're going to figure that out by finding the node that does not have any incoming edges so here you can see that this has an incoming Edge but this one does not have a parent so that's where we would consider our root that's where we're going to start the DFS from theoretically what if there were actually multiple nodes that don't have a parent well our DFS would then tell us that graph is not connected so we would end up figuring that out anyway and in terms of time complexity since we're running a DFS and we're going to have to determine where the root is we are going to have a Time complexity of Big O of n because n is the number of nodes we know we'll have at most uh two edges for every single node and the space complexity is also going to be Big O of nend for our visit hash set and couple other sets I'm going to show you in a bit okay now let's code this up okay so the first thing I'm actually going to do and we can get away with this in Python it's pretty easy we're going to take the two arrays and actually add them together remember these represent children and if we add all of these together and I use a hash set to get rid of the duplicates I convert these arrays concatenated together into a hash set then we get rid of the duplicates so these are all of the children these are all of the nodes that have a parent has parent that's what I'm going to call it and theoretically we should be able to tell if the length of has parent is equal to n then every node has a parent and then we can just return false we don't even need to do anything we don't have a root node of course if every node has a parent but there's one little thing you might forget about we have some negative 1es potentially in these two arrays so before we check this let's actually remove ne1 from here so I'm going to do has parent instead of doing remove I'm actually going to do discard because remove will throw an error if this key does not exist but discard won't throw an error this does not have to exist but if it does exist it will be removed from the hash set so that's just step one now we know there is at least one root in the tree and we're going to initialize the root as negative one just as a default value but now we're going to figure out what exactly is the root node and we can't actually iterate over has parent we are going to instead iterate over the range of valid nodes which is from zero to n- one and we know at least from zero to n- one and we know at least from zero to n- one and we know at least one of these does not exist in has parent so if I is not in has parent then we're going to set the root equal to that and we're going to break out of the loop so by the end of this we will have our root node now the only thing left for us to do is run our DFS on I'm going to Define that as a recursive algorithm here before I do that I'm going to declare a hash set up above that's going to be used within this function and we know that with DFS there's typically a base case when we reach null but since we have numbers instead what is null represented by well it's going to be I is equal to1 and if it's equal to1 we return true we're returning true because we know that this is a valid tree so far at least because the other case is going to be where we detect the same node twice what if I is already in our visit hash set in that case we immediately know we don't have a tree so we will return false in this case that's why we're actually returning a Boolean in this case we have to now if this node is not visited then let's go ahead and add it to the visit hashset and then let's do our DFS let's do DFS from the left child how do we get that well that's the easy part that's why we have our left child array the left child of I let's run DFS there let's also run DFS on the right child at this index but remember we are returning a Boolean so how can we use these two functions to return a Boolean what how do we know if this is a valid tree or not well basically the left uh tree the left sub tree has to be valid and the right sub tree has to be valid so actually let's return the end of these two so now our DFS will tell us starting at this node is this a valid tree or not but it doesn't the one thing it doesn't tell us is are all of these nodes connected it could be a valid tree but what if we didn't visit all n of the nodes so for that what we're going to do here is we're going to call DFS because we have to we're going to start at the root but we're not going to just return the result of this we're going to return this and is the length of visit equal to n so this is the solution that will tell us if there's no cycles and all of the nodes are connected so this is the entire code let's run it to make sure that it works and as you can see on the left yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon
Validate Binary Tree Nodes
tiling-a-rectangle-with-the-fewest-squares
You have `n` binary tree nodes numbered from `0` to `n - 1` where node `i` has two children `leftChild[i]` and `rightChild[i]`, return `true` if and only if **all** the given nodes form **exactly one** valid binary tree. If node `i` has no left child then `leftChild[i]` will equal `-1`, similarly for the right child. Note that the nodes have no values and that we only use the node numbers in this problem. **Example 1:** **Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,-1,-1,-1\] **Output:** true **Example 2:** **Input:** n = 4, leftChild = \[1,-1,3,-1\], rightChild = \[2,3,-1,-1\] **Output:** false **Example 3:** **Input:** n = 2, leftChild = \[1,0\], rightChild = \[-1,-1\] **Output:** false **Constraints:** * `n == leftChild.length == rightChild.length` * `1 <= n <= 104` * `-1 <= leftChild[i], rightChild[i] <= n - 1`
Can you use backtracking to solve this problem ?. Suppose you've placed a bunch of squares. Where is the natural spot to place the next square ?. The maximum number of squares to be placed will be ≤ max(n,m).
Dynamic Programming,Backtracking
Hard
null
1,663
uh hey everybody this is larry this is day 28 of the january leeco daily challenge uh hit the like button hit the subscribe button join me on discord let me know what you think about today's problem um and just you know yeah wait is it 28 yeah okay i guess i just had to hit the refresh one but yeah um hope everyone's having a good day a good weekend or a good week um life is tough life is weird life is tricky so i hope everyone appreciate uh what y'all have and i it's not clickable i have to refresh it again this technology stuff is very weird um is my computer being like nothing is clickable sorry technical difficulty as i'm saying uh these are recorded live so um yeah and so you also so you can see my thought process for this silly things like this but yeah life is short um appreciate people around you that's all i say for today um smallest string with a given numeric value uh okay let's see uh what does that mean uh lower k so a is one b is two okay so four string is abc is one plus two okay lexicographically smaller string with length equal to n and okay i mean this is just greedy um let's see i think i go over this a lot uh or not you know like in different problems i think uh and i guess my stuff is java but um but uh yeah um yeah so basically and this is just from experience these are gonna be um for lexographically smallest for this one it probably is gonna be greedy because it's just some um yeah because it's the sum and stuff like that and you know you can have small cases to prove to yourself the short story is uh was it smallest the largest okay yeah so you have like two numbers two one and two one or sorry one two and two one they both obviously sum to three um and you always want the smallest number in the beginning so that's basically the idea behind greedy and then the question is well how can you do this in a good way um n is 10 to the fifth so we just have to do it in linear times 26 is what my guess is and what i mean by that is just um doing it one digit at a time and then use math to determine whether um we can solve the rest right um so we'll do the math together i don't know the math of my head because i'm not that good at math uh but um yeah uh yeah but for example in this case we have n equals to 3 k is equal to 27 well we see if a the first character could be a and the first character could be a what does that mean right that means that n is equal to 2 k is equal to 26 is possible um and then we try again for is the second character i think a again is good yeah a which means n is equal to 1 left and k is 25 as possible right and whether this is possible it's just all math right because in the worst case um um you know in the worst case the last n flatter is just all gonna be z or z's um so then that's just equal to 26 times um n is the maximum number right where n is the number of n remaining so that's basically the greedy um idea that i have and gonna try and because you can do this one digit at a time um you know it's going to be 26 times n in the maximal case uh so which is going to be fast enough in this case um and you could call it o alpha times n or 26 times n which is oven or something like that um so yeah let's get started um okay so yeah so i have a result um i'm gonna make i think we could go right away but sometimes i like doing this and then just add concat to it um let's do it that way i think i actually don't know if python optimizes it so we can also if it's too slow we can make it an array and then do one join at the very end um but i'll write it the way that i want it to be right written and then now we just do one at a time which is um which one is the digit again n um okay so how do we want to write it so for index in range sub n um so what is this right so then we try one at a time so before for c for character is in range of 26 say um but is it's one to 27 i guess right because a is one so let's do that i mean you could change the four loopings any way you like but um is it one to twenty six or one two twenty seven huh now it's still two twenty five so it's one to twenty six so this is good um and then you know let's call it uh yeah and then basically now um how many digits do you have left right well the number of digits left is just equal to n minus index minus 1 because you want to consider this character um and actually i'll just move this is obvious that it doesn't change i'm going to move this outside and then k will progress um you know so the digits left not in and this is they just left not including this current digit um so yeah so if digits left times uh 26 as we said if this is less than k this is let's see yeah if this is greater than or equal to k then this is good right um it's k minus c yeah right because c is the digit that we're taking off um if this is just the current k that will remove um and this is the rest of the string that we you know will be all z's so another way of thinking about it maybe it's just that you know you have a string of all z's and then and this will give you some k or some other some value and then one at a time you choose a will just some be at least k or more if this is true then you know and this is good um otherwise if it's not you try b is this good enough right is this at least k or more and that's basically the idea here um and this is it in math form so if this is true we well k we minus c for using this character we saw we increment um and this in python this is a little bit messy but we just change it from yeah we just use this to convert it to um the character and i think that should be it um yeah let's give it a go i think i feel like this is mostly it but i feel like maybe i'm missing oh no i need this to break um because you only need to do it once because if this is not true then you need c to be smaller um is there a negative one value thing where this is too small it doesn't seem like it um like what is the okay let's try the other examples uh i'm again i'm just trying to think about like what if i have like five and four so it's not possible or something uh but maybe that's in the control oh yeah okay so it has to be at least that so yeah so maybe i was trying to look for that constraint uh so let's get oops what uh yeah that looks okay for now so let's try some zook i actually don't know okay so cases okay so one and i don't know seven or something um oh so looks okay so let's give it a submit oh no is it too slow i don't know okay that's fast enough though uh yeah so that's basically the idea um you do it one digit at a time and i think the better visualization is actually what i said earlier where you instead of trying to do it whatever you just have a string of z's uh where this is uh length n and then you try with a this is you try to see if this is bigger than k if it's not then you know you try b is this k or bigger um if this is bigger than k then you could go to the next digit uh you try a again you try b again you try c again and so forth um i think also there is an optimization that i've just realized that i didn't when i was doing it which is that i think um it doesn't make sense to try a uh b and then a because if there's an answer such that there's a b and then a you actually convert it from an a to a b so actually you could optimize this a little bit by setting up this uh as the last digit um so that should make things run a lot faster but uh but obviously as you saw it's not really given necessary and in terms of big o it doesn't change anything so that's okay um so what is this well this is um given that alpha is 27 or 26 i guess um this is of alpha times n so uh or o of 26 times n or of n which is linear and the size of the um no that's not true well n is the yeah so it's just all of n um and in terms of uh the result of course that's also of n because that is the length of the output um of course that is not linear in the size of the input because the subset into the size of the input is constant it's just an int but uh but it is red um cool uh yeah this technique of greedy and doing one digit at a time uh comes up a lot so i definitely recommend um just playing around with it i don't know if it comes up that much but uh but the idea is coming up with him in uh coming up with an invariant that you can see change as things go that comes up a bit and in this case um and like i said actually i didn't i came up this visualization just now so i think maybe uh that's a better visualization of just doing a one you know instead of quote unquote force one digit at a time we just check everything as the biggest and then we swap them to be you know um yeah maybe that's a better visualization let me know what you think um yeah so that's all i have um everyone please uh take care of yourself take care of others around you if you're lucky um you know stay good do well and you know to good mental health and i will see you tomorrow bye
Smallest String With A Given Numeric Value
detect-cycles-in-2d-grid
The **numeric value** of a **lowercase character** is defined as its position `(1-indexed)` in the alphabet, so the numeric value of `a` is `1`, the numeric value of `b` is `2`, the numeric value of `c` is `3`, and so on. The **numeric value** of a **string** consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string `"abe "` is equal to `1 + 2 + 5 = 8`. You are given two integers `n` and `k`. Return _the **lexicographically smallest string** with **length** equal to `n` and **numeric value** equal to `k`._ Note that a string `x` is lexicographically smaller than string `y` if `x` comes before `y` in dictionary order, that is, either `x` is a prefix of `y`, or if `i` is the first position such that `x[i] != y[i]`, then `x[i]` comes before `y[i]` in alphabetic order. **Example 1:** **Input:** n = 3, k = 27 **Output:** "aay " **Explanation:** The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3. **Example 2:** **Input:** n = 5, k = 73 **Output:** "aaszz " **Constraints:** * `1 <= n <= 105` * `n <= k <= 26 * n`
Keep track of the parent (previous position) to avoid considering an invalid path. Use DFS or BFS and keep track of visited cells to see if there is a cycle.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
null
52
hello my name is kaushik and today i'm trying to solve this problem uh this is the june late court problem and uh that is a slight modification of yes status problem that was in queen and this is a type two here the number of queen has been given and we'll have to find the number of district solution so yesterday i have been trying to solve this solution through backtracking method today i'm also trying to solve this problem as backtracking so how i'll do that let's approach that yeah suppose that is a matrix there is a third one there is a four by four cross matrix and from there that's method there is an i have been putting four condition where i can place that queen there as a column is that is yeah so basically i am in trying to that fast that is the sorry that is the q position that one and that is the that one so basically i have been trying to solve this through the row as row s after that it can be trying to solve that well it could be possible to uh another queen as the next column so they here the queen has been sorry where the queue has been present and next i am trying to uh putting there so that is not was possible so basically there one yeah sorry yeah that one yeah here the queue has been present so uh next column where it could be possible to send that there so that one and from there i have been text another condition where that next column that queen has been present to possible to that q not possible that one not possible because diagonally that not possible that's not possible so that solution not be executed so next one that is q so if i have been putting that value if i've been putting that value so for that third row position that is q so there q has been present and uh cube has been present because there is no diagonal connection has been possible from there i have been trying to last column where the q has b has to be present because so q they are not possible because diagonally and their q not possible so that's the condition has not been fulfilling so here i have been trying to finding that each and everything each and every column and row wise where i could place a queen and basically the queen placing condition there is queen co placing condition there is queen placing condition there is basically that same column not possible same row not possible as well as same diagonal not possible because in that condition each and every uh queen has been attacked with each other so i have been trying to solve that problem to backtracking or with recursion let's implement that first of all we have to initialize and vector of vector in sorry vector vectoring or vector of beta bool also i can place the basically there is a zero or one fraction has to be present there i've been trying to there is a board of n and vector of a bowl that one n of zero so all are false condition and now i am trying to make a call from here so i will be making that function later that is board will be passed and the n number of queen yeah sorry that zero that i have been trying to find the first row so basically i have to maintain that method vector of vector bool integer row if the row value is equals to board of size that means we have been reached to the last row so right now we'll have been putting as the i will return the one i have i right now i am found a solution and now i have been trying to recursive solution is that possible or not that is the column wise sorry call as much to zero correlation that one and we have to check that uh that coordinate if the queen has to be placed or not so we'll have to make an uh function that is checking that is it safe or not so board yeah board off board up row or column is it uh safe then i have been changing that value in the board that is one and now i have been recall the recursive call that is board of row plus 1 that one and i uh talk about the backtracking so here i have been returning that value i mean that backtrack the previous value so now we'll have to oh sorry i forgot to add that value and return that count yeah last one and we'll have to make that bool function that is safe or not first we'll have to check that the column value and that is if board of i of call is equals to 1 that means return false and now we'll have to check that first we'll have to check that the left diagonal left row as well as the left bottom diagonal so first then we'll have to check that condition that is rho minus i is greater than or equal to 0 and column minus i that is greater than or equal to 0 and we'll have to find that board of row minus i that and call minus i in that position there is a um there is a true position or not if there is a true position that will be written false so i am trying to set that condition suppose q has been present so i have to tell about that so how much left diagonal how much electron sorry that means suppose a that is the column has been present so that left value that left um row as well as that left bottom diagonal we'll have to check that condition and now we'll have to check that the bottom right uh sorry i mean that uh so right side uh diagonal right row as well as the right uh bottom diagonal case called plus a is less than n and what board of row minus i call plus i is equals to 1 then return false and after that return true so try to check that is there any compilation error or not yeah it's coming true once six trying to solve it yeah it's accepting try to submit there it's got to accept it thank you so much
N-Queens II
n-queens-ii
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_. **Example 1:** **Input:** n = 4 **Output:** 2 **Explanation:** There are two distinct solutions to the 4-queens puzzle as shown. **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 9`
null
Backtracking
Hard
51
767
hello everyone welcome back uh here is Van Thompson and today we are diving into fascinating problem from Bitcoin daily challenge uh seven six seven reorganized string so you are going to enjoy this and by the end of this session uh you will become a master of character manipulation so let's get started before we dive into the code let's break down the problem a bit so the goal here is to rearrange the given string as such that no two adjacent character are the same so if that's impossible we return an empty string so let's take a look at some example given input a b our output should be a b a so pretty straightforward right but don't let that fool you so the devil is in detail so as always python is my go-to language for uh today but Fred not go-to language for uh today but Fred not go-to language for uh today but Fred not a cut uh in order programming languages like go rust C plus and much more uh are in a description below so now let's talk about how to solve this problem we are going to employ an array sorting approach so the idea is to sort the character based on their frequency and then sprinkle them around to avoid repetition so this will store the array will store the character by frequency making it easier for us to pick and place them in a resulting string so first let's initialize our free frequency map and sorted array so we will Loop through the string to count the frequency of each character so uh count frequency of each character and it will be frequency map and four turn in s frequency map which are will be frequency map get Char zero plus one and now yeah when we do this second step will be to sort by frequency so let's implement it as well so sort by frequency and sorted character sorted frequency map Keys key Lambda X frequency map reverse true then check if rearranging is possible so with an input like a b our sources array after initialization will look like a and b so now comes the fun part we will populate the result array placing the most frequency character at event indices and rest at odd indices so yeah let's implement it IF frequency map sorted character greater than Len plus one two to read return empty and initialize result array so result will be known times Len s now place the most frequent character at even index so i 0 and 4 character in sorted characters four in range frequency map character if Len s I one result I director I plus two and return join of result so then we what we do so we place the most frequency Charter at even index so after processing our result array become a b a which is a valid answer because no two are just instructor are the same so finally we are joining this individual character to form our final string and yeah so let's run it to verify it's working four it's test cases so yep all good and good works perfect so now let's submit it for unsynthesis cases to verify it's work as well so yeah approach using a sorted array uh yeah we have runtime of 39 seconds and a bit 85 with respect to uh runtime so there you have it uh this is how you solve this intriguing problem so uh I have also implemented it using uh priority queues so in previous video so it was a bit faster so between 93 and just 35 milliseconds so uh that's how you solve it uh with uh sources array and I hope you found this uh Deep dive and live coding intriguing and also now know better how to implement and solve it and if you have question or article native approaches please leave them in the comment section below and don't forget to check the description for code in order programming languages and also if you like this video please like And subscribe for more coding challenges tutorials and much more mainly in pi but also in go and rest so uh and yep as always see you next time keep practicing and happy coding
Reorganize String
prime-number-of-set-bits-in-binary-representation
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
Math,Bit Manipulation
Easy
191
920
hello hi guys good morning welcome back to a new video and in the video Problem number of Music playlist asked by Google and Godzilla we are having n different songs with us and our goal is to listen goal number of songs so basically ultimately in the end I should be listening to gold songs although I initially have in different songs but maybe I can just repeat some pattern and it is saying goal songs need to be not necessarily it is different which means I have any different song but my goal songs it can be more than my n which I have the N different songs cool now so as to avoid get boredom in the trip I need to choose the goal number of songs my entire trip no basically just saying every song is played at least once so basically if I am choosing this gold songs and if let's say I have three songs in this n different songs I can't go and choose one two again I need to have three also so basically ultimately in the end I need to have three different songs for sure which means I need to have n different songs for sure in the end in these gold songs now basically what you say what it means is in the end all n songs should have been used now cool that is one point other point is all songs can be played again only if K other songs have been played which means I have let's say a song as zero now if I have S1 S2 up to SK which means K songs have been played only then I can repeat this song as zero again I cannot repeat the song as zero again here because with if I am gonna do that I need to make sure if I'm repeating any song K songs K other songs have should have been placed previously so when I am trying to repeat a song which when like which means I am trying to use a song s0 which has been used before so I'm trying to use that song again so for sure before that K different songs should have been played now my task is to return the maximum the number of possible playlists that can that you can create with all these 10 different songs and you know that for every song you need to make goal number of songs so for every song you have some options which are these and different options which you can have since the answer can be pretty large return in model 197 now again very similar stuff as you do as we have the example look okay we have goal as a three we need to make a three different songs now for sure at every location which means at every song I will try to place okay for this location which means for this song What all songs I can number of songs I can put here okay let's say I can put in three songs which means I can place three songs of the first location which it just means okay I have listened three songs what is the to listen first song how many number of options I have two listen the second song how many number of options I have Plus in the third song how many options I have it is just the same kind of stuff which we look at in the permutation that okay you will just see it is just the permutation of these numbers one two and three okay because for the first location I can listen the first song or I can listen to the second song or I can listen to the third song and that's how I can simply keep on building my answer again for the location first location I can just write okay what all songs I can choose to play on same I will just go on and ask for the next location what all songs I can choose to play on there was one song already I have chosen here I will just choose two songs okay one song chosen again remaining songs I actually want so I just simply get six songs chosen so you will see Iron it is so simple I will just know I have any songs so I have these gold places I will place n songs in the beginning then n minus one then n minus two and so on and so forth until it becomes a one but hold on here you are just placing your song uniquely okay here one song is placed here the next song is placed but I am saying that you can also repeat the song which means you can repeat a song which means here I have n minus two options but I can also play some used songs which I have earlier used I can also place them here as well now the problem changes a little bit that now I can also play some used songs that's how for this location number of options have now changed they are not entirely on okay what is the new song I can have you so I can have our n minus two options but still I can also play some old songs for the old song I have a condition that key songs should have been occurred before K song should have been occurred before and for sure ultimately in the end I need to have all n distinct unique songs so again we have that okay the goal it needs to be all the occasions which I have I need to fill those all locations now coming back to as we do in a simple problem we just look at the mid because we know for one thing for sure we need to also maintain we can do okay if I have unique songs and I'm placing a new song I can place but if I am going to place an old song then how will I solve it to just look into it how will I solve it I will simply make this example again and will go on at any mid location and we'll try to find the answer for that which means I am at this location which is the current location and I need okay it is a current location and I need to place a song now to place a song as I saw above I have two options for it either I can place a used song or I can place a new song now as a as you know you have n songs in total and as you are placing any new song so you will know okay what are the number of new songs left so I will just say okay it the new songs left so far will be n which is all the number of unique songs I have minus the number of songs which I've used so far it will just give me the number of new songs I have and I can directly place these unique these new songs number of new songs at this location but what if I use some use song I can use some uni some use song but please also make sure that okay if you are using a used song please make sure that okay in the end you also should be using all these songs too right now when I'm saying I am using I use songs now number of ways to place an old song now again as we saw above if we have something like this I need to make sure I although as you can see all the songs I have placed here are nothing but K plus three songs I have used so far but if I'm gonna place any used song here what other options I can have I can only place these three songs I cannot choose to place all these K songs why because if I let's say choose this song S2 I need to make sure that okay K songs should have been occurred in between S2 and if I'm gonna place the S2 again and you know for sure it's not s it's not K it is K minus two so annual show again K song should have mean occurred so you will see that okay to plays a song Here although you have K plus 3 you song as an option but you can only place three unused three use songs you can only place it so you are just mounting okay I can only place a M1 M2 or a s 0 because I need to make sure okay I have some K places with me again so number of used number of use a song which I can place right at this location are actual number of used songs minus K just the same okay actual number of few songs are actually K plus 3 but actually I can place in only three songs just saying that K plus 3 minus K actually giving me I can just Place three used songs at this location that's how number of songs I can place for the used songs are nothing but number of used songs minus K and if I'm placing a new song so it will be n minus number of you songs that are the number of phase to place any of those songs for the use song that is use minus k for the new song it is n minus used and that's how you know one thing and you know one thing that okay you will actually be seeing okay it is used minus K but RN what if the used songs are less than K so for sure you cannot place any of the used songs so the number of ways for the new for the user sound to play to be placed will actually be a zero so I'm just simply take okay what is the maximum of 0 comma used songs minus K it will give me the number of ways to place a used song at that location which is the current location so now you have gotten okay it is a simple recursion because I have simply two options so it's a simple recursion and for sure as we have seen when like whenever you have a recursion let's say take it not take it or simply okay it's being used not being used so we will simply know it's a memorization problem which will have a repeating sub problems in it so you can simply have overlapping sub problems so we'll simply apply a DP but for that we need to know the state of the DP we know one thing for sure as we were actually looking at it we just are requiring used and my current location because my K and N are already given the question itself so I know my current location is one such variable which I need to maintain because I am going out at every location and also I need to maintain that okay what is the number of used songs I have got so far because you know to get the number of used songs left I need and to get the number of new songs I need so I need NS fixed case fixed use songs will actually be there so again I can just simply get okay what are the number of huge songs it's more than sufficient and the current location to just put in those songs used or new anyway you can just Place those songs on that location which is the current location so now you know okay you just need used songs and the current location to find the answer and you know one thing for sure you just go on to every of those indexes every those indexes and will ask him if I can place a huge song at you then number of ways and then I can place a new song at you then number of ways and for sure it is okay either I can place a u song or a new song okay you song or a new song and again here also use song or whereas I use or new so it will be added but as we have to play song at every location so I will just simply multiply these number of ways which means simply getting our um you know it's I know it's a recursion so I will just simply initialize my Global variables as n goal NK just simply having n goal NK because I know I have to use those in Google and K with me I'll simply initialize my DPA which simply minus one because you know you have to Simply memorize that DP you have to Simply get you know you have to start with the current location and you also need to have the used songs number of songs used initially are zero because you have not used any songs and for sure uh number of the location in the initial beginning is actually also a zero now if you actually get the question itself we have the current location we have the use songs as soon as we'll we will look at it later on but for sure uh DP usual memory stuff that okay if you have encountered the state of DP simply return that DP state but if not then for short we have two options as I showed you we will use a used song to play use on to play number of ways as we saw above was actually used song minus K but it can be negative so actually picking it up okay if the Hue songs are actually less then I have no ways which I have which means I have zero ways so it is a number of ways if I used new songs but for sure you know you have to multiply at every location so you increase which means you increase the current location which means you went to the next location and you will find the answer which means the number of ways if you just put a song at the next location but you will simply multiply those ways right and again other option is either you are using a use song or you are using a new song If you are using a new song number of ways will be n minus U song because the number of new song will be n minus number of news so like number of user songs if it is the number of new song which I can place at this location which is the current location again I will simply multiply it with the number of years I can find out by simply getting what is the number of ways you can bring in by simply saying okay because I will go and look finally find for next location which is the current location plus one and number of used songs have been increased because one song I have used out of my all new songs because you know I'm using a new song which means I am you I'm using a new song now a new song will actually make sure okay now your used songs have increased by one here you are already using a user song so your user song will actually be still remain same now you have the new song you have the old used song your total is either you can place at current location either you can place a used song or a new song so used to song or a new song you will simply add that up and that will be a number of phase and for sure you don't have to worry about all other things why because you are simply multiplying it because you simply have to place your songs at every location so you will get the number of face if you place on for further location and you will simply multiply the number of phase you will place on for the current location cool and that's how you can simply apply that particular logic in here Simply Having it back okay we will simply memorize it and pasting this in our state of D which is use songs and current location with having please do modulus at every step modulo and modulo right now customer base condition I am just saying okay I want my all the goals being fixed which means I was aiming for goal number of songs so I'm just saying okay my goal number of songs should be completed which means my current location if I am picking and I have completed the songs up till gold which means I have completed the goal number of songs cool but if it is done I also need to make sure one thing that all the songs which I have used should be saying okay I have used all n different songs which means number of used songs should be equal to n as I showed you above Also let's say I have n songs as one two three but still if I am making my one two like this that's it you know my Gap my goal is completed my I have completed my four songs goal but still three is still not there which means number of used songs should actually be N I should be using all these songs so that is condition okay if all songs are used be used simply return of one else you will have to return a zero and that's how in this very short and simple code you can just get this fault ultimately you will simply return the answer by converting that to end and by this you can simply get your answer solved complexity again our goal into end because you are going on to every index and for every index you are simply going and checking okay what all used songs I can place in here and with this you can simply get a completely done in this particular time and space the code example for your reference I hope that you got it was a very simple maths plus DP questions if you had just one option which means if you have if you had just plays a new song you guys simply applied maths but here you had two options that's again you have to pick a path of recursion which means simply have two options so place this or this and as this or this came in picture you will simply do okay uh let's simply add a DP because we know as we have two options have this or this which means place this or this um take this or not like not to have this so we know we have to apply a DP at these points bye foreign
Number of Music Playlists
uncommon-words-from-two-sentences
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `goal`, and `k`, return _the number of possible playlists that you can create_. Since the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, goal = 3, k = 1 **Output:** 6 **Explanation:** There are 6 possible playlists: \[1, 2, 3\], \[1, 3, 2\], \[2, 1, 3\], \[2, 3, 1\], \[3, 1, 2\], and \[3, 2, 1\]. **Example 2:** **Input:** n = 2, goal = 3, k = 0 **Output:** 6 **Explanation:** There are 6 possible playlists: \[1, 1, 2\], \[1, 2, 1\], \[2, 1, 1\], \[2, 2, 1\], \[2, 1, 2\], and \[1, 2, 2\]. **Example 3:** **Input:** n = 2, goal = 3, k = 1 **Output:** 2 **Explanation:** There are 2 possible playlists: \[1, 2, 1\] and \[2, 1, 2\]. **Constraints:** * `0 <= k < n <= goal <= 100`
null
Hash Table,String
Easy
2190
73
oh yes now let's do this every third garlicy code that matrix 0 given an M into n matrix hip and element 0 7 and as row and column 2 0 3 in place and we must go through in this extra space just how do we do it then we are going to mark every 0 F 0 and column that we encounter which has a 0 we'll put a 0 in it first now first halibut let's see how that one work it creates two variables a pass for row in shainsa 0 4 columns initialize it to 0 1 and x will be equally of 0 I is less than matrix that length I plus 4 so 4 in J equal to 0 J a smaller than flicks switch dot length or metrics we return n J + + so now if which I J equal to zero then I want to check that in I everything this year or not if it is then a value 1 if j is equal to 0 and f c equals 1 otherwise matrix I will equally field and matrix 0 J okay so once this Lu exists we'll have our matrix of modified matrix we will go to the matrix watch move and check if but now we go from 1 to Ankush we have modified for sellable so if matrix or I 0 is equal to 0 or metrics Oh 0 k equal to 0 then my quick I J it will be real that will take care of all the row for us but we still haven't tangle is a fossil so cultural capital equal to 0 31 then we have 2 point I is equal to 0 is lessened matrix 0 length I plus and it is going to do matrix o 0 and I is a busier similarly for the column in the column has to be 1 then I will go here 0 will go here this is it let's run this line fold okay Sally mistake guys I'm sorry this one this again real quick okay lensing here 940 okay not very good okay let's see what happens now okay what let's submit the code now and accepted that's it guys 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,200
hello guys welcome to my another video so this is this video i want to talk about how i solved a 1000 and 200 nico program uh in this video i want to talk about how and why i did that and also what i learned from that and also my suggestion for you guys uh on that if you want to destroy an interview or improve your coding scale or uh solve more nuclear problems okay so let's get started so first we can check out echo page to make sure i'm not lying to you guys uh so you can see that i do solve one thousand and thirty plus nickel problems and uh so let's get started so first why i did a lot of political problems so obviously the first reason is that a lot of big tech companies they do uh the coding interviews and it will give you this algorithm problem so you need to learn and solve this problem so nico is definitely a very good place for you to practice these skills and nurses algorithm and try to solve the problem so that's the first second actually i think liquid actually improved my coding scale including enhancement understand in different algorithm ability to understand the problem more how you get a solution or different algorithm and also debugging and corner cases so actually code do help you uh we when you're trying to do the coding in your daily work you care more about details um so that's a second and the thing we come to the next topic how i did that so did i solve the problem in one day or did i solve the problem in a very short time like every few months so actually i solved the problem within a two years period i think so the initiative is that i need to do some uh interview at that time i need to find a job so i found that record is a good place to study this program and also practice your uh solution and also learning this algorithm and also it's quite fun and interesting so i do edited a lot of link code during this time and you can check that i have a lot of submission on 2018 2019 and also 2020 but i didn't do much in the past two or three years um so next is uh important to do a lot of nuclear problems so i would say yes because i think right now a lot of tech companies they do the coding interviews they will have the nico like problem or some other problems with different contexts or but they have the same a solution with the algorithm you know from so that's quite important from so that's quite important from so that's quite important uh you get a familiar with algorithm and also especially we are finding some jobs right you want to pass the coding interview that's very important so you know the problem the algorithm and what type of program you will you have with this servicing so when you interview when you have the similar context or a different problem you can always think about some ways to solve the problem right just like your dating work you kind of practice your skills and you know more about the system you know more about the context knowledge so you have a better uh knowledge how to handle this or how to do better in the future so that's the same theory um so next um and also after you solve like a lot of problems let's say 500 or something like that you can destroy a lot of interviewer just like just also including me i will be the one of the interview destroyed by you if you did a lot of nickel problems um so next topic is how to lay the code so i want to give you guys some suggestion and also uh from my experience so first check out the category the coding problem category like different data structure every uh trade map and also queue some stuff so it's very important for you to get familiar with each category and you get familiar with each data structure um in that case you can enhance your experience and knowledge in that area not only do some random coding stuff this will help a lot and second is that you can also uh check out the category by the algorithm type so for example uh bfs search dfs and also graph problem binary search etc so it's important for you um to give families with this algorithm in a deeper level so when you practice a similar problem uh in a short time so your brain will actually become better handling this problem so that actually also helped a lot and uh second suggestion is that you can focus on the first 300 problems so why is that because first 300 problem is very classic problem with different solutions or algorithm the other problem i'm more like the variation of the first 300 problems so actually they don't introduce any new algorithm but they just kind of change the context and also change the input output or maybe just they have a different kind of variation of the algorithm right but it's still behind this original algorithm or syria so you can enhance your experience in different algorithms in that case so next one is that you need to actually practice a lot for the first 300 problem so if you check out my screenshot here you can see that i have different submission history in different years so actually it's very important because sometimes for people the solve the problem but they actually they don't have a very deep understanding of the algorithm or they don't really know how to solve that they just check out the answer and they think oh that's a correct answer or that's the idea for that but after a while he just they just forget about that forget about idea forget about the algorithm so when you choose him or will you uh when you check out the same problem actually it is very striking for steam to uh re to re repost the same solution which means you need to spend more time practicing the problem and strong stress in your understanding of this algorithm right so that's my another suggestion and don't be afraid of the checking out of the answer so you can free feel free to check the answer if you uh if you are not familiar with the problem or i have no idea how to solve that after like 10 minutes or 15 minutes and also just uh and also in this progress you are able to you can also search online to know this algorithm to know the basic idea of the algorithm so by doing lead code you're not only just doing analytical or you are forcing yourself to solve the legal problem but also it's a process of to nourish the algorithm to know the basic idea to learn how to solve a problem so don't be afraid of checking out the answer just do that if you can really solve the problem or you have no idea what the problem is or how to solve that do that and um just to make sure uh you will revisit this problem uh after a few days so i would suggest you also uh address him to a specific folder i think lincoln has this function that you can add is a problem that you are not very familiar with so you solve them by checking out the answer in a separate folder or something like that so you can rebase them in the future uh and also other than that you can also solve the problem multiple times um and so you can have different texts for the problem different folder first problem the problem that you didn't solve when you first time do the problem coding or the problem that you didn't solve even when you do the second time and also the problem that you didn't solve even when you do a third time of that so this will help you enhance your understanding of this algorithm and also enhance the understanding of how to solve that so hope that be helpful and also the third one is that don't focus too much on the heart problem the reason is that hard problem really it's not easy like just like laser name it's hard sometimes it will make you strong frustrated and a little some motivation to nerds algorithm or to do the late code so that's not good that's the first one second one is that actually a lot of big tech companies they don't do hard problems for the i think i have 100 plus coding interviews in my experience in the past few years so i actually i um i mostly get a medium problem or medium plus i didn't get a lot of heart problems so you can actually skip that especially when you just that beginner to start the analytic code it's very important that you focus on the medium and also easy problem to get user confidence and also to get you just familiar with the algorithm not necessarily get familiar with the complex problem or complex context something like that okay so yeah that's all about how i solved the 1200 plus nicole problem and what i learned from it and some of my suggestions for you guys to improve uh your lead code or coding or interviews if you found this video uh interesting and helpful please like this video and uh subscribe to my channel uh and i will have more videos coming soon and also if you have any other questions regarding lego or interview or any other stuff please comment this video i will answer them thanks see you
Minimum Absolute Difference
remove-interval
Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows * `a, b` are from `arr` * `a < b` * `b - a` equals to the minimum absolute difference of any two elements in `arr` **Example 1:** **Input:** arr = \[4,2,1,3\] **Output:** \[\[1,2\],\[2,3\],\[3,4\]\] **Explanation:** The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. **Example 2:** **Input:** arr = \[1,3,6,10,15\] **Output:** \[\[1,3\]\] **Example 3:** **Input:** arr = \[3,8,-10,23,19,-4,-14,27\] **Output:** \[\[-14,-10\],\[19,23\],\[23,27\]\] **Constraints:** * `2 <= arr.length <= 105` * `-106 <= arr[i] <= 106`
Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals.
Array
Medium
null
1,337
Hello everyone, welcome to my channel, it should be easy, it is a very good practice question, the question has been asked from Amazon, only the problem statement was different, okay, it is a matrix , the name of the question is the company, who asked, Amazon has asked two questions, very simple. What is to be said in this is that the given matrix will be binary meaning it will either have only zeros or one. Okay, look at the example. Look, it is not only zero or one. Okay, look at any row . 1111 Only after that C willions. He will not come later, all the soldiers will be there in the beginning itself, so it is seen that it is sorted in descending order, it is seen that it is not the date, which D is one file upper, you are D left of D, which D is cleared, hold it first and which of the two How will they know if the number of soldiers in row is week? Take it. The number of soldiers in row is okay. If I have less soldiers then that disorder is in the row. It is okay and if both of them have soldiers in their account then both of them have less soldiers. The index which is smaller than se will be the disorder like if i &lt; j then do this and sort . There was only one soldier in roll number zero. How many were there in roll number zero? How many were there in roll number 3? Only two soldiers were there in roll number one. Do soldier rows. Number four will be 500. You see, they are the strongest. We have arranged it. Okay, so it is obvious that we need the first three, we need them daily in three ways. So see, the answer will be 203. The index has to be sent. 203 questions must have been understood. Let's see the approach, friend, we will make it with two approaches, first of all we bill the installment, that is the most important thing, okay, let's see, when we were looking at the example, we got half the solution from here, right and tuition is a little from here. It was very clear that what we have to do is to count the number of cells in each cell and store them. Okay, just like a mother takes how many cells we have. Okay, so I am 5 sizes fine and this is what disease it is. All you have to do is share this information. Okay, roll number 2 has roll number 21, roll number 3, roll number 4, till now it is clear, now see what to do brother, we need a weekend, this one has two, this one also has two, but whose index is there in both of them? Smaller is smaller, so first will come 4, after that 54 will come, I have stored this in the vector of my account name, okay, do nothing else, sort, dog and not in sending order, so by default it will do such a shot, first second, what else has to be sent, only index. You have to send zero three, remember this was our answer 203 Now the question has come that brother, how many forests are there in each row, how will they come out, it is very simple, first of all, what is the method, you should do whatever is right in each row and travel, you have got a lot of forests. Good one was found, very good one was not found, wait, which is fine, so one is the method, what is the first method of counting descent, what is the first method of linear account, one is fine, the second is binary search also, now you can apply my It must have come to my mother. Think, it is sorted in this order. First one is followed by zero. You can find out where the rightmost one is. Talk about it here. Okay, so first let's see from this approach. Okay, okay. The one with short brinjal count lineage, I have sorted it in the sending order. The elements of the first are here. If the number is taken as mother, if M is then it will be equal to rose and if you push the element here then it will go to your place. Look . So O of M login, the first one plus K will be taken in the last one. This is your time complexity in forming the result. Okay, and how much space complexity did you take. Look at the count of times and the size of the vector in which you have stored your elements. What was M, was that of M, so space comparison is going on, yours is correct, so this is approach band is going on, so very simple code is going on, its ok, just one thing, what we have to see now, brother, which is binary search. No, how will they write, what to find in binary search? If I want to find the right most one, then I will find out how many ones are there in total. If I find out that the right most one is in the index one, then I will find out how many right ones are there. I can't do it easily, whatever is the value of the index, add plus one to it, so look here in this row, look at the right most one, in which index is the third index, this is on the third index, so how many times will there be in total. By doing three plus one, by doing two, we will get one by doing one, two by three, okay, so I am going to get the same from binary search, so I am showing you my binary search by writing it here, okay, which will be very simple, okay, I will write one here. let's see you One one zero is okay, I will do the indexing 012 Third column Fourth column is okay Now pay attention, we have to put binary set, so here L will start from zero and R remember my pen will start from minus one and if there were more columns then This will be n - 1 so r will start from my n - 1 l will start from 0 we have to put binary set okay so right now I don't know in which index the last one is stored so I will put -1 in the result index. I store it, okay, I leave the mid, give mid, what will come, its mid, this will come, is its value one, yes, its value is one, then I will go to mother, maybe this is my right most one, okay, so what is the index, see . There are two, so here I have made the index 200 in the result that brother, it will be the last one in this index, but it is possible that it may not be the last one and you have to go further to the right side, you will find one there, actually it is present here right now. So we should go to the right side, so what will we do to find the right side, if we move L to mid plus one, then L will be removed from here, helmet plus A will go here and if I find one, then I will try to move to the right, okay. Now look, Aloe Vera is here, mine is okay, it is equal to one, no, it is not equal to one, if it is not equal to one, then you will have to move to the left side. If you move to the right, left side, what will happen. R = mid minus one, so R is here A. Okay, now look at R, whatever is there, give L, that means A loop will break our binary search, so look at the value of the result in the last one, it will be absolutely correct, interest will be left. Already in the third index, my last one is okay, so that means how many count offs. There will definitely be times, whatever result index is there, do plus one in it, do plus one from the result plus one, do one, two, three, it was a very simple binary search. When we code, we will do the story from that, then we will go to the approach. Okay, so let's code it first. We will make our approach from one, okay so first of all after that I said that I will make a vector in which I will keep the count of once, I will keep it daily, how much count will be of which row, so I define here, this is what I always do. So see my code is a little simple, I have defined it above so that I just write P here and say vector of P, then P of Income and okay, let's name it Count Vansh, okay, what noise will it make, my account of Vansh is fine . Which other rock is there, it is clear till now let's go to each row in this row, make it equal to zero row, take it as M row plus, okay which disease is this one, the entire row will go away, isn't it the function count ? Sorry count one, which is mine, it is fine, result of i = index is just to be sent, this is the first element and this is the second element, this is the second, so I am sending the index, see return the result in the last, I have given you a spring quickly. Submit and go away, it's okay , it's okay and if you keep it intimate, then mid will come out every time, its mid is okay, if it becomes equal to one, maybe this is my right most one, then don't put it in the result, but right and Let's go and check, that is, we will do L = Mid + 1, okay, if there is no one, then it will be zero, it means we have to go left hand, then the left side is equal, you R = made minus one, this is what the left side means, okay. Lastly, what do we have to do? Why send the runt result plus one? Send plus one because the result is an index. We have to send the count of once. To send the right count of one, how many counts are there? So whatever index, add plus one to it. Ok, let's see after submitting it. This time using and first approach, now let's go to our second approach. Okay now look at the approach, I will not tell you in advance which data structure to use or what to do, first you understand this. You noticed in the questions that in some questions. It has been said that we need sources of K. Okay and from Now I thought, brother, what to take for this in my playlist, I have asked a lot of questions, there I told you one thing that if you look at banana, it is okay to go from smallest to strongest, if you want to go from smallest to largest, then it is okay, what does it mean to the largest one? You will have to remove the largest one. To remove it is necessary for the largest one to be on top. If we get it right then we will keep removing them. Ok, a simple trick is that if the smallest is asked then take the max hip. If the largest is asked then I just take the reverse of that. So here I asked the smallest to the largest. It is the weakest, so we will take a simple Maxi. Okay, what is the use of taking it? Now I will show it to you by driving through an example, so look at this example and understand that you first went to ISRO, okay, you calculated the binary search, how many number of ones are there, how many in it? Number one to two is one, which row is zero through, okay and you have also defined your max here, okay, this is your maxi, so as soon as you got this information that brother, there are two one here and How many rows are there 0? So you have put it in the maxi. Whose maxi will be in the maxi? It will be the maxi of the leg. Okay, if you have put comma zero, then it is on the top only. You have put comma zero. Okay, and we remember how much was k3. Na, 3 weeks, you are the largest, I wanted to tell you, okay, here you are at 3 weeks, you have got tax one, so brother, if you have got 41 and now you put it here, then now it will come on the top because its value is big, the maxi big one will come on the top. Right now there are only two, okay, great, now let's come here is one, right, row number, you are there, so look, there is one, the smallest value is 20, it will go here, and now the one comma 2, which has come, will go here, because this is the smallest value. Now here, how many are there, two are one, row number is three, okay now look carefully, this is smaller than two, so come down, these two are equal, so look at the bigger value among them, the account of both of them is one. If it is equal then the next cellmate will be compared. Look, if the index of 3 is bigger then it will go on top. Okay, so let's shift 41 up. Here, A should be three. From here we will pop the top element and look at the top element. If you top then always the bigger one will come out because this is the max hip so the largest value is from here, so four one is popped, I removed it from here, you are seeing the advantage, okay that means how the size of the hit will never be big, the size of the hit It will always be equal to K, immediately we will pop it, okay, its time complexity will be just off K, it will not be more than this, okay, row number is now by the way, it is the biggest value, so A will go here, okay, still hit. Look at the size, it has become 4. As soon as I do it, I hit delete, it popped up, now you don't have to do anything, you have to extract the value from HIP and put it in the result. This is my result. You can definitely see the elements in HIP. It will be the weakest and it is true that this one had one, this had two, this also had two, okay, we only want the index, so look at the hip, when the elements come out from the hip, it always comes from the top, so the bigger one will go first, so now just that. You put it last, put it here, 0112, we need an element, so I took the size of the result, okay, so from the top I popped 2, you comma three, there were two bands, what was the index of the row near it, if it was three, then I will put it here. This is because you are strong on it, right, how much is going on every rupee, so people of N are going here, M of people are going here, it will definitely be felt, okay, it will be felt there also. Remember people, the off key was being used, it is okay to push and pop, okay, so what is the size of the priority, brother, it will go there, okay and if we look at the space here , it has not been taken, it is just the space of the result, which is my result vector. If so, what is the space of priority? If it has maximum number of elements then it will be turned off. If it goes there then it will be of space complexity. It is ok but its time complexity is a bit butter. Look how its time is. We are carefully applying plus of Amazon . After that, remember M was sorting, we took it out of the loop and put analog M in it and this was look here of M people M na g ke so it is going in both of them, here is the binary search in every row but see this. M is Log K, there M block was M so this is a small value, it is okay because if you stored the entire element there and sorted it then it would look like Mrig M, here it is Log K only, so it is butter, okay quickly. Let's code, we will repeat the sorry. Already in the code that is present, we will remove the sorting and apply the concept. Let's modify this code, so those who code it from the code approach, binary search will remain exactly the same, everything is fine . Here from count one, we will not have to take the vector which we had taken separately. Why are we taking priority? This time it is right for write priority, so by default this is the maximum fee. If you do not enter co-operative then this Max is divided only brother, the default is fine, and here I am removing the count of one from all. Okay, now what is being put here, are PK dots being pushed, whom are you putting whom? That becomes my Greater Dane's key, then I pop it in the PK road, you will know it, okay if I pop it, then it will seem locked up, people can also plus these two in the off key. M * Take this out. It is clear till now it is necessary to sort here because when we pop the priority, the bigger element will pop first because it is the max, till the priority is reached, I will keep popping right time, this is equal, you have taken out the top element from the PK and added it. Now I have added it to the top index of the result because what used to happen in seconds is to add the index of the row which is present in the description and I will share the PF note of the iPad too, okay thank you.
The K Weakest Rows in a Matrix
design-skiplist
You are given an `m x n` binary matrix `mat` of `1`'s (representing soldiers) and `0`'s (representing civilians). The soldiers are positioned **in front** of the civilians. That is, all the `1`'s will appear to the **left** of all the `0`'s in each row. A row `i` is **weaker** than a row `j` if one of the following is true: * The number of soldiers in row `i` is less than the number of soldiers in row `j`. * Both rows have the same number of soldiers and `i < j`. Return _the indices of the_ `k` _**weakest** rows in the matrix ordered from weakest to strongest_. **Example 1:** **Input:** mat = \[\[1,1,0,0,0\], \[1,1,1,1,0\], \[1,0,0,0,0\], \[1,1,0,0,0\], \[1,1,1,1,1\]\], k = 3 **Output:** \[2,0,3\] **Explanation:** The number of soldiers in each row is: - Row 0: 2 - Row 1: 4 - Row 2: 1 - Row 3: 2 - Row 4: 5 The rows ordered from weakest to strongest are \[2,0,3,1,4\]. **Example 2:** **Input:** mat = \[\[1,0,0,0\], \[1,1,1,1\], \[1,0,0,0\], \[1,0,0,0\]\], k = 2 **Output:** \[0,2\] **Explanation:** The number of soldiers in each row is: - Row 0: 1 - Row 1: 4 - Row 2: 1 - Row 3: 1 The rows ordered from weakest to strongest are \[0,2,3,1\]. **Constraints:** * `m == mat.length` * `n == mat[i].length` * `2 <= n, m <= 100` * `1 <= k <= m` * `matrix[i][j]` is either 0 or 1.
null
Linked List,Design
Hard
816,817,838
221
Loot Hello Everyone Welcome Back To My Channel Suggestion Or Go Into A Personal Problem Problems Maximum Square Year So In This Problem What Were Given This Will Give The Name Cross And Tricks And Tips For Angry Matrix Means 2001 Need To Find Out The Largest Per Containing Only Wants a determination to achieve these test cases in which give videos and win in to-do list within videos and win in to-do list within videos and win in to-do list within Siberia and then continue at maximum only once in every side to the Video then subscribe to the Page Loot Princess Can Only Be Research Scholar Off Side Want Fight Alone in One Suit 12312 2nd One and Very Soon You Will Be No One Should There Be No One Will Be No Problem No Veer Saput Ko Ki Irfan Want to Know Left Over Your Favorite Position No That is Not Possible for Possible and You Standing Position Me Too Right Side Bottom Right Corner Not Possible To Know What Is The Right To Make Over All World So This Corner Is That Similarly Similar Id Take This Point Is Prompt Defeat A Flat Se Effect A Study That Laced Is A Design That Is I Want To DC on this one with the right bottom corner of square which Kulbir where possible request be Aishwarya size equal rights for or citric well shoulders coming soon this cannot describe this cannot be this and feedback from here and with a distinguished stree ko stree dress not to Square Possible When This Is The Right Water Resource Coming In Between Option Is Videos On Square Carolina University To-Do List That Is Vihar To Make A Square Me To Make A Square Vishnu Right Bottom Corner With This One Is This Tell Which one can we make a jo f-35 Tell Which one can we make a jo f-35 Tell Which one can we make a jo f-35 kulbir and i ask ride gautam corner is this so what confusion which we get from this can be no know the question adhir where possible Share subscribe and subscirbe possible and 120 2011 no like and share the video Like And Share And Subscribe And Share Thank You To Go Through Who Is That There Is No Zero No That Was Not Here Me But Who Is The Best Player And Share And Subscribe Possible End On Side Beat The Side Of The Year Which Will Hear Here A E Will Be Minimum Turn Off A We Now Ko Machine A Ko Minimum On Minimum Side Dim Cea Plus Vwe Backlash Co Explain Want To Have Alleged In 31- 05-2018 31- 05-2018 31- 05-2018 1582 The Minimum Science Which Software Which Are Pending Here Subha Minimum Par Which Is The Twilight Vanished And Will Make You Aware Of Area Off Side Minimum Now Machine Plus One Thing Which We Will Do You Know What Will Be The Year Ending Here What will be the year ending here and right side par lena hai are minimum hai aur one hum abhi ko machine plus one which will be the side of the square which will and share that try election lattu an electronics approach to send me to see Need to decide subscribe enough to give me numeric 10 hour se side par ki poushad side aapke ear witch will and the self witch will and addition means like and share like share and subscribe the channel now to receive 102 ki lakhyou sushil let me clear hai That This Ribbon One And White And Every Night See You Will Start From Gift Veer Vo End Column Tulsi Fuel Means The Position Of Beat Only Possible And So 101 Subscribe Now To Take To Find The Square Root Which You Want To Be With 10 Similar When E That Find Over A Year Ago That Holiday Also Sawn You Will Provide You Have Not Taken When You Might Not Taking It Difficult To Find Square Meters Which Will And Will Be Given Only Now Can Not Possible In All Possible Liquid Which Will Give You 110 Such Light Come Now Avoid Her That Sufi When A Guy In This Way Can Have Him On So Will Find Amazing Pain Disappears With Minimum Amazing 1020 Plus One Side Per Possible Due To Beat Not Be Possible To Make The Side Of Possibly Due To E Hai So Let's Pradesh Vansh Minimum ISRO Ka Mang Ko Mann Anti Possibility Come End Monitor Surya Minimum 1000 Ka Not One Should You Will Surya Minimum 10 Plus One Because Many Years When E Ko Again Will Appear Welcome Mobile Destroy All So Come 121 Maang Ko Mann Manavwal Minimum Will Be One Plus One Vikas Vihar Near Civil Right Side 2012 Side Ko Arvind How To Do Subscribe 2.30 Ek Veer 2.30 Ek Veer 2.30 Ek Veer 1.11 Ko Minimum Kar Do Ka 1.11 Ko Minimum Kar Do Ka Simran E0 So0 Minimum Nothing 2000 Note 10000 Maximum Volume Maximum Side Of All Want to submit update I hope I understand what are you doing and how we prostate show the formula calf using S2 field its metric because of SDP liye quality sur DP of particular IPL huge feeling hello how your feeling beating minimum after Getting through values ​​where is this what is this Getting through values ​​where is this what is this Getting through values ​​where is this what is this is a coma like for which were fighting for finding it must be taken this position will be one lutai - man ko lutai - man ko lutai - man ko minimum of dpi - one ko masjid ko minimum of dpi - one ko masjid ko minimum of dpi - one ko masjid ko ameer wa And You Will Be 151 - - Verb - One Who Will Be Broke This Is Robbed On A Figure Of I Commerce Mi ID Minus One Will Find Minimum Second Plus One Because Senior Ministers And Willing To Decide Aside From Love Quotes For This Thank You A Solution To approach to degree sample business class 10th land acquired 70% in business class 10th land acquired 70% in business class 10th land acquired 70% in those days other wise water for any damages pay matrix in Delhi after eating to the matrix in cases where is hui door hoti ia 3010 column and value in the matrix is hero in both cases will Do matrix i ko maje - jiva maje - jiva maje - jiva visit rate is lineage is mexico maje is 151 - visit rate is lineage is mexico maje is 151 - visit rate is lineage is mexico maje is 151 - top come 210 vik and widening distinguished from all the meaning of this and also left side ko majbar prithvi side 00000 time will be updated on hua tha to vent to welcome A President Will Be Updated From 02111 Subah To Hai To 8 Class Mil Return Side * Hafiz 8 Class Mil Return Side * Hafiz 8 Class Mil Return Side * Hafiz Saeed This Is The Simple Approach Time Questions Play List Making Tools To 1pm Time And Space Subscribe Now To Receive New Updates Reviews Value Every Time You Will Find The Value Of That NDC Volume-1 1This Value Is In Shamrock This Volume-1 1This Value Is In Shamrock This Volume-1 1This Value Is In Shamrock This One And Two Values ​​Aadat Problems Russia This One And Two Values ​​Aadat Problems Russia This One And Two Values ​​Aadat Problems Russia This Project Volume And They Want U Want To Thank You Just Need Every Time E The Previous Role Every Time E That Genealogy One Value Which Is This One Will Get From Near This Mountain Soni Jagdish You So Will Only To Prepare You Will Only Take Away Or You Can Say Which Will Contain The Value Of The Giver And Debit The Good Night Some Ideas For Temple Optimization To Reduce The Time Of Press Complex Lekar Bhairav bhi same suji is given taking two vectors 124 the previous oh and 124 rates on current role bilkul vishnoi the times will only need to find the current value is the previous true values ​​and which prevents the same values ​​and which prevents the same during a that suji sadh is condition Also Same Is The Difference Between The Salute To Withdraw The Dominance Refining Minimum Of Previous Day - One Means Minimum Of Previous Day - One Means Minimum Of Previous Day - One Means Lips Se Fluid Once Mode Servi Tv And Share And That Prithviraj Dhara Like It And Enjoy Discharge Value One And Distance Is The Same Ko Lamba Previous 125 - Man Ko Masjid And This Vansh Is The Previous 125 - Man Ko Masjid And This Vansh Is The Previous 125 - Man Ko Masjid And This Vansh Is The Previous Rota Minus One And Kolam Of The Prevention Gmail Account Torch Light And This Also Means That You Pray Jai Sukhdev Vihar Will Be Systematic Food Taster Metro Station Person Soldiers Will Be Chief - Soldiers Will Be Chief - Soldiers Will Be Chief - Ashraf -Ul-Haq do minus one upon - minus one upon - minus one upon - subscribe and will BJP's picture to respect and services - by the picture to respect and services - by the picture to respect and services - by the previous day - 100 salute oo hai previous day - 100 salute oo hai previous day - 100 salute oo hai enter janmanas mein which is well in night person should do the same plus one every time to be Taking back side and in which was doing subscribe for and 2000 subscribe now to pick up the phone the father neck titration are here and here so aaye ho gaya front student let me to go [ let me to go [ let me to go a bright where is the number of columns In The Matrix Point To Point Video Please Like And Subscribe My Channel Short With Friends And See The Question Thank You
Maximal Square
maximal-square
Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_. **Example 1:** **Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\] **Output:** 4 **Example 2:** **Input:** matrix = \[\[ "0 ", "1 "\],\[ "1 ", "0 "\]\] **Output:** 1 **Example 3:** **Input:** matrix = \[\[ "0 "\]\] **Output:** 0 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is `'0'` or `'1'`.
null
Array,Dynamic Programming,Matrix
Medium
85,769,1312,2200
27
hello friends welcome to coding host youtube channel in this video i will explain you a lead code problem remove element so in this question we will get integer array nums and an integer val so we have to remove all the occurrence of this val variable in the nums in place the relative order of the elements may be changed so we can see this example one in the input we are getting a array nums in which we have four elements and in the val variable we are getting three so from this array we have to remove all the occurrence of three and in the place of theory from the beginning the next element will take place and in the return we only have to return the number of elements remaining so here they are telling that do not allocate extra space for another array and you must do this by modifying the input array in place with a big of one extra memory so we cannot make another array so first i will write the program and then i will explain you so first i will take a variable end p equal to zero then i will take a for loop for n to i equal to zero and i less than nums dot length and i plus now in this for loop i will take if statement if nums of i not equal to well so inside of this i will write like this nums of p equal to nums of i and p plus and in the return i will return this variable p now let's run the program so you can see that this program is working fine now let's see how this program is working so in the input we have this array in which we have four elements and we have to remove theory from this array so first i have taken a variable p equal to zero so we have a variable p its value is zero then i have taken a for loop for into i equal to zero so this for loop is starting from zero value of i is zero now inside of it we have a if statement if nums of i not equal to well so nums of i means element at index zero at this index element is 3 and in the value variable element is also 3 so these elements are equal so this if condition is false and it will not execute after that i plus i will become 1 and now it will again check that if nums of i not equal to val so this time at index 1 we have 2 and in the val variable we have 3 so 2 is not equal to 3 so this if condition is right and it will execute so in the array at nums of p we will store the element which is at nums of i so value of p is 0 so it means that in the array at index 0 so at index 0 we will store the element which is at index i so at index 1 we have 2 so now it will get stored at index 0 after that we will increment so p will become 1 after that i plus so i will become 2 now this if statement will again check that nums of i not equal to val so at index 2 we have 2 and in the val variable element is 3 so these elements are not equal so now this if statement is right and it will execute so now at index p which is one so now at index one we will store the element which is at index i and the index i is 2 so at index i we have 2 and we are storing this 2 at index 1 after that value of p will increment so it will become 2 after that i plus so i will become 3 now this if statement will again check that numbers of i not equal to val so you can see here at index i which is three element is three and in the val variable we have the same element so this if condition is false and it will not execute after that i plus so i will become 4 so when this follow will check that i is less than nums dot length so i is 4 and it is not less than nums dot length so this for loop will break and in the last we will written our variable p and its value is 2 so you can see that rest of the elements at index 2 will remain and at index 3 also remain but we do not have to care about this remaining elements because in the front we have the elements which we want and we have removed the occurrence of the well from the starting of the array so rest of the array will remain as it is and when we are returning the variable p which is 2 so it will only print the first two elements from the array time complexity of this program will be big of n because we are only using a single for loop and the space complexity will be big of one now let's submit our program so you can see that our program has submitted successfully thanks for watching
Remove Element
remove-element
Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_ `nums` _which are not equal to_ `val`. Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things: * Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`. * Return `k`. **Custom Judge:** The judge will test your solution with the following code: int\[\] nums = \[...\]; // Input array int val = ...; // Value to remove int\[\] expectedNums = \[...\]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums\[i\] == expectedNums\[i\]; } If all assertions pass, then your solution will be **accepted**. **Example 1:** **Input:** nums = \[3,2,2,3\], val = 3 **Output:** 2, nums = \[2,2,\_,\_\] **Explanation:** Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). **Example 2:** **Input:** nums = \[0,1,2,2,3,0,4,2\], val = 2 **Output:** 5, nums = \[0,1,4,0,3,\_,\_,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `0 <= nums.length <= 100` * `0 <= nums[i] <= 50` * `0 <= val <= 100`
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
Array,Two Pointers
Easy
26,203,283
1,200
what's up everyone today we'll be looking at uh this question what is minimum absolute difference I should have loaded it earlier so 1 120 minimum absolute difference um yeah so let's start the timer and let's see if we can solve it solve the question okay so given an array of t distinct integer are find all pairs of elements with the minimum absolute difference of any two elements return a list of pairs in ascending order with respect to pairs each pair AB follow uh follows AB are from array a is less than B minus a equals to the minimum absolute difference of any two elements in Array okay I did not get this question um the minimum absolute difference is one list all pairs with difference equal to 1 in ascending order given an array of distinct integer R find all pairs of element with the minimum absolute difference of any two elements find all pairs of elements with the minimum absolute difference of return a list of pairs in ascending order with respect to pair each pair a follow A and B are from array a is less than B minus a equals to the minimum absolute difference of any two element in AR so I guess minimum absolute difference 4 - 3 B minus a is less than b a are from array so 1 2 3 and 3 4 okay so I guess we I need to find a absolute difference between find all pairs of elements with the minimum absolute difference of any two elements so I guess first of all we need to find a minimum absolute difference between uh between the pairs like if I do o of n² for 10 ra to five that would be too much but yeah like I guess I need to I guess uh what I need to do is I need to do find a minimum difference and then I need to find up find all those pairs which satisfies that minimum difference right is that right is am I getting that question right no way of telling but uh if you see this one and two they both form a pair of that kind two and three also form a pair of that kind and three and four also form a pair of that kind uh which has a minimum absolute difference of one so in this case let's see 1 and three is two the minimum difference is to um so nothing here is satisfying that so 1 and three is the only one so 3 and 8 is um so what companies have asked this PayPal Bloomberg Amazon okay not a lot but yeah um so 38 - 10 so I guess uh to find the absolute minimum absolute difference I would say uh I'm thinking that either we have to calculate uh for the first two elements like after sorting the Sorting the array we will have to uh take the first two elements and then find the absolute difference between them that would be minimum or else uh we can find the difference between last two elements but uh but as uh the these are uh the absolute difference can be anywhere in the array itself I guess uh we need to search for the absolute difference of so my time complexity for this algorithm would be in and login for uh sorting them then n² for finding the minimum absolute difference um so again n Square for finding the pairs which satisfy that condition is that right yeah so that's what I'm thinking can we code it out yes we can try to code it out and let's see if that uh that works so I did not ask the question uh if this array what size of the array will be always two okay gotcha so let's see uh let's do one thing let first sort a do sort a comma B A minus B so that will sort the array then for let I is equal to z i is less than uh R do length I ++ ++ ++ for let J is = to for let J is = to for let J is = to I + I + I + 1 and I J is less than R do length j++ what I need to do is I need to j++ what I need to do is I need to j++ what I need to do is I need to find the minimum difference right let M Min difference is equal to let's call it number. Max save integer um just for the comparison sake and at any time if we math. Min if math.abs R of I minus um R of G the are with Max oh sorry Min if Min so if you just want to let current diff uh to make the code cleaner um what will what I'll do is this and current diff okay so what we also need to do is uh we'll do this and finally after all of this we'll find our minimum difference and then let rest is equal to an array to which we'll be pushing our um the difference and then finally what we'll do is return that rest so let's copy this block of code I guess this is going to take a lot of time and I get it might also um uh exceed our time then minimum div equals to sorry I need to do this again so let's take this here and do current diff and if this at all is equal then minimum diff is equal to then what we need to do is do push R of I first R of J next so my goal so that's it I guess and my goal is to just uh check if our test cases just executes yeah so everything get fast so basically our logic is right for solving this question but it's not highly efficient for larger uh test cases because yeah it's going to exceed time limit exceeded yeah I thought so is not very efficient so how would you um make it more efficient or reduce the time complexity minimum absolute difference okay what is the hint that we have here oh not this hint why is this is going here okay yeah hint find the Min minimum absolute difference between two elements in the array I did find that the minimum absolute difference must be the difference between two consecutive elements in the sorted array thanks for letting me know what if they are not consecutive what's uh so do we have here any consecutive number no so sorted at I know I have already sorted it but how can I figure out so okay so I know the minimum difference now between my idea is now what I have is the minimum difference right minimum difference so if I have this 1 3 6 10 15 okay let's take this um let's go to the road uh this I hope this is not reset or if I do this and delete this okay I guess I need to refresh this okay now if I delete this and write okay sorry my bad 1 2 3 4 right so the minimum difference here is minimum diff is one after traversing so my in is to start from index uh one and then check if the adding uh taking the previous value and adding the difference lead uh like if it is equal to the current one if it is then we can add it add so one two will add then we'll go to three we'll add that um we'll uh take this and add so 2 three will take and similarly 43 so that will reduce our time complexity to basically n um so where are we so we don't have to do this calculation again um so yeah so for let I equal to 1 because we'll always have two elements and R do length I ++ what we'll do length I ++ what we'll do length I ++ what we'll do is I will simply check if R of I -1 + Min diff equal = to equals to R of -1 + Min diff equal = to equals to R of -1 + Min diff equal = to equals to R of I if yes then I would like to add that pair to my answer which is R of I -1 comma R of I -1 comma R of I -1 comma R of I so if I do that it should be quicker let's see if our yeah this is getting fast I hope it get so the only yeah it get it passed but it was too poor for a solution so uh if I sort this what is the need of me going through check every pair so all I can do is uh take one uh the same thing and Min is equal to number dot uh sorry uh let's calculate first let current diff is equal to math.abs math.abs math.abs um R of I -1 minus r of I -1 minus r of I -1 minus r of I so let's find out what is the minimum current diff or main diff so that will I guess yeah okay that reduces the complexity okay yeah it reduces the complexity hell a lot so our mean uh our time complexity for this would be and login and yeah that's what it is okay guys um thank you so much I was um thank you so much for watching I was able to optimize this on the fly so time complexity of this would be uh in login for the sorting and this is just or and linear time that we are doing a space complexity is nothing because we are we don't consider the result for the space so that's it thanks for
Minimum Absolute Difference
remove-interval
Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows * `a, b` are from `arr` * `a < b` * `b - a` equals to the minimum absolute difference of any two elements in `arr` **Example 1:** **Input:** arr = \[4,2,1,3\] **Output:** \[\[1,2\],\[2,3\],\[3,4\]\] **Explanation:** The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. **Example 2:** **Input:** arr = \[1,3,6,10,15\] **Output:** \[\[1,3\]\] **Example 3:** **Input:** arr = \[3,8,-10,23,19,-4,-14,27\] **Output:** \[\[-14,-10\],\[19,23\],\[23,27\]\] **Constraints:** * `2 <= arr.length <= 105` * `-106 <= arr[i] <= 106`
Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals.
Array
Medium
null
67
hey everyone welcome back to another video uh i'm jotander and i do lead quote questions on youtube so be sure to check out my channel if you're into that stuff right so today we'll be looking at this problem that is called add binary so given two binary strings you have to return their sum in the form of another binary string and they've told us that both the inputs will be non-empty will be non-empty will be non-empty right so binary is just another number system we usually use decimal number system we can use binary number systems which is actually the number system that is used inside computers right so any number that we have in decimal we can represent as that as a binary number as well so binary number system only consists of two kinds of digits which are zeros and ones if you know how numbers work you know that each position in a number each digit position in a number represents a certain value so what is that value for instance when we have a number let's say 237 each of these places is a power of 10 so what i mean by that is i'll just add some spaces here so what that means is that zeroth position or the least significant position represents a power of zero the first digit or the first position represents a power of one and the most significant position in this number represents a power of two so you start off from zero and as you move towards the left hand side you keep incrementing those powers so the first position represents a power of 0 this is a power of 1 and then you have a power of 2 and so on if you have more digits so how do you actually get the value for this number it's pretty easy to see that the number equals to 37 but what does that actually mean this number is computed in the following manner so you the first number is a power of 2 and this is a decimal number system so 10 to the power 2 multiplied by uh 2 right so this 2 comes from this number that is the most significant digit this two comes from this power right so this is the first number that we have right so let's just put that in the bracket plus we get this three so the power is one so we write this as 10 to the power 1 multiplied by 3 plus we have the least significant digit which is 7 so and the power is 0 so we write 10 to the power 0 multiplied by 7. so this just equals to 200 plus 30 plus 7 so we get the sum as 237 so this is how decimal digits are represented in a similar manner we have binary digits so let's say we have a number one zero or let's say one for as a matter of fact this will be represented in powers of two because it's a binary system binary just means two right so you might have taken this in the computers in your computer science classes and all and you might already know how binary edition works so you can actually skip forward to the coding part if you understand all of this right so yeah i have time stamps down in the description so you can just skip forward to the part that you want all right so how do we calculate the value for binary numbers let's say a binary number that we have is represented as three ones one so how we'll calculate this value is the way we calculate decimal places we'll do this in the same manner but replace the 10 with the two so the most significant position will be represented as 2 to the power 2 multiplied by 1 plus 2 to the power 1 multiplied by 1 again plus 2 to the power let's say 2 to the power 0 multiplied by 1 or if this was in fact 0 we would have written something like this right so this is how you calculate the value so this equals 4 plus 2 plus 0 so this number represents 6 right so in decimal form this number will represent 6 in your usual number system so how you write 6 in binary you just write 1 0 right so this is how binary system works so let's see an example here the first example that they've given us is one plus one so one represents three and one represents one so three plus one equals four so how do you represent four in binary form you require three digits as you already saw and you represent that as one zero because one zero will be written as two to the power two plus zero so that equals four right so this is how you work with binary numbers and as you might have noticed we start work the way we did in elementary school like the elementary school mathematics if you just go back to that time uh you always start off with adding these numbers from their least significant position so if you have one and you want to add a one to it you add the least significant digits first right so you add these two digits first what you get by adding two ones is two right but in that binary form you represent that as one zero so you get one zero you retain the least significant digit but you take the rest of the number as a carry so you remove the carry and you write that as a carry to the next digit right to the most significant digit in this example and when you add them up you get another two you represent two as one zero so again that's what you do you just write one zero here and this is your result so how will you work this out in code right so how will how we'll start off is we'll just initialize a string and we'll call that res we'll define two pointers that will define which element we are looking at or which digit we are looking at in each of these numbers and we start off at the rightmost position at the least significant digit as i just explained so we'll start with i equal to a dot size minus one and j equal to b dot size minus one we'll also take keep a variable for the sum and the carry so we'll say in sum and carry will be initialized to 0 right so now we'll start off with the while loop and we'll start adding these numbers from each of these indices so we'll say while i is greater than zero uh greater than equal to zero or j is greater than equal to zero we use an or here because we want to traverse till both of these num these numbers are finished traversing right because we want to keep going until each of these numbers is not finished adding right we don't want to stop midway when one of them stops so the first thing that we do is uh initialize the sum as the carry so we'll just write sum equal to carry because we're starting off adding a new digit so we initialize that with carry so if the carry was one the sum is initialized at one if the carry was zero the sum is initialized at zero right now we'll start adding these digits one by one so if i is greater than equal to 0 which means that if string a is not yet traversed completely what we'll do is we'll just do sum plus equals to a of i minus 0 right we do this minus 0 to convert the character value because these are characters to convert a character into an integer into the corresponding integer you simply subtract 0 from it so we just do that here so this will simply mean so if this was a one in character form subtracting a zero in character form from it will simply make it equal to the actual integer one right so just that's just a small trick that we use right so once you've done that you'll do the same thing for j as well or for the string b as well so if j is greater than equal to zero that means if string b is still left to be traversed what you'll just do is you'll just add that to the sum that digit to the sum so you'll just do b of j minus 0 again so this is again the integer value of that corresponding digit that we are traversing so once you've done that all you need to do is append this sum that you got to the result now how do you do that you don't directly add the sum there because it's all fine when you have the sum as z1 or if you have the sum as 0 you can directly append that but if the sum is 2 because let's say you added the numbers one plus one the sum will be two but in binary form this is represented as one zero so the sum or the number that number at the current position will be zero right what we want at the current position in the result is a zero so what we do is we simply add the mod of the number with the two so if we have two here we simply mod that with two because we are using a binary form so if we mod that by two so if you do a two mod two you get zero right and similarly if we were adding let's say one and zero and we had one here so one mod two would be equal to one itself so we'll be adding one in case we had zero here we'll be doing a zero mod two and we'll be having zero right so the number that we are currently appending to our result is simply the mod of the sum number with two so what we'll do is we'll write res plus equal to two string because we need to convert it to it into a string first so we'll do sum mod two right now we have to initialize the carry as well so we write carry equal to and the carry will be equal to the sum divided by 2 and why is that so because let's say uh let's just remove this example completely if we had one plus 1 we got 2 right in decimal form so 2 is represented as 1 0 in binary so the carry should be 1 so you notice that if you divide this sum by 2 because we are using binary form so if you divide the sum by 2 you do get 1 which is equal to the carry and in case you had 1 plus 0 you would have gotten 0 as a result which will be the carry in the case when you had no carry right when you had one plus zero you represent that by one so the carry will be zero right so in these cases you just uh divide this sum by two so the carry becomes sum by two right so if you have a carry the sum by sum divided by 2 becomes 2 by 2 which is equal to 1 so the carry becomes 1 in those cases and if you have no carry the carry simply stays as 0 right finally all that you need to do is simply decrement i and j so i minus and j minus that's because once you add these digits you need to move to the left and add the next corresponding digits right so this is just the while loop now you just need to check in case there was a carry at the last position so in this example itself you see when you add the last two ones you get zero at the current position and one as a carry then you add that carry carried one and this one of the most significant position of a you get another carry which is one and the current position becomes zero so you get another carry at the end which adds a final digit to this entire result so all you need to do is write if carry is not equal to zero which means that if a final carry was still left you will simply do a res plus equal to one right but now you realize that the whole while that we've been building this number we've been doing res plus so initially we added zero then we added zero again then we added one in this example right because when you added one you got a zero as the sum so you added zero then you move to the next digit you initialize that with the carry was one so you add these two numbers you again get one zero you put the sum as zero again and finally when you come out of this while loop you see that the carry is not zero and you add a one so this number gets built in the reverse form right it gets built in the reversed order so what you do is you just reverse this number to get the final answer so what you'll do is you will just reverse this so you just use the built in reverse method begin and res dot n so that we reverse the entire string and simply return this result back so we'll submit this and we get the correct answer eight milliseconds perfect so this is how you solve this problem and i hope you enjoyed this video if you like this video hit the like button and subscribe to my channel for more content and i will see you in the next one you
Add Binary
add-binary
Given two binary strings `a` and `b`, return _their sum as a binary string_. **Example 1:** **Input:** a = "11", b = "1" **Output:** "100" **Example 2:** **Input:** a = "1010", b = "1011" **Output:** "10101" **Constraints:** * `1 <= a.length, b.length <= 104` * `a` and `b` consist only of `'0'` or `'1'` characters. * Each string does not contain leading zeros except for the zero itself.
null
Math,String,Bit Manipulation,Simulation
Easy
2,43,66,1031
380
Hello everyone welcome to my channel so today we are going to start a new play which is question number one of playlist with data set design it is ok lead code number 380 is a medium level question madam pretty sir I will make it super like this When you reach the end of this question, okay, this is the name of the question, then I will understand what the question is trying to tell you, before that, let's see which companies have asked Amazon, Twitter, Bloomberg, Microsoft, Facebook, Uber, Google, okay, the question is good. And I will design in general and remove and get random gar man lo, it is okay, these three operations should be done in open everest time, so here we have given an input, it has named that which takes the random set in our data set, okay. After that insert you, if you are not there then you have added it. Okay, any number is okay. So here van and any random number will be added. Here you are okay. Now let's remove on remove van. To remove is present in it, yes is present then we have removed it, hence true is returned here, if not then we return first, after that if we say then there is no need to insert it, hence see false, the same number has been returned for the return. Average time is fine, so now let's see how to solve it, look at this, I know that the first approach that comes in our man is victory that we will take a vector, okay, we will keep inserting in it like man take now van. It is okay, it is present, it is not there, you have to do it directly, just ask, now if you want to remove it in the vector, then before removing, you have to check whether that element is there or not. Now you can insert that element in this vector. If you search, you will not be found, but you will have to search, so tell me the number. When does oven access happen in vector, when you have index, here we do not have index, here it is directly saying, look, search for you first. Will it not be included in it, I will write it down, we do not have an index, you do not have an index, that is why what I am saying is that I take this one of yours which has three numbers like this, okay 012, what is its size, so what? Random, what number can come, either zero can come, or you can come, okay, any number can come, any one of these three can come, if we send it the number of the index, then also see Get Random. If you go, this is our oven, here is the removal process. Why was there any problem in the removal because you did not have the index, where that number is, you also did not know, I gave you the direct number and said brother, remove it and see, now how will you remove it in vector. This trade will have to be done, okay now I have found it, now will you shift it, this is also a tension, that too will take a lot of time, so let's see, if we do it in vector, then we are doing the insertions in this fine oven. Okay, but our removal seems to be fine and why does it seem to be okay? What was missing? We did not have an index. There was no index of numbers. So, whatever was missing, we can fill it somewhere. Okay, we will keep the vector in which. What will we keep that number at which index is the correct combination? Look, I am saying this again and again, you should know how we came to vector and map but there was a problem in removal. Okay, so I am happy with vector. So there was a problem in removal, now why was there a problem in removal because there was no index, how to find the element directly, it took oven time even to find the element, so we need direct access, we need index, so if we store the index somewhere, then where is the index? You can start by making noise in the map. In this way the instructions will help you a lot. You should know the complete path that you started from here, you went here and then here it is okay, so let's see how we can solve the vector of map. Okay, so let's see this question here, this was our input, okay here is the input, what's in the input, insert one remove, insert one, get random remove, okay, this is the first important one, now let's see how we will solve it, okay now. Look, we have taken the vector and map here, okay, now we have this, the size of the vector is zero, it is clear till here, okay, now let's come to insert van, ok in insert van, so first we should have checked that brother van. Which is there, have we not inserted it before? Okay, Van, we have never inserted it before. This is the first time that we have made it, so we will check it in the map. Is Van there in the map ? ? ? Okay, let's add the van to the vector. Now look, we will remove the N vector and will return true in the insert van. Because van was not there, we have already inserted it, so we will return true. Now let's insert Tu again. First of all, let's see in the map whether Tu is there in the map or not, then it means you are new. Let's insert 2. Okay, I inserted Tu in the vector first. It's okay by pushing back. And in the map, what is the index of tu and 2, brother, what is the size of the vector right now, it is two, neither is it 2 - 1, this van is correct, it is also neither is it 2 - 1, this van is correct, it is also neither is it 2 - 1, this van is correct, it is also correct and we have returned true because we have inserted the element. Get random combination is very simple, what I told you, we will get an index, how will we get the random index, the size of the random percentile vector, what is the size of the vector, what will come if you are right, then whatever index goes to A, we will send it to zero, okay simple. The alliance has become simple, it's quite ok, our alliance is done, now let's come to the remove van, okay, remove the van, first pay attention here, where do we have to remove the van, where is MP of van, so what is the index of mine, okay, so remove the van. If we do, then we will have to bring someone in place of the van. If we have to bring someone in place of the van, then what do I do? Let's remove one less. If we have to remove the van, then we send the van to the last. Send the van to the very last of the vector. Let's give and the last element of the vector will be brought to the van and what I am saying is that send the van to the last, okay and the last element is stored first, okay, the last element is this element in it. Stored, okay, now in the back of the vector, which is the back of the vector, we have added van there in the last element, meaning vector dot back which is the last element, we have added the value that we have to delete, we have added van and what else. You see, here it is tu, here van has become okay, it was zero, we will have to put the last element there, this tu, we have made noise, so what will we do here, which is the vector of which is the index where van was earlier. Now we will add the last element there, because instead of the last element we have added van, so A will go here, okay and what will happen after 2 hours, what will happen to the MP of the last element, so what did we do now that we had to remove it. Raced the van and MP which was the last element, first you can do anything, you have got the index, okay, so we removed the van, okay, now let's come, Dada, okay, get random, do you understand? It is simple, you have to do so much in the removal, what did you have to do in the removal, first check whether that element is there or not in the map, if it is not there then return false because you cannot remove it, that element does not exist, it is our data. It is fine in the structure and if it is then you just do not have to do anything, just send the element to the last element which you have to remove and send the last one to the place where the element was which you have to remove which I have done. Here we have put it in the variable and in the last element we have given the element which is to be removed. Look here, where I had the element which has to be removed, there we have given the last element. In a way, remember in the last we had given the group. The one which we have to remove, then we removed it from the vector and also removed it from the map. It is necessary to remove it from the map also, isn't it? And lastly, the element which we have brought in the index of the vector, this is the empty IDS that we get. Also, we will have to update the index because we are swapping it, so we have updated it here, okay, so look, friend, if the story comes to your mind, then you will immediately put it in the code, okay then let's go. Let's code it exactly like the story was narrated just now. Okay, so the question will be understood. What was said is that we are going to use two things, we will factor one and map it, okay then I would have taken it. Okay MP, now let's come to the shirt, so what did I say first check that element is not already present, MP dot find that value, if not equal, MB is rotten, that means it is present. If it is in the map, then brother, do return false. Why insult? It is already present in your data section. Okay, and if it is not so, then let's insert it. So, what should we insert first? Let's put it in the vector first. Welcome to Dal. Given the vector and its index in the map, we had to know the map of value, what will be the index of the value, maintain the variable of the size of the vector but I think this is also fine vectored size -1 okay and let's this is also fine vectored size -1 okay and let's this is also fine vectored size -1 okay and let's start return because we have element Inserted, okay, now let's come to Get Random, we will come last in removal. Okay, Get Random was simple. An index comes out. The random index comes out. Okay, how does the random percentile vector come out? Dot size comes out. Internal, you are the vector and size, right? Random modular N, so what does it give? It will give you the elements from zero to end minus one. Okay, that is our index. It is of the vector, right from zero to N - 1, it vector, right from zero to N - 1, it is the index. This is any element of the random index. Will send it brother, it should be there in your data structure, if it is not there in your map, then return false, then what will you do by deleting it, now if it is low then how will you remove it? First of all, index it and do it. It is okay, the one which you have to remove from which you have to remove the cement, the index of that has been accessed, right? Now what did I say, we will send this element to the last, right? So that it can be easily removed from there, but before that, store the element which is already present in the back of the vector, store it in a variable named last element and bring it from the back in the n vector dot back index and it is fine in the index. Now you will have to change the map also, this element will have to be changed in the map, okay and MP was mapped, you had to map it also because what was missing was you were not getting the index, right, so let's submit it and see. Have great left side I hope you have understood any doubt please resident d comment section I am again repeating it is very important you understand how you come to any approach start from very big then gradually we If we know about retirement, we also need a good index, so we have mapped it, this is what you have to follow, do not watch any such video, do not watch the tutorial in YouTube which directly tells you the solution, you should be able to understand, well, I have come to this solution. How what was missing due to which I had to bring the map ok this is very important I hope you like the video see you gas and next video thank you
Insert Delete GetRandom O(1)
insert-delete-getrandom-o1
Implement the `RandomizedSet` class: * `RandomizedSet()` Initializes the `RandomizedSet` object. * `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. * `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. * `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. **Example 1:** **Input** \[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\] \[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\] **Output** \[null, true, false, true, 2, true, false, 2\] **Explanation** RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. **Constraints:** * `-231 <= val <= 231 - 1` * At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`. * There will be **at least one** element in the data structure when `getRandom` is called.
null
Array,Hash Table,Math,Design,Randomized
Medium
381
609
Good WhatsApp Web Large Maximum Volume Unmute Welcome Back Oriental YouTube Video In Today's Video 2019 Pointed End System Deputy Minutes Silence On [ Deputy Minutes Silence On [ Deputy Minutes Silence On Governor List Of Parts Of The Train For Including Directory Papad All Files Which Contains Industry Duplicates 5757 Times After 5 You May Return Answer and Order Subscribe Like and Subscribe Names and Content and Mrs subscribe and subscribe the Channel subscribe Kare Mein Ek Ansh Directory Has Multiple Files For Example The Verses That Were Given Its Roots Like Share And Industry Of 251 Dot Ac Dot S Seen And His Followers for all the best friends and after the name of the file behave something interested in this context that place and not where should they need to take all the best results into consideration subscribe The Channel subscribe to the Page if you liked The Video then subscribe to the Page That Asirgarh Keeps Similarly This File 120 Excellent PHP Web Content ABCD Any Present End Second Wait Until Research Active Latest How Can Approach To The Problem Solution For Latest Thinking Subscribe To Generate subscribe and subscribe the File Path to the Best of the Best Element Idli The Video then subscribe to the Page Aadhaar Card PIN Into a Spirit to Compare Multiple Files for It So They Required to Lift Loot Setting Element of Contents for Doing the Elements and Subscribe Button Answer Final Chapter Note Subscribe to the channel and press Elements And Didn't Want To Avoid Subscribe The Amazing Subscribe Quartz Vrat Ki Hai Win The Content Of The File Ok Software Reached That Bollywood Subscribe Button Data Subscribe Elements Of Obscurism Subscribe Thank You Be Complete But Attention Spot Reader Will Just Read Hotspot Pyaar-Vyaar Generated And Hotspot Pyaar-Vyaar Generated And Hotspot Pyaar-Vyaar Generated And Avoiding Checkpoint Element subscribe our Channel and subscribe the Channel Note Required And Subscribe Data And The Volume Subscribe And The Best Of All The Spot Width Of All The Best Friend For U Half Hour Reach Now Blank Space And It Depend Of The Political Are Doing To The Point And Finally E Woold In Now Kautsa Lash Bigg Boss Forward Slice Not Present In The Delete Or Only Avatar Just Giving Speech At Least Now What We Do We Need To Take Source File Name And Entered Into And Mom's Sweater 200 Cr Create Into Variables And File Name And Form Data And Now They Will Reach This Place Was Clear Okay So After 10 PM Will Reach And The Richest Subscribe New 2018 Quarters Portion It * And Map Ok So Even Middle Age Not Represent A New Chapter Complete 56001 Subscribe Now To And Subscribe The Channel Please Subscribe And Subscribe The Do Points 138 A Plus 98.3 Pass And After Submission Sorry A Plus 98.3 Pass And After Submission Sorry A Plus 98.3 Pass And After Submission Sorry For This Video Guys Tubelight Video of What You Did Not Understand and Comment Willow Polling Will Also Present and Destruction of Freedom of Speech Content subscribe to the Channel and dont see this Server and Tool in Next Video Bye-Bye-Bye-Bye Ajay Ko [ Ajay Ko [ Ajay Ko [ Praise] Praise] Praise] Ajay Ko Kar two
Find Duplicate File in System
find-duplicate-file-in-system
Given a list `paths` of directory info, including the directory path, and all the files with contents in this directory, return _all the duplicate files in the file system in terms of their paths_. You may return the answer in **any order**. A group of duplicate files consists of at least two files that have the same content. A single directory info string in the input list has the following format: * `"root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content) "` It means there are `n` files `(f1.txt, f2.txt ... fn.txt)` with content `(f1_content, f2_content ... fn_content)` respectively in the directory "`root/d1/d2/.../dm "`. Note that `n >= 1` and `m >= 0`. If `m = 0`, it means the directory is just the root directory. The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format: * `"directory_path/file_name.txt "` **Example 1:** **Input:** paths = \["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"\] **Output:** \[\["root/a/2.txt","root/c/d/4.txt","root/4.txt"\],\["root/a/1.txt","root/c/3.txt"\]\] **Example 2:** **Input:** paths = \["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"\] **Output:** \[\["root/a/2.txt","root/c/d/4.txt"\],\["root/a/1.txt","root/c/3.txt"\]\] **Constraints:** * `1 <= paths.length <= 2 * 104` * `1 <= paths[i].length <= 3000` * `1 <= sum(paths[i].length) <= 5 * 105` * `paths[i]` consist of English letters, digits, `'/'`, `'.'`, `'('`, `')'`, and `' '`. * You may assume no files or directories share the same name in the same directory. * You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info. **Follow up:** * Imagine you are given a real file system, how will you search files? DFS or BFS? * If the file content is very large (GB level), how will you modify your solution? * If you can only read the file by 1kb each time, how will you modify your solution? * What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize? * How to make sure the duplicated files you find are not false positive?
null
Array,Hash Table,String
Medium
2079
1,444
um hello so today we are going to do this problem which is part of lead code daily challenge number of ways of cutting a pizza so what this problem says is we get a rectangular pizza that is represented by Rose by matrix um Rose by Karma of course um and this Matrix has a which will represent an apple and it has a DOT which will represent an empty cell and we get also an integer k and what we are doing in this problem is cutting the pizza into K pieces using K minus one Cuts right because to cut into three pieces you just need two cuts right so that's sort of the idea here now for each cut you have only two possibilities for the directions you can either do it vertically or horizontally in this rectangular Pizza um it's a little bit weird that the pizza is rectangular but yeah that's the problem um then you choose also where there it's a pizza that has our ports they should have just chosen cake but yeah I digress um so you can cut either vertically or horizontally then you choose a cut position at the cell boundary and cut the pizza into two pieces right so if you cut it vertically here the problem is tells us to give the left part of the pizza to a person so that and we are left with the remaining parts to divide further into further Cuts until we do all K minus one cuts now if you cut horizontally then you give the upper part of the pizza to a person right and then we give the last piece of course to the last person now we have the problem asks us to determine the number of ways we can cut the pizza such that each piece that we give to each person has at least one apple right we can't give one person a piece that doesn't have apples on it which means basically we can't cut in a way where the parts we are removing doesn't contain an apple right so that's the first that's the constraint and what we want is the number of different ways we can cut it so that's the idea here now of course here they are asking us to use modulo we can use that but if we take a look at the first example here we get um a three by three rectangular Pizza like this and so one way we can divide it is cut here horizontally and so we give the first person this portion here right and we are left with the rest and so for the rest we can cut it for example vertically we'll give that person this so you can see here it has an apple here it has an Apple so we are still within our constraint and now we did K here is equal to 3 which means we need to do only two cuts and so the last person gets this piece and we did only two cuts um and we cut into cut it into three pieces and we did two cuts right so within our boundaries the other option again cut horizontally but when we cut vertically cut from this side so the second person get a different slice and the last person gets the slice and still each one of them has an Apple so should be good the last different way we can do this is cut vertically first instead of horizontally right so this person gets an apple two apples here so we are within our constraint and then we cut again vertically right so the second person get this and then the last person gets this and each has an apple on it okay so these are the only three ways where we have valid configurations notice we can't actually do this cut right because if we do this cut then this person gets the apples but what's remaining doesn't contain apples so the last person doesn't get an Apple so that's not a valid way to cut the pizza okay so that's the explanation of the problem now if we look at the constraint we have only up to 50. so 50 by 50 is the max and K is only up to ten so this tells us that the constraints are not too big so some sort of a Brute Force solution should work um yeah so that's pretty much the explanation of the problem now let's see how we can solve it um okay so how do we tackle this so the first there are a couple of observations we can just think about while playing with the problem right so the first one is that the problem says so here I'm going to be representing a with apple with a and this is the pizza so the problem says that if we take if Arc if we cut a horizontally let's say this is the pizza into cut horizontally so something like this then we give the person this top piece and then the remaining is the bottom piece right and if we cut vertically so something like this right then we give the person will give it the left part and what's remaining is the right portion so this is what's remaining here okay so what's common between these two you may notice right what's coming is that the bottom right portion is stays the same right so this is basically the number of rows minus one columns minus one this is the coordinates of this one and the usual way to define a rectangle um in a matrix or a portion of a matrix you can Define it by just the top left corner right by your top left corner and then your right bottom right corner right so here the for what's left for us to divide further right so we will need to divide this one further right so what's left um is going to be always still having this at the bottom right corner but the top left corner changes so for example in this case let's say we cut here and let's call this maybe uh I right because it's a row so let's call this row just the one before the last one in the cut let's call it I so then here it's going and this is um and this is of course going to be what row it's going to be row I plus 1 because the next one and the column is going to be column zero in this case right and here let's call this cut at J then this is J plus 1 here so J plus 1 and what's the row is row zero right okay but here zero right once we this here just represents the actually the um the column from the top left from the before recursion call because remember we it's not always going to be zero once we cut vertically it changes right it's going to be J plus one so this is just the previous top left column so let's say the top left is always so that we don't we are not stuck with zero let's define it as r1c1 top left so if so that it works when we occurs so here this is going to be C1 right this is because of the same column and the last quality here R1 so this is going to be R1 J Plus 1. okay and so this one stays fixed but this one also we can obtain right so that's the first observation here now the second thing to notice is that we don't know which one is better we don't know if it's better to cut horizontally we don't know if it's better to cut vertically we don't know at which position it's better to cut right we don't know um and so when we don't know let's just try all of them and like intuitively it doesn't seem like there is an easy way to find the optimal way to cut and so since we don't know and the cons the constraint of the problem says the rows and columns are up to 50 and K is up to 10. which is not a big number so if we can try all of them right and so let's just try all of them which means basically each time we'll try to cut horizontally on all possible places and then we will try to cut vertically also on all possible places what does that mean so that means let's say if this is like from zero to five so that means we'll try to cut out row 0 here which means basically we give the first row to the person and then we have the remaining part and then if that doesn't work we try to cut at one we try to cut a two all the way until the last place we can cut which is R minus 2 right because we have to leave this one to the last person um yeah and then same thing vertically we do the same thing we cut at zero we cut at one at two all the way to the engine so we try all of them and then if we are able to do all the K the required cuts which are K minus one cuts right so that's the first constraint so what are other constraints that we needed for our Cuts so the first one is that we need to do K minus one cuts the second one is that each cut right needs to contain an that we give to a person needs to contain an a which is an apple basically so we will do we'll try all of them but we will we won't try if when we cut we won't give the other person n a so if we are not able to give that person any we want cut so we'll just do this but we'll try all of them okay so that's the sort of a couple of observations there that will help us solve it now the second thing to ask is we'll try all of them will recurse of course what would be the state of our recursion what do we need to um what do we need to pass to our recursion well the only thing we need is since this one is fixed the bottom right corner is fixed we just need to pass each time the top left corner that's the only thing we need to pass right and so the state of our function is going to be something like um let's call it maybe count ways it's going to be just the coordinates of the top left which are so top left coordinates here which are going to be R1 and C1 and of course the remaining number of cuts we need to do right because we need to know we can cut more than K minus 1 and so we need to know when we reach 0 and that will be by the way our base case right so that's the first thing now what is our base case we definitely know that if Cuts is equal to zero we should stop right because we already did all the cuts the other case is if the remaining portion let's say we did cut somewhere here and the remaining portion doesn't contain an a well there is no use in proceeding because we won't be able to do any valid cut right and so that means basically if we end up with what's left doesn't contain an a that means we can't this is not a valid way to cut the pizza so we stop and we return zero because it's not a valid way and so what we can do here is just to check if right if not Apple in our in Pizza the remaining pizza right we should return zero right now how do we solve this function what section of the pizza to look at well we know the top left is this one is R1 and C1 so we'll give it to the top left corner and then we need to give it also the bottom right corner so we need to give it where to start and where to stop and as we said the bottom right is this one and so we just give it that okay so return zero now if we get here in this case now that means there is an apple because we didn't enter this Loop so we can just return one because that means there is a remaining Apple in the last cut which and since we reached here it means previous cuts all of them had an apple on them and so this means this is a valid cut so we'll return one all right okay so now these are our base cases we should be good now the second step we need to do we need to have the count here that counts the number of ways from this state to cut Pizza in different ways and now we try all of them so here we try to cut horizontally and then we try to cut vertically and then we have another way where we cut vertically right okay so now for cutting horizontally well we just try all possibilities right so we just have I which is the row we will cut at and we need to try all of them but when we are here by try all of them here so in on this portion by try all of them it means starting from here right and then for the horizontal part when we are cursing on this portion right trying all of them means starting from here right not from the beginning starting from just the sub Matrix that we have we try to cut here so that's the idea here and so that means we start from only the top left right row which is R1 but it needs to be plus one because we can't right here right when we are left with this submage sub um yes sub Matrix or whatever you want to call it we can't cut actually here right we have to cut because we need to give that person something right something that contains an apple right and so that's where we have R1 plus 1 and we need to um when do we need to stop well we need to try all of them all the possible Cuts all the way to the end here and so that's why we need to do here to up to um R minus r right um cool okay so up to R and now for each of them we just try which means we added to count the number of ways and then we try recurse which is count of ways now what is the new um the new coordinates for the top left well that's exactly what we said here the new coordinates are I plus one uh sorry not a i plus 1 if we had um so we have two choices if we wanna I to be the one we give to the other person we can do R like this but if it's want to be the one we use ours the one we left then this is going to be I right so let's say if I is actually here this is going to be I right and here if J is actually here then this is going to be J and it depends on when you where you want to represent inj both work in the same way right and so here that means it's I and as we said the column is going to be C1 stays the same so it's C1 and then we just did a cut so this Cuts now it's Cuts minus one now there is one condition which is we can't cut if well we can't cut here right if this portion doesn't contain an a because that means we'll give someone a piece of the pizza that doesn't contain an apple but that's while it's out constraint here so we have to check make sure that what we are giving to that person contains an apple which means we have to check that this portion here contains an apple and so how do we do that well we already have our function Apple in pizza so let's just call that function and so what we want to do here is only if the portion we are giving so the top left one the top one contains an Apple so Apple in pizza for what is the top left coordinates well the top left coordinates is just this portion here which is the sub Matrix R1 and C1 and what are the bottom left right so in this case let's do a new one so we are here r1c1 and let's say we cut here what is the so this is the top left it's r1c1 what's the bottom left let's say we cut here and this is I so this is where we cut so starting from I here and so this is I minus one and so what this says and this is column minus one and this is R minus one and so what tell what this tells us is that this is basically just I minus 1. C minus 1. right and so that's the last piece here so I minus one C minus 1. basically we are making sure that what we are giving to the person this portion here actually contains an a because it doesn't contain Z and a so if we had that here then this is not a valid cut we can do this cut we have to cut to here maybe right and so we have to check that it contains an a so that's what we are doing here and then now for the vertically it's the same concept just we need to do it in the vertical order and so instead of I here we are going to do 4J so it's going to be 4J in the range of now what's the this one it's just C1 plus one the same way we for the same way we did the horizontally we tried this one vertically we'll try this one right and so that starts from C1 plus one of course because we do it here right and so that's exactly what we are going to do here so C plus one and then we stop the same way we stop on the last column with python this is going to be C minus one and then we'll do the same check we did for we did here right so we want to check if Apple in pizza right we want to check now what should we pass here so this is the now let's try it with this one so let's just delete this and see what it looks like so this is going to be R1 C1 right and this is R minus 1 C minus 1. so this is C minus 1 and this is R minus 1. and so when we cut vertically let's say for example here let's call this J at this position then this is J minus 1. okay so how do we represent this portion here well it's R1 C1 that's the top left what's the bottom right has the row R minus one and has the column J minus 1. right just before the cut um so it's then let's just write that exactly like that so that's going to be starting top left is r1c1 but the bottom right is where we cut so it's um J minus 1 R minus 1 and J minus 1 right that's exactly what we said here it's R minus 1 and J minus 1. and so that's if this is the case now we can do the proceed to the cut and do the cut and proceed to the to recurs on the remaining portion of the pizza and so we do count plus count weighs now what do your curse on again similarly here we need to recurse on this remaining portion now how do we Define this remaining portion we know it's bottom right what is its top left well it's top left is just we know the column is G what's the row well row is just the same row as before so R1 right and so it's just going to be R1 G right and then the bottom right is the same right so that's why we said here R1 G and the bottom right is R minus one C minus 1. okay and that's pretty much it and then at the end of for this function call we're going to return the overall count that we just calculated with all possibilities and remember here we return one only if we get down to we do all the cuts and all of them all the cuts contained an apple and so here we return that count okay so we just tried all of them and we respected the conditions here the constraint that we have which is we need to do exactly K minus one cuts right and then we need each cut to give the person a um and then the rest is just manipulating coordinates right now the only thing we didn't do is checking if Apple in pizza but this is easy because we have the top left we have the bottom right so we can just Traverse the entire sub Matrix and check if any of the values is a will return true and if we do the entire uh sub Matrix and we didn't find any a values would return false right that should be pretty easy to do um yeah so that's pretty much the idea here now let's implement it and make sure it passes um okay so let's see how we can just let's write the implementation so the first thing we need is the function that we are recursing on so the top left corner and then the number of cuts remaining and we need our base cases which are if there are no apples in this portion there is no use in trying to cut it because it's not valid it will return zero otherwise if the cuts equal to zero that means the remaining Pizza has an apple and we did all the cuts so we'll return one so this is a valid way to cut so we'll return one because it's one way to cut otherwise we proceed and we try all the possibilities so try to cut horizontally and we try to cut vertically okay where did you saw this in the overview so we shouldn't spend a lot of time on it so um cutting horizontally is just going to be going through all the possible eyes we can cut at and then we check if the pizza are given to that person to the person which is the top um the from the top um contains an apple if it does then we recurse on the remaining portion of the pizza right and then we do we cut vertically as well and the explanation of these values is already in the overview so we don't need to repeat it and then we cut vertically again we'll try all the possible Cuts vertically so we just go through the columns we can cut at and we do the same thing we check if the portion which is the left side of the cut we are given to the person is going to have an apple if it does we are good we can recurse on the right portion and try to get the number of cuts we need right and then at the end we just return count right um yeah and these values are all explained in the overview in the earlier section okay and now we just need to call our recursive function here and launch it right so the first thing is we also need to Define these rows and columns which just represents the number of Frozen and number of columns um and so that's just going to be the number of Frozen number of columns and with the problem also says to use a mod right you can choose to use it here right but the values are so small that we can just use it at the end um and so I'll just um yeah if you want to use it here you can just do something like count Plus and then each time make sure you mod right so that's what we all just do it so and just make sure you mod each time like this um and that should be it and here we should mod as well and we might at the end um and that should be it except so here we call it our recursion we start from the initial top left which is zero and then the bottom right is of course you just throw minus one columns minus one is just the last cell and the problem says we get K we want to cut into K pieces but the number of cuts we need to make are just K minus one so that's why we pass K minus 1 here now the only thing I'll have to do is to Define this apple in sub size in sub pizza so let's just Define it this one should be straightforward we get the top left corner we get the bottom right corner and so we can just go through um the rows and columns in these boundaries right so that should be just two for Loops for the coordinates I and J so the I is going to be from R1 right to the LA to this from the boundary rows beginning to the end of the end row and same thing for the column and then we check if Pizza um yeah I'm going to call it P instead of pizza just to be easier to write all right so just peel like that so if this cell p i j is a that means there is an A in this sub pizza right so we just return true and then if we try all of them and it's not there we can return false and that's pretty much it so very brute 4C but it should be fine with the constraint we have um let's see what's there is an indent problem here yeah because of this okay so it passes this but one thing to note is that because of the we try all of them we will have some repetitive States and that we if we don't memorize this will get caught multiple times for the same input and it get executed again and so in Python we can use cache if you want to do a hash map you can also use it I will leave that exercise to you can just use these inputs as the key and check if it's in your hash map use the cache if it's not um if it's not just return if it's not just continue your calculation do the calculation right so pretty straightforward there which we don't need to go through it so let's run this let's submit and you can see it passes um one thing to note is that this is not optimal right because each time we are checking so you can actually optimize this using a prefix sum on the pizza Matrix where basically you do a pre-processing step where you mark a the pre-processing step where you mark a the pre-processing step where you mark a the values of a as one right and then you do the prefix sum normally that way it's really easy to check a boundaries that have a top left and uh in the bottom right corner both top left and bottom right corner you can use this to check if the sub Matrix contains sum is bigger than zero if it's because then zero that means there is an a because if it didn't contain a the sum would be zero because a would represent one right so that's one way you can optimize this I want to write it here to make the video short but you can try to write it um yeah so that's pretty much it for this problem please like And subscribe and see you in the next one bye
Number of Ways of Cutting a Pizza
number-of-steps-to-reduce-a-number-to-zero
Given a rectangular pizza represented as a `rows x cols` matrix containing the following characters: `'A'` (an apple) and `'.'` (empty cell) and given the integer `k`. You have to cut the pizza into `k` pieces using `k-1` cuts. For each cut you choose the direction: vertical or horizontal, then you choose a cut position at the cell boundary and cut the pizza into two pieces. If you cut the pizza vertically, give the left part of the pizza to a person. If you cut the pizza horizontally, give the upper part of the pizza to a person. Give the last piece of pizza to the last person. _Return the number of ways of cutting the pizza such that each piece contains **at least** one apple._ Since the answer can be a huge number, return this modulo 10^9 + 7. **Example 1:** **Input:** pizza = \[ "A.. ", "AAA ", "... "\], k = 3 **Output:** 3 **Explanation:** The figure above shows the three ways to cut the pizza. Note that pieces must contain at least one apple. **Example 2:** **Input:** pizza = \[ "A.. ", "AA. ", "... "\], k = 3 **Output:** 1 **Example 3:** **Input:** pizza = \[ "A.. ", "A.. ", "... "\], k = 1 **Output:** 1 **Constraints:** * `1 <= rows, cols <= 50` * `rows == pizza.length` * `cols == pizza[i].length` * `1 <= k <= 10` * `pizza` consists of characters `'A'` and `'.'` only.
Simulate the process to get the final answer.
Math,Bit Manipulation
Easy
1303,2288
199
all right welcome to this video we're gonna be solving Miko prom 199 binary tree right side view so they give you a binary tree I like what the directions say they say imagine you're a person staying to the right of this tree and you're looking sideways left what notes would you see you would see just the 1 the 3 and the 4 note right because these nodes would block the view of this 2 and 5 note so you should turn the output of 1 3 4 now this problem seems deceptively easy my initial approach was oh just keep traversing passing each nodes right child and then appending the current value of the node as you traverse down the right child of each node into a result array and I'll give you the result but what the direction just don't show is what happens if this 3 node does not have a right child and the 4 is on the left-hand side of 3 so 4 the 4 is on the left-hand side of 3 so 4 the 4 is on the left-hand side of 3 so 4 is the left child node of 3 then it should still show 1 3 4 because you're on the right-hand side you'll still see on the right-hand side you'll still see on the right-hand side you'll still see that four node if it's the left child of 3 so you only pass down the right children that approach won't work right if this 4 note is on the left-hand side if this 4 note is on the left-hand side if this 4 note is on the left-hand side of 3 so one easy way that I can think of the solve this is used a breadth-first the solve this is used a breadth-first the solve this is used a breadth-first search right breadth-first search goes search right breadth-first search goes search right breadth-first search goes by each level and then for each level you pass the last node of each level to your result right so breadth-first your result right so breadth-first your result right so breadth-first search goes up here passing one bare first search gets 2 and 3 the last node of here is 3 then reffered BFS goes down to this last level last node here is a 4 and that would work so you can do that there's nothing wrong with it but in JavaScript well with breadth-first JavaScript well with breadth-first JavaScript well with breadth-first search you need a queue and javascript does not come in with built-in queues does not come in with built-in queues does not come in with built-in queues you have to create from scratch and you're too lazy to make a queue from scratch you can simulate queue first-in scratch you can simulate queue first-in scratch you can simulate queue first-in first-out behavior using an array but first-out behavior using an array but first-out behavior using an array but then your time complexity will get messed up so I want to do a slightly different approach and I think it's easier if I type out my approach rather than explain it so let's get started so in my code editor I'll say let res be equal to an empty array right this will be the result it's initially deep we're gonna fill it out and I'm gonna solve this whoops let's uh reset that I'm gonna solve this with helper method recursion so I'll keep my helper recursive function and I'll call it Traverse and it takes in a node and a depth level like I like so this would in my code this will be depth level zero depth level one and depth level two right similar to how a raise they start at zero so we'll our depth then I'll say if no node return right so you don't recursively recall so this is our base case for our recursive function otherwise I would check hey if no res at index of depth then res at index of depth is equal to node dot Val right because each node has a vowel so we only put in one value from each level and this code says if a value for that level has not been put in here yet set it to that value of our current node otherwise I'll say Traverse we're not otherwise but after this we'll say traversed no dot right and then pass in depth plus one because we're going down another level so def plus 1 and then we will also do Traverse node dot left it's really important that in this function right here we Traverse the right child first right because we only put one node value for each level and in our resume each index each position in the in debt in the array excuse me each index position in the array represents one value from each level and what we want to prioritize the right child first right so once this is done I'll say Traverse Roots zero we're sour depth at level zero to match our array indices start at zero right we define the function now let's call it and then once Traverse is called Reza laugh the appropriate results so then I'll say return rez and of course if you like this kind of content be sure like comment subscribe and hit that notification bell to be notified future videos let's make sure our code passes the leet code tests so I'll submit and we're good to go so what is the binary tree right side view complexity analysis time complexity so then because we traverse every node in the tree and space complexity is also oh then because we make use of recursion and the cost stack of all those recursive calls could be a size or length of the binary tree given and again you can do this with a BFS but this is approach I like to do so that should be it for this video
Binary Tree Right Side View
binary-tree-right-side-view
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_. **Example 1:** **Input:** root = \[1,2,3,null,5,null,4\] **Output:** \[1,3,4\] **Example 2:** **Input:** root = \[1,null,3\] **Output:** \[1,3\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
116,545
1,881
hello everyone today is we're going to solve this problem maximum value after insertion on lead code so the problem statement is we have a large integer as a string let's say the integer is one as a string is let's say it's one three four 5 and we have an integer x which is let's say it is 2 in this case and after the insertion i'm going to rename this to s because it's a string and so we want to insert this 2 into the string so we can get the maximum value how can we insert it in this case so if i insert number two at the beginning we're gonna get one two three four five if i insert after one we're gonna get one sorry we've got two one three four five if i insert that here it's going to be one two three four five and uh let's make this uh if we insert it here we're gonna get one and so on one three four two five one three four five two so it is obvious that this is the answer so we didn't even need to go that far so the algorithm is we look we compare we scan from left to right if the current number which is if x is greater than this we just insert it and what if it's a negative if it's negative and in this case we're gonna have like minus one three two so here we need to uh yeah let's i'm gonna make this shorter so we can get to the uh to solve the problem faster so if i uh we cannot insert before d minus so let's say uh we insert here get two one three two let's say this is four so we don't get confused and minus one two three four and minus one three two four minus 1 3 4 2. so obviously this is the maximum here and so in this case we need to compare what one by one and the moment that we see so two is less than two less than three we insert it there so that's a basic approach and now we start coding so first i want to get the size of the string i'm going to capture it into variable n so we can use it later and then uh since we are working with characters i'm gonna and this is an integer i'm gonna convert this uh integer x to a character c so now we can like basically if it's if x is two here it's going to be like a character two so we can compare and then we're gonna check the first and we basically we're looking for the index where to put x and that index is we're gonna call it i we need to start from 0 if s is not negative and otherwise uh i should start from one so there's a very nice trick to do this we can do a comparison if s of zero is equal to minus sign this will return 2 and true converts the integer to 1 and if it's false i is going to be 0. so now if we get we say if i that means if i is true or this is negative in this case this is gays and otherwise here it is positive s is positive we just scan basically while we say while loop while i first of all need to make sure the boundaries i is less than the size of the string and then s of i the current integer is less than current uh less than uh sorry the current integer is less than what we want to insert which we convert it to less than or equal to c then i plus just move on if it's smaller and otherwise do the opposite basically i'm just going to get rid of this comments while i listen in and s of i greater than or equal to c and i plus and at the end so now so far we have the index where we need to insert so we just return of the sub substring from 0 to i plus the character which is x but it's converted to a character and then from i to the rest of the string and yeah basically that's it just going to run this to make sure there's no compile errors or anything so yes we have this working for a negative number now let's try a positive number and now let's run all the sample cases and then we can submit so again here if the first character is equal to minus one minus so this is true this is one we start from one and then i'm going to bring this example again look at here so let's say this is uh minus one two three so or i would start from yeah i'm gonna make a space here just to make it clear and this is i so i is to greater than one yes so move forward this is i is 2 greater sorry is 2 is 3 smaller than 2 no so i is going to be uh this is basically this is the index 0 1 2. so i is going to be 2 and then we're going to end up inserting this here so it's gonna be minus one two three four well i'm gonna remove this and go back to run all sample test cases and just submit and yes we get accepted well thanks for watching and i'll see you guys in the next videos
Maximum Value after Insertion
closest-subsequence-sum
You are given a very large integer `n`, represented as a string,​​​​​​ and an integer digit `x`. The digits in `n` and the digit `x` are in the **inclusive** range `[1, 9]`, and `n` may represent a **negative** number. You want to **maximize** `n`**'s numerical value** by inserting `x` anywhere in the decimal representation of `n`​​​​​​. You **cannot** insert `x` to the left of the negative sign. * For example, if `n = 73` and `x = 6`, it would be best to insert it between `7` and `3`, making `n = 763`. * If `n = -55` and `x = 2`, it would be best to insert it before the first `5`, making `n = -255`. Return _a string representing the **maximum** value of_ `n`_​​​​​​ after the insertion_. **Example 1:** **Input:** n = "99 ", x = 9 **Output:** "999 " **Explanation:** The result is the same regardless of where you insert 9. **Example 2:** **Input:** n = "-13 ", x = 2 **Output:** "-123 " **Explanation:** You can make n one of {-213, -123, -132}, and the largest of those three is -123. **Constraints:** * `1 <= n.length <= 105` * `1 <= x <= 9` * The digits in `n`​​​ are in the range `[1, 9]`. * `n` is a valid representation of an integer. * In the case of a negative `n`,​​​​​​ it will begin with `'-'`.
The naive solution is to check all possible subsequences. This works in O(2^n). Divide the array into two parts of nearly is equal size. Consider all subsets of one part and make a list of all possible subset sums and sort this list. Consider all subsets of the other part, and for each one, let its sum = x, do binary search to get the nearest possible value to goal - x in the first part.
Array,Two Pointers,Dynamic Programming,Bit Manipulation,Bitmask
Hard
2108,2162
398
okay so uh lead code practice time um so two goals in this video the first one is to see how to solve this problem so find the solution and then we are going to do some coding work and the second one is to see how we should behave in a real interview suppose this is something given in a real interview so let's get started let's see all right so facebook has you this question before uh remember the first thing um the first step always is to try to understand the problem if there is anything unclear please bring up the questions to have the interior to clarify and also think about the ash cases at the very beginning so let's see random peak index so given an array of integers with possible duplicates now randomly output the index of a given target number and you can assume that the given target number must exist in the array all right so the size of the array can be very large so solution that uses too much of the extra space will not pass the dodge yeah so it doesn't say that whether the input string sorry the input array could be empty or not so if it is empty i think then i'm not sure what we should return so let's assume that the input array the inputs the input array won't be empty so we don't need to consider that case let's make this assumption so the second one is to see how to solve this problem so after you fully understand the problem uh you know what the ash cases are you clarified everything then it's time for you to find the solution of the for the exists for this um question so for this one i'll say the first solution i could think of is that we could use a hash map we could turn the input array into a hashmap so the key would be the number and the value will be a list of the corresponding indexes of the number so in this one for this solution uh the constructor is going to take 11 and is the length of this the input array and for the peak it is just going to be one which is constant operation um so it says but since this uh this there's no sense that the array can be very large and it doesn't want us to use too much of the extra space then we have some extra concerns about it so remember for this question there is a pretty well known algorithm called random reservoir so it's the general random reservoir is descripted in this way so you have a numbers n numbers and you want to pick k numbers from it uh from numbers randomly and each number there the probability for each number to be chosen is an overk so sorry the probability is k over n so probability uh for a number to be chosen is k over n so and also we need to say that k is smaller or equal to n so the process is like this so first of all you will have an array let's say a rk so you fill the you fill in the ark with the first and first k number is from the array so let's say we have ar which is uh which contains the numbers and we are going to pick k numbers and insert them into ark so we are going to say i from um let's say one to um this is one to k so you're going to say all right so k i is equal to a r and say in this description i just use one based uh index instead of zero based index uh which would be easier for me to just uh describe this uh this the this general garden and then for the rest of the numbers so we have the j is from uh let's just reuse i so i from k plus 1 to n so the so suppose so at this moment we pick a random number j pick j um within uh within one two k plus sorry within one two i randomly so if j is smaller than or equal to k then we just replace uh replace the ar k j where's the card number otherwise you just uh if j is lighter than k we just uh threw it away so this is essentially how the algorithm works so the reason why each number is has the equal probability to be chosen is because suppose um suppose it is a random number j i suppose okay so let's say suppose um ar and let's take ar and j so to see uh the probability for this number to be kept in the final array so if j let's say if j is larger than k so for the first time and the probability for a to be chosen is k over j and the next time um the probability for it to be kept is actually one minus uh so you have one over j plus one of the probability for this number to be replaced and you have one minus this problem one minus one over j plus one's probability for it to be capped so similarly the next round it to be capped is one minus one over j uh plus two so on and so forth until you have one minus one over uh n so you can see that this one or k divided by j and then this would be j over j plus one and similarly this is j plus one over j plus so on and so forth for the last one is n minus 1 over n so you could see that the this j we could just do some uh simple uh calculation to see that the final answer is actually k over n so similarly we can have some uh we can follow similar process to justify that uh if j is smaller or equal decay the probability for it for the number to be kept is also k over n so having said that the run time for the constructor is going to be constant because you don't actually need to do anything and for the pick the runtime is going to be linear to the length of the input array so having said that let's do some coding work on this approach because it's a bit more difficult than the last hashmap solution and also if it's the assumption that we cannot use too much of the extra storage so let's see coding so for coding part we care about speed and also the correctness and also the readability of the code so let's give it a shot so for the solution you're going to find member let's call it uh nums this dot nums is equal to nums all right so that's that finishes uh the constructor so for the next one we are going to pick the numbers so let's see so we are going to just have one numbers which means we are going to pick one number from the numbers so first of all let's see i'll say is equal to zero so for the first time you need to have a all right so actually we need to initialize count as uh as one and the corresponding index let's assume it is equal to minus one so you're going to say okay for i is equal to zero and smaller than nums um or we just use we don't use in we need to use the next best because i actually need to return the index so smaller than the lens plus i this is the index and if um so if target is equal to nums i so that's the time we have found so if it is not equal to this then we just continue so this can save us some indentation and make the code to be more readable then after this it means the target is you it we find the target number so we are going to call okay so actually you can just return uh we can just define random here let's say this is ren so rand is equal new random okay so you're going to say um new yes and um random is equal to let's call it random so let's see code random number is equal to random dot next ins uh where's count so i need to see whether the random exclude or include the number random next okay so saying the jdk next in synaxin return the next so uniformly distributed in value between 0 to the specified value drawn from this random number generator between 0 and okay so it is inclusive if it is inclusive then we need to say conhas equal to zero so if um random num is equal to zero then we are going to set the index as i and finally we are just going to return index so that's pretty much it about the implementation of the random reservoir solution so you have pick targets so first of all initialize the random and also initial we designed the reference of the array to be a private member and also when you call the pickup you first initialize count as zero when indexes minus one so if target is equal to the if not equal then you continue otherwise if it is equal then it generates the render and run a random number between zero to the count so for the first time you're going to for sure to generate random number as zero so and next time uh the probability is two plus one uh for it to replace uh to replace it and uh yeah so on and so forth so we are just following a similar procedure uh a similar procedure for the random reservoir it's a little bit special because we just need to pick one number from the random reservoir so let's um give it to run remember the last step is always to do some testing so testing usually if it is not a runnable platform you will need to go through a simple example explain how this piece of code is going to work and at the same time do some sending check on the code and after you're done with that uh you could um use some say some extra test cases to have good enough test coverage but i would say for this one uh let's simply go through the example first so let's say we take three so first of all count is x equals zero index minus one so the first two integers are not um aren't are we are just going to continue so one all right so i think we find the iphone above we need to plus the count so for the first one the probable we are going to just generally random number from zero to zero so we are going to replace the index and we plus the count for the next time uh count is equal to one you're going to generate a random number between zero and one and then um if it is zero then we replace the index for next time um you're just going to generate random number zero one two and then um yeah so if the random number is zero then we have the index to be replaced so i think overall it looks fine let's give it a shot okay so there's a typo next it so bond must be positive which means the ish okay so the any index should be open i guess yeah so yeah it's pretty it says that uh into value between zero and the specific value okay so the specific value is exclusive i think i uh over just overseeing that i didn't pay attention to that exclusive so let's do a submission for it all right so i think we're good with this uh solution and uh that's it for this coding question if you have any question feel free to leave some comments below and if you liked this video please help subscribe to this channel and i'll see you next time thanks for watching
Random Pick Index
random-pick-index
Given an integer array `nums` with possible **duplicates**, randomly output the index of a given `target` number. You can assume that the given target number must exist in the array. Implement the `Solution` class: * `Solution(int[] nums)` Initializes the object with the array `nums`. * `int pick(int target)` Picks a random index `i` from `nums` where `nums[i] == target`. If there are multiple valid i's, then each index should have an equal probability of returning. **Example 1:** **Input** \[ "Solution ", "pick ", "pick ", "pick "\] \[\[\[1, 2, 3, 3, 3\]\], \[3\], \[1\], \[3\]\] **Output** \[null, 4, 0, 2\] **Explanation** Solution solution = new Solution(\[1, 2, 3, 3, 3\]); solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. solution.pick(1); // It should return 0. Since in the array only nums\[0\] is equal to 1. solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning. **Constraints:** * `1 <= nums.length <= 2 * 104` * `-231 <= nums[i] <= 231 - 1` * `target` is an integer from `nums`. * At most `104` calls will be made to `pick`.
null
Hash Table,Math,Reservoir Sampling,Randomized
Medium
382,894,912
91
hey guys it's all five one here and today we're going to be solving the code ways in this problem we're told that we're mapping every letter to a number so for example here we have a and it's mapped to one B is an app to two and Z is map of 26. so every letter in the alphabet is mapped to its position in the alphabet so pretty straightforward there the part where it gets tricky is that we're told that we're giving a string of numbers and they're asking us to return the amount of ways we can decode it so for example for this one right here we're told that there's two different ways to decode it and that's 1 10 6 11 10 and 6 and we're told that this is not a ballot combination right here because of the zero six here because 0 6 does not equal 6. so that's a small Edge case we're gonna have to take care of in the code but other than that it's pretty straightforward let me show you so here I've written in example s where the strings are one two three two and one and the way I'm going to approach this is by taking a look at each and every string and then the next iteration I'm going to include the next part of the string and so on until we reach the end and for every time we do that we want to calculate how many combinations we have up to this point so for example for one there's only one combination and that is just one for one and two we have two different combinations we could do one and two or we could read it as 12. for one two and three there's three combinations and those would be just all single or we could start with 12 and then three or we could do one and twenty three and as you can see these are all different ways of interpreting the string so now we're going to do one two three and two and here's where we see that it doesn't follow a certain pattern because you can't make a string out of 32 so I'll show you what I mean here you can do one two three two you can do 12 3 2 or you could do 1 23 and 2 and the reason we can't have any more combinations because like I said before we can't make a number out of 32 because that is not correlate to a letter in the alphabet and then for our last number one two three two and one we actually have six combinations and I'm going to write them out here so here are the six different combinations you can do for this string of numbers and here I'm just going to write how many combinations each number can produce so for this first one you can only do one different combination when it's one and two you can have two different combinations one two and three you can do three different combinations one two three and two still only give three combinations and then if you add a one at the end you can have six combinations so what pattern do we see here well I'm sure most of you see it already I'm sure you can see that this six here is the addition between these two different combinations and that for this three here all we have to do is add the previous two indexes and we get the number combinations for this but what about for this three here why couldn't we add three and two well we can see that we couldn't make a double digit number so maybe that can be one of our conditions so what we can say is if we can't make a double digit number just rewrite whatever's in the previous index to the current index since that means we can't make any new combinations but what if our string here was modified so instead of one two three and two it's one two three and zero how many different combinations can we write from this well we know that 30 is not a valid double digit number and 0 is not a valid single digit number so our actual combinations for this would be zero since we can't make any combinations so our two conditions can be if we can't make a double digit number then just copy over the previous indexes value and if we can't make a double digit number and our current number is zero then we don't add our current index either we can just leave it as zero so I'm just going to rewrite all that on a cleaner page so you can see what I'm saying so here I've initialized our results array and in this results array this first spot here is for our base case the reason it sets one is because when we check our first index on the string we want to set this value equal to whatever is here and obviously if you can make a valid combination we want to set it equal to one and I've also filled out all of the other combinations so you can see that if we go to the end of the string our valid combinations would be six and that's true as we saw in our example and here's our pseudo code so the way to read this is if let's say we're at 2 here if we can make a valid double digit number so let's see can we make a valid double digit number using two let's see one and two is that valid yes so what we would want to do in that scenario is that the current result that we're at so we would be at index two we want to set it equal to result at I minus two so not this index here but this index so we will start with a 1 there and now we go to this if statement so if the current number we're looking at is not equal to zero what we want to do is set it to our current result plus our result at the previous index so in this scenario it will be one so we would have one plus one and that would equal two the reason we check if it's not equal to zero is because if you remember from the example if we have a zero then that means we can't really have any new combinations and if we don't have a double digit number that's valid either we expect a zero there so when we initialize our array all of these are going to be set to zero except for the base case so to give you another quick example of why we don't do this condition if we have zero let's look at one two and zero well let's start with one that makes one combination just with one and two we can make two combinations we can have them separate or we can have them together as a 12. and with one two and zero we cannot do this combination here where they're all separate because zero is not mapped to anything so this would be an invalid combination but we can do 1 and 20. and also we couldn't do 12 and 0 for the same reason as above so that would be invalid so we would actually only want just one combination and as you can see here if we can make a double digit number we want to add our result at I minus two so that would be this in a scenario which would be one and that is how many combinations we have here as well so that's true and it checks out our type complexity for this algorithm is going to be o of n the reason for that is because we have to iterate through the whole string and the string is of size n and for space similar thing it would have to be o of n because our result array is going to be size n plus 1 which rounds down to n but actually as you can see if you solved enough of these you'll see that if we only use I minus 2 and I minus 1 we can do it in constant space because we can just store these in variables and update them as we go through the loops so really our space is going to be of one once we implement the code and let me show you how to do that to start we're going to initialize two variables one is going to keep track of our I minus 1 and the other is going to keep track of our I minus two so we're going to have previous one and we're going to set that equal to one and previous two and we're going to set that equal to zero the reason previous one is set to one is because this would be pointing to our base case and if you remember from our example that would be one and previous two would be out of bounds so for now it's just zero from here you want to iterate through the whole string s so we're going to do for I in range of length of s and now we just want to make a new temporary variable I'm just going to call it current and we're going to initialize it to zero for now and now we want to do our if statements so our first one is going to be if we can make a valid digit number then we want to add our I minus 2 to it so how do we write this condition well first we have to make sure that I does not equal 0 because if it does then that means we can't actually make a double digit number to begin with so just taking that out of the way and also now we have to check if our substring at I minus 1 all the way to I plus 1 and all this means is the previous digit and all the way up to our current digit I did I plus 1 because this would be not inclusive so really we would be doing just two digits like that and what do we want to check well we want to check that is less than or equal to 26 because that is our greatest value in our array and that would be Z but it's a string so we want to do like that and then we're going to copy the same thing here we're going to check the previous two numbers and make sure that they're greater than or equal to 10. and from there all we want to do is set our current equal to our previous two now we check if the current number is zero so now we check if it's the string at index I it's not equal to zero then we want to add current plus previous one because that would be our index I minus one if you remember that from our pseudo code and then from here we just want to update our previous one and previous two variables so previous two is going to be updated to previous one because we're moving forward in the array and previous one is going to be updated to whatever our current is and then at the end we can just return our previous one because that would be our Max at the very end and that should work forgot to put an and right here but now it should work so as you can see this code is pretty efficient and now I'll go through the code manually so for this problem I've initialized this array here and even though we're not using it I just want to have it here just for clarification because I know it can be kind of confusing to follow these pointers so let's get started so I've already initialized previous one and previous two over here so we're good there and now we want to iterate through the whole string s and we're going to start with just this string here so our current is going to be set to zero which it already is and now we want to check if we can make a valid double digit number well we're at I equals zero still so we can just skip this condition for this iteration and now all we have to do is check is the current index pointing to a0 no because this is a one so what we want to do is update our current to be equal to current plus previous one and that would be one and we can just set this to one as well since that means that we found one combination and now we just want to update our pointers previous two is going to be equal to previous one so previous two is going to be 1 and previous one is going to be equal to current which they're both already one so we're good there and now we go to the next iteration so now we're looking at two so let's see I does not equal 0 anymore and we can just kind of forget about this condition now since it's never going to apply again and we just want to check if we can make a double digit number so if we take S at the previous index and our current index what number does that make well we can see that makes 12 and that is between 26 and 10 so that would be a valid double digit number so if you want to update our current to be equal to previous two which is already one so we're good there and now we check is the current number we're looking at not equal to zero so let's see we're looking at two and two does not equal zero so what we can do is add current is equal to current plus previous one is one current is one so our current is now going to be two and now we can update our second index here to B2 so that means up to this point we have two different combinations and we know that's true because we can make one and two or we can make 12. and now we want to update our pointers so previous two is going to be equal to previous one and it's already one and previous one is going to be updated to our current so in our previous one is going to be two so now we're going to be looking at our third index which is going to be 2 and now we check can we make a valid double digit number well let's see if we combine the previous index with the current index we can make a 22 and that is between 26 and 10 so we're good there so we can update our current to be equal to previous two and previous two is one so that is updated to that and now we check is the current index equal to zero and we can see that 2 is not equal to zero so this condition checks out and now we can update our current to be current plus previous one so previous one is two and current is one so we want to update this to three because two plus one is three and now we can update our third index here to be three meaning we can make three different combinations and we know that's true because one two three one and twenty three or we could do twelve and three and all three of these are valid and now we want to update our pointers so previous two is going to be equal to previous one which is two and previous one is going to be updated to our current and our current is three so now this is three and now we go to our last iteration so now we're looking at three so let's see current is equal to zero we already did that and now we check if we can make a valid double digit number so let's see if we combine 2 and 30 we get 23 and that is a double digit number so what we can do is update our current to be equal to previous two so zero gets updated to two and now we check is the current number we're looking at equal to zero well we're looking at a three so no so we can add current plus previous one and then set that equal to current so current is going to be two plus three which is five so you want to update this to five and also at this fourth index we could have a five here meaning we have five different combinations and we know that's true because we can have one two and three twelve two and three 12 and 23 1 2 and 23 or we could have 1 22 and 3 and all of these are valid combinations so that checks out and now we can update our pointers so let's see previous two is going to be updated the previous one which is three and previous one is going to be updated to current which is five and now we just return previous one which would be five and that's true if this video helped in any way please leave a like And subscribe thanks for watching and I'll see you in the next video
Decode Ways
decode-ways
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** s = "12 " **Output:** 2 **Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12). **Example 2:** **Input:** s = "226 " **Output:** 3 **Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6). **Example 3:** **Input:** s = "06 " **Output:** 0 **Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 "). **Constraints:** * `1 <= s.length <= 100` * `s` contains only digits and may contain leading zero(s).
null
String,Dynamic Programming
Medium
639,2091
100
hello everyone so today we are going to solve this question so the question is to find if the given two trees are same or not so in the first example we can see that both of them are having three nodes one two and three in the same direction same order so for example if we consider the root of both of the trees so they are for the left one it is two in both the cases and the right one is three in both the cases so we can see that both of them are same so if they are same we have to return true and if they are not saying we have to return false so in this what we can do is we can the base case will be if they are null so if both of them are null we can return true because now they are same if one of them is null and the other one is not null this means that they are not same and even the subtrees of them will not be same so we will return false in this case and for the remaining cases we can be sure that both of them are not null that is both of them are having some values so if the values are not same then we can return false because the value that not same so it cannot be same tree and the last case is that if both of the values are same so in this what we will do is we will use the question to check all the sub trees of that particular node so for example in this case if we have one as the node as a root so we will check if the left subtree of this node is same as the left subtree of the node the corresponding node of other tree so if both of these sub trees are same then and both the sub trees like left and right if both the sub trees of the trees are same then we can say that both of them are same and for this also as we are using recursion so we will again check for the same properties like same conditions so now we can do the code for this so the first case is that if both of them are null so if P is nelle and Q is also another so both of them under this means that both of them are same so we will return true if any one of them is null so if since both of them are not null and we will check if any one of them is not so if P is equal to null or Q is equal to null we will return false and if both of them are not but the values are different so if P dot well is not equal to Q dot well so we will return false and the last case is that if both of them are not null both of them are having some values and the wall values are also same so what we need to do is we need to check all the subtrees from that particular node so the final condition will be returning the we will use recursion so we will call this function again on the left and right subtrees so P dot left should be same as Q dot left and is same tree P dot right should be same as Q dot right okay so this one little done is the left sub trees are same and this one will return if read the right sub trees are same so if both of them the left and the right are same so this means that both of them are same tree so now we can run this code okay so this solution this approach was similar to the last question they are resolved and this in which we had to find if the given two trees are symmetric or not in the given tree symmetric or not so first we will check all these three conditions and finally we will use recursion to solve the remaining problem so in this one the time and space complexity so that time will be linear because we are checking all of the nodes only ones where n is the number of nodes and space will be equal to the depth of the recursive approach so depth of the recursion so this was other time and space complexity and that's all for this question thank you for watching the video and do like comment share subscribe the channel if you liked the video and the code will be given on my github profile so the link will be given in the description you can check that also thank you
Same Tree
same-tree
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. **Example 1:** **Input:** p = \[1,2,3\], q = \[1,2,3\] **Output:** true **Example 2:** **Input:** p = \[1,2\], q = \[1,null,2\] **Output:** false **Example 3:** **Input:** p = \[1,2,1\], q = \[1,1,2\] **Output:** false **Constraints:** * The number of nodes in both trees is in the range `[0, 100]`. * `-104 <= Node.val <= 104`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
1,673
hey so i just came back from a break which is why i didn't upload for about a week but hopefully now i can start doing that again i just did this question but i realized my mic wasn't turned on so rip um now i'm going to just do it again so find the most competitive sub sequence you're given an array nums and an integer k you want to find a subsequence of nums of size k such that subsequence is the least lexicographically of all possible subsequences so for example if you're given an array like this and k is equal to 2. you want to find a sub sequence such that the subsequence is the least possible in this case it would be 2 6. other subsequences that might start with 3 or 5 wouldn't work because if you have something that starts with the three and the two this is greater lexicographically than this subsequence so this one wins and that should be the answer there is a problem though what about this so i know that maybe i could have a subsequence starting with a one that will give me the smallest lexical graph of these subsequence but by definition of subsequence the order of the elements have to be maintained so i can't just have a one here and then two because the two becomes before a one i can't swap them in the answer so i can't start with a one i have to start with a two and then a one so this would be answer in this case how do we do this we could sort the array and try to find the smallest but then that would ruin the order so a solution could be using a stack and for this solution we go through each element one at a time and add it to a stack so in this case three then we can add the next element of five then we ask ourselves do we want to actually replace the last element in the stack with the current in this case we don't want to replace three with five because five is greater than three so let's leave it then we move on to next element a 2 so up to here now let's just index this array like this we're at index 2 and we could add a 2 to this but k is already the largest possible size so we could ask is to less than the latest element it is and also do i have enough elements remaining after the current so that i can make this stack a size k well after i move five then i only have two elements in the stack if i push two on and i have how many remaining elements two so the number of remaining elements would be numbness.size minus the current would be numbness.size minus the current would be numbness.size minus the current index which is two that will give me five minus two which is three there's only two remaining elements so i can subtract one from that i wanna compare this with number of remaining elements that i need to make my stack a size of k that would be the k minus the answer of size k is 2 so k is 2 and my answer size is 2 so 2 minus 2 is 0 because it's already 2 i don't need any more elements to make this a complete subsequence then i could just ask do i have enough remaining elements to pop off the light latest element well yeah this is less than or equal to the number of remaining elements that is zero is less than or equal to two so that means i can pop off the five and add a two then i ask can i continue replacing the previous elements well two is less than three so it'll be good if i can replace the three with the two can i afford to do that well i still have two remaining elements and how many elements do i need to make up to make this subsequence complete i will need one so this will just be one less is one less than equal to two that's true so i can remove the three here and i move on to index three so i can add a six and that's it i wouldn't want to replace two with a six that's the answer if i remove the one there because that's the original question so let's give that a go four and i is equal to zero i less than nums size in fact i want to store the size in n and then while i can only remove from the answer if the answer is not empty so let's create an answer if answer is not empty then i can remove from it and i want to remove from it because if nums at i is less than the latest element so answer the back and i can remove so k minus answer size is less than or equal to n minus to i minus one that's the number of remaining elements that i can pop back from the array and then i can push back the latest the current element nums i now this could potentially be making the answer have a size greater than k so i only want to do this if instead of size is less than k then at the end return the answer okay give that a run i've done this many times before that seems to work thanks for watching like and subscribe and i'll see you in the next video where we will do a hard question that uses this as a prerequisite so see you then
Find the Most Competitive Subsequence
find-the-most-competitive-subsequence
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. **Example 1:** **Input:** nums = \[3,5,2,6\], k = 2 **Output:** \[2,6\] **Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive. **Example 2:** **Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4 **Output:** \[2,3,3,4\] **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `1 <= k <= nums.length`
null
null
Medium
null
108
in this video we'll be going over convert sorted array to binary surgery so give me an array what elements are sorted in ascending order converted to a high balance bst for this problem a high balanced binary tree is defined as a binary tree in which the depth of two sub trees of every node never differs by more than one so now for example we're giving a sort of array negative 10 negative three zero and five and nine and then we generate a balanced binary search tree we get the following trait so let's go over the thought process so we are given an array numbers of sorted numbers sorted values which number should we pick to be the roots of the current sub tree we will want to pick the node that's exactly in the middle because we want to be height balanced so then the values on the left side can be the values on the left subtree and the values on the right side can be on the right subtree we will want to pick the middle value or we should say the value at the mid index to be the root of our current subject this will allow elements to the left of mid to be the no values for the left subtree then the elements to the right of mid will be the null values for the right subtree we will be keeping track of our current boundaries so let's go over a pseudocode so we'll implement a recursive approach to generate a tree and then what parameters do we need the first it will be the input ring and then left the current left boundary will be initially zero and then the right boundary will be initially at the last index so num star length minus one and then what is the base case if left is greater than right there are no more values to pick to be our node so we can return null as a so we have an invalid node or we don't have any more values to pick to create a node so we're going to return them so in each of the recursive call calculate the mid index mid is go to left plus y minus left divided by two and then generates a root node with nums mid and then we're going to recursively generate the left subtree of roots this will mean our right side has to be updated to mid minus 1 and then we're going to recursively generate the right subtree of roots which means the left has to be updated to mid plus one and then we're going to return groups the newly generated tree and then we go over to time and space complexity the time complexity is of n where n is the length of the input ray visit each index once to generate a node or yes a root node of the current subtree and space complexity is go to of h plus of n now our o h is the recursive call stack memory now onn is the newly generated tree now let's go over the code so we're going to implement the recursive approach keeping track of our current left and right boundaries if left is greater than right we don't have no more values to generate a node so we return no and then we calculate the mid index generate a new tree node with the value at the mid index and generate the left subtree then generate the right subtree and then return the newly generated tree let me know if you have any questions in the comments section below
Convert Sorted Array to Binary Search Tree
convert-sorted-array-to-binary-search-tree
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_. **Example 1:** **Input:** nums = \[-10,-3,0,5,9\] **Output:** \[0,-3,9,-10,null,5\] **Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted: **Example 2:** **Input:** nums = \[1,3\] **Output:** \[3,1\] **Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs. **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in a **strictly increasing** order.
null
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
Easy
109
435
in this video we're going to take a look at a legal problem called non-overlapping intervals so given a non-overlapping intervals so given a non-overlapping intervals so given a collection of intervals find the minimum number of intervals you need to remove to make the rest of intervals non-overlapping so here you can see we non-overlapping so here you can see we non-overlapping so here you can see we have a 2d array and for each sub-race we have and for each sub-race we have and for each sub-race we have a interval which has a start time and the end time so the start time is 1 the end time is 2 and so on and so forth so the there is a overlapping interval in the um in the array so all we have to do is just have to remove the overlap interval in this case we want to remove the minimum number of intervals to remove in this case we can either remove those four right so sorry either we can remove those two or we can remove this interval so we want to remove the minimum number of intervals to make it non-overlapping so in this to make it non-overlapping so in this to make it non-overlapping so in this case we can just remove one two oh sorry one three right so in this case we remove 1 3 the rest of the intervals are non-overlapping of the intervals are non-overlapping of the intervals are non-overlapping so here you can see we have another 2d array which consists of overlapping intervals so all we have to do is just we have to remove two intervals right because we can either remove those two or we can remove those two to make it none overlapping now here you can see we have another example of one two three and there will be no intervals overlapping so if that's the case then we just have to return zero so you might need to remove only um sorry any of the intervals since they are already not overlapping so you might assume the interval's endpoint is always bigger than its star points okay and the intervals like 1 2 and 2 3 are borders touching but they don't overlap each other so to solve this problem let's talk about how we can determine if the intervals are over are overlapping well let's say we have a given example like this right so where we have something like this we know that this is overlapping right this intervals that we have here is overlapping each other because in this case we have an interval starts at one two and the other interval starts at one three one two three right um in this case is overlapping so how can we determine that in the array what we can do is we can check the current intervals last element which is 2 right is actually bigger than the first element of the adjacent interval in this case is 1 then we know that there is an interval right sorry i mean there is a overlapping interval and if we have something like this um then we know that this is a non-overlapping interval because in a non-overlapping interval because in a non-overlapping interval because in this case 2 right la the end time of the current interval is not bigger than the start time of the interval so therefore we cannot say this is the overlapping interval so once we find there is a overlapping interval what we can do is we can say okay well if there is overlap interval we can just remove the um the overlapping dual right so in this case we can either remove this one or remove this one but first we have to sort the array by the each interval's start time in this case let's say we're given this kind of intervals and we just sort the array based on the first element in this case two goes after one so we have a descending ascending order of the start time intervals and that looks something like this and we have 1 3 and 2 4 right so then what we're going to do is we're going to find if there's an interval in this case there is a duplicate or sorry overlapping interval then what we're going to do is we can either remove either this one or this one right so but what if we have something like this right what if we have something like this where okay well we talk we know that all we have to do is we just have to figure out if there's an interval if there is a overlapping interval we just have to increment the count by one and then we're just going to compare um the next interval right so in this case we have a situation where we have three overlapping intervals then which one should we remove right we can either remove um one second let's change the color so we can either remove this one right we can either remove this one or we can remove this one because if we were to remove this one we have to remove um both of them right because in this case if we remove this one there is another overlapping interval right here so we if so we have to remove both then there will be two intervals that we're going to remove but if we were only to remove this interval right here right then we only have two intervals right so there in this case if we remove this one that will be the valid answer so how can we how do we know that well let's take a look at another example here you can see we have another interval right so three intervals and you can see that we have a long one which is between one and five and the other one is two to three and the other one is four to five so which one should we remove we can either remove those two and keep the longer one right or what we can do is we can just remove the longer one and keep the shorter ones and now we have two intervals rather than just one so the valid answer of course is going to be removing the longer one so that we have uh we basically remove the minimum interval right in this case we just remove one so to solve this problem what we can do is we can basically um compare the end time right we want to let's say we found that there is a overlapping interval all we have to do is we just have to compare the end time of those each intervals those two intervals we're basically trying to find we're basically trying to remove an interval that has a longer end time or a larger end time in this case the end time for this second interval is four then all we have to do is we just have to remove the interval that has a bigger um bigger end time in this case is going to be the second interval right and same thing apply to this one right here okay so in this case if we were to if we found a dupe overlapping interval all we had to do is we have to remove the longer interval right the bigger end time a interval that has a bigger end time in this case is going to be the first one it's going to be this one right here this one's five and this one's three is less than five so what we have to do is we just have to remove the top one okay so what if we yeah basically here you can see all we have to do is we just compare the left end time and the right end time if the right end time is bigger then we just have to remove the right end time okay so now you know how to solve this problem let's take a look at how we can do this in code so if we were to do this in code our first step is to make sure that the data right the intervals are not empty so we're going to check to see if intervals dot length is equal to zero or intervals at zero the length is equal to zero right because it doesn't really say anything on the constraints so we're going to see if it's actually zero if it's empty then we can just return zero because there's nothing that we can remove right okay so we're going to do then is um one second okay so we're going to do then is we're basically just going to have a sort the array first right we're going to sort the array raise the sort intervals based on the um the start time so we have a and b we're going to sort the array based on ascending order okay and we're going to do is once we sort the array we're going to have a because we're going to remove um no sorry we're not going to remove the interval we're just going to have a tracker the counter that basically count how many intervals that we remove at the end so we're going to say count counter right so counter is equal to zero and we're also going to have a previous interval because we don't know which one we're going to compare the interval with right we initially we're going to have a this interval as the initial interval so that we can compare with the adjacent element right in this case we're going to compare with this interval um if this interval is overlapping with this interval and this interval has a shorter um has a smaller end time then we're going to take this interval as the previous interval to compare with the next interval right so we're going to have pre is equal to intervals at zero and we're going to start your the array or the um the loop at next one so while i is less than intervals that length what we're going to do is we're just going to start to compare um with the current interval with the previous interval right so in this case if the previous interval at 1 the end time is actually bigger than intervals at i at the start time right if it's bigger then we know that this is there is overlapping so that means that there is overlapping if there is a overlapping then what we're going to do is we're going to see who has a larger end time and whoever has a larger end time we're just going to um remove that right we're not actually going to remove that we're just going to keep we're just going to get the interval that's not that's that has a shorter um that has a shorter end time to be the previous array right to be the previous um interval that we're going to compare with the next interval so we're going to do is we're going to first increment the counter by 1 because we found the overlapping interval right so we're going to remove it and then we're going to do is we're going to see if the previous at 1 is actually bigger than intervals at i as at 1 right so we're going to see if the um so if the previous interval right in this case at one is bigger than the interval the current interval then what we have to do is we have to get the previous interval the previous pointer it's going to point to intervals at i okay and this will give us the um the interval the new interval that we're going to compare with in the next iteration otherwise if we have a situation where we don't have interval then we also have to get the previous interval point to the current interval to compare with right and at the end our returning is the counter so basically let me just summarize this basically we're just going to have a previous interval the previous interval that we're going to compare with the current interval and we start at index one and then what we're going to do is we're going to see if there's overlapping right so we're going to compare to see if the previous interval at the end time is bigger than in the current intervals at the start time if it is then there is over there is a overlapping then we're just going to increment the counter by one and if the um to delete the overlapping integral we want to delete a interval that has a larger end time in this case if the previous interval that end time is bigger than the current interval's end time then we're going to get the smaller end time um interval to be the previous interval right and um if there is no overlapping then we're going to get the previous interval is equal to the intervals at i which is the current interval so that we can compare with the adjacent interval right the next iteration so let's try to run the code okay let's try to throw more test cases okay let's try to submit and here you can see we have our success so basically this is how we solve this lee code problem and the time complexity in this case is going to be in log in because we're doing sorting and this is going to be linear so n log n is bigger than linear so therefore we have a log in as a time complexity so there you have it and thank you for watching
Non-overlapping Intervals
non-overlapping-intervals
Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_. **Example 1:** **Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\] **Output:** 1 **Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping. **Example 2:** **Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\] **Output:** 2 **Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping. **Example 3:** **Input:** intervals = \[\[1,2\],\[2,3\]\] **Output:** 0 **Explanation:** You don't need to remove any of the intervals since they're already non-overlapping. **Constraints:** * `1 <= intervals.length <= 105` * `intervals[i].length == 2` * `-5 * 104 <= starti < endi <= 5 * 104`
null
Array,Dynamic Programming,Greedy,Sorting
Medium
452
1,020
hey so welcome back and this is another daily code problem so today it was called number of enclaves so let's take a look at it so this is a medium level graph question and so you're given this two-dimensional and so you're given this two-dimensional and so you're given this two-dimensional Matrix here called grid and where you want to Output an integer and so all that you want to do is find out how many land blocks here so yesterday's question was actually the opposite where like the ones represented water and the zero was land but they actually inverted it this time so this time ones represent land box and zero is water and so you want to return the number of land blocks that don't touch the boundary so in this case it is like three here and so you don't count this one because it's naturally it's touching the boundary there and so for this one we return zero and so that's because if any of them touch the boundary here then you automatically want to say okay the whole block itself won't work and so you just set them all to zero so you don't even include like this one here and this one here because as long as one portion of the island is connected to the boundary then it won't work so there's two kind of popular approaches that you can solve this one of them is to go from like the boundary inwards and the other ones that kind of go from the like inside of the island outwards and so like what you could do is kind of flood inwards and say okay anything that touches any land blocks that touched this boundary let's kind of explore inwards and just set all of those blocks to zero so in this case we kind of go around the edges here just outside of the boundary the first kind of walks in around these edges and we say okay let's visit once we encounter a land block let's just like visit this entire uh Island here and just set them all to zero and so you can do this we just set all of these to zero and so then once you do that and you kind of export anything that attaches to the boundary then you know okay any uh land blocks that are within this sphere here we will say okay that is good and we just count them all and so in this case maybe this might be a better example you can say okay let's explore around you know the edges here and we go around we say okay this is a one so let's explore this island and set all the cells to zero well there's only one here so you only have to set one to zero well let's do that so we set this to zero and then we say okay now let's explore all of the values that are in the middle here that don't connect to this Edge and just say whenever we encounter one let's increment the count and so we can do that okay but for me I kind of like a different approach where you just iterate through this entire Matrix here and whenever you encounter A1 you explore that island and just see okay if I can reach the exterior boundary here then we won't include this count and so right initially you say okay we found one land block let's explore it so let's go right nope no land there let's go down there's no way in there let's go up no land so it's still at a count of one but once you kind of go out of bounds and you see that oh we're touching the boundary then you say okay we're not even going to include this count and so it's worth nothing so we're still at zero but when we explore this island we say okay there's a lion block here there's one here and there's one here so we're at a count of three and so as we check every single neighboring block here from this island we see that okay none of them touch the boundaries so that we do actually include the count of three okay so this time complexity is just going to be like n by m where it's like the number of rows and number of columns um and I think for the space complexity it's the same thing because we're going to want to have a kind of visited set to just keep track of blocks that we visited before so we don't just end up in an infinite Loop and keep recursively visiting them so yeah I'll show you the implementation for the second algorithm but if you like the other one maybe try implementing that approach as well so let's go ahead and so first thing we want to do is just get the rows and number of columns just because we're going to be reusing these a couple times so number of rows is equal to the length of the grid and then this is how you get the columns so now we just want to iterate through all the rows and all the columns and all of this is just templated code that you write for a lot of these Matrix problems great and so from here we're going to want to perform our depth first search so at the end we're expecting to return like a total count so we want to return that and initially it's going to be zero and so let's define our depth first search function and we're going to want to pass in like the row and the column like the indexes that we're looking at say we want to start exploring this node and so the only ones that we're going to want to explore is when we find land here otherwise we don't care about exploring the water we want to explore these islands so we only want to perform depth per surge if at this particular location it's equal to one so then we want to explore it and so now we only want to add to our account here so if our depth first search function finds that okay this isn't connected so let's return true if our um Island that we just explored is like not connected and let's return false if it is connected and so you don't want to include it so we kind of complicate if true so like island is not connected then we'll want to add to our account so we'll do account plus equals and so let's say that in this that first search function we're also not only are we returning like true or false if we want to add account but there's going to be a count that will be incrementing while we're in here and we'll call that like current account and so before we perform our depth first search function this initially would be zero but inside of this step for search function it'll be incremented here and we'll just add to our account as long as the island is not connected otherwise we don't want to okay and so we want to pass in the rows and the columns like we are and so to get this current count variable a common approach is just to Define non-local in approach is just to Define non-local in approach is just to Define non-local in that variable name and so that way you can get access to this and increment the count Okay so first thing that we want to do is we want to check okay have we hit out of bounds in this kind of our base case like once we go out of bounds we don't want to explore anymore and so we want to say okay if our row index is less than zero then it's out of bounds or with a column is less than zero then it's also out of bounds I don't need to add that also if it's equal to the number of rows then we know it's out of bounds or in that case also the number of columns so any of these cases we know it's out of bounds and we don't we want to say okay um it is in fact connected so hashtag Island touches boundary otherwise let's continue on so if it touches water then we know okay in this case we didn't just find the boundary so let's just return false and so we want to return immediately once we see water here because we don't need to explore any further beyond that we don't see need to look at the waters neighbors we just need to say okay this is just water and let's just return true and continue on so if at this location it is just water let's just return true so Island touched water and so we also want to return true if we already visited this piece of land before and so that in that case like let's say that you explore this point and you go up down left and right and then you travel to this node you want to make sure that once you're visiting this node and you're looking left and right and up and down you don't look at this note and then start revisiting this again and just infinitely doing that so to prevent that we're going to have a visit set and so we want to add to our set whenever we touch land here so visit dot add this particular row at this column so we also want to say okay if we already visited this piece of land before let's just return true so we don't keep exploring it so if this is in our visit set or we touch water awesome okay so from here we're going to want to go in all the different directions so up down left and right but before we do that since we know that this didn't touch the boundary and didn't touch water or we haven't already visited this piece of land let's increment our account and so we just found a new piece of land that we're trying to count for out but so let's increment this by one great and so from there let's just say okay left is equal to that first search and we're going to want to go at this particular row but to the column behind us and then we'll also want to go in the right direction so we just increment the column by one and then we want to say let's go in the downwards Direction so we want to go to the row below us yes this way oh and these need to be minuses here and then finally we also want to go up or I think I got this reverse so no this is that then up is negative one because it's reverse when it's you're dealing with rows great and let's and then at the end of this we just want to return and so we need to make sure that in every single Direction these all return true otherwise one of them touch the boundary so we want to return false and not increment our account okay and so to do that we just say if left return true and right and also our downward section and our upwards Direction all these must have returned true so like hashtag Explorer Island and this is just visiting land block an incrementing the count great let's try running that and it looks accepted oh we got a wrong answer so we return 23. that is not good and so it didn't get very far let's use that test case so let's see here so our account plus equals it gets reset here we're incrementing our current count and let's make sure that I'm using the right numbers so I don't know how to lower this for some reason right now there we go so zero is water so that looks good if row is less than zero yep makes sense are these right left right down up yep oh I need to add plus one here so that's definitely one issue there might be another but we'll try fixing this oh that worked and it worked this time so just small issue basically if we just look at here I just had to change this so that when we're going right we add to our column so sorry if that confused anyone but yeah once again this is n by m where that's like the number of rows the number of columns for the time complexity and also the space complexity because we'll want to add to this visited set for every Row for every cell at every Row in every column and so that you have to have some space but otherwise you'll just be visiting every island infinitely so you need that so yeah I hope that helped this is the depth first search approach and I think it's um pretty intuitive it's just once you get this templated code and you practice a few of these problems it helps a lot you'll see the patterns and you just kind of have to take that templated code that you the patterns that you see and just alter it a little bit to answer this question so yeah I hope that helped and hope you have a great day thanks for watching
Number of Enclaves
longest-turbulent-subarray
You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell. A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`. Return _the number of land cells in_ `grid` _for which we cannot walk off the boundary of the grid in any number of **moves**_. **Example 1:** **Input:** grid = \[\[0,0,0,0\],\[1,0,1,0\],\[0,1,1,0\],\[0,0,0,0\]\] **Output:** 3 **Explanation:** There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary. **Example 2:** **Input:** grid = \[\[0,1,1,0\],\[0,0,1,0\],\[0,0,1,0\],\[0,0,0,0\]\] **Output:** 0 **Explanation:** All 1s are either on the boundary or can reach the boundary. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 500` * `grid[i][j]` is either `0` or `1`. For i <= k < j, arr\[k\] > arr\[k + 1\] when k is odd, and arr\[k\] < arr\[k + 1\] when k is even. OR For i <= k < j, arr\[k\] > arr\[k + 1\] when k is even, and arr\[k\] < arr\[k + 1\] when k is odd.
null
Array,Dynamic Programming,Sliding Window
Medium
53
1,441
hello hi guys good morning welcome back to the new video so this video we're going to see the problem uh build an array with stack operations so as you can see right here uh it has been asked by Google not much frequently uh so the problem says that what we are having right here with us we are we have to build an array with the stack operations whatsoever we have now what are stack operations uh we are having an in are called as Target and the only operations which we can perform again the only operations which we can perform is push or a pop on every element I can just perform an like perform this Operation Push or a pop I cannot just say Okay halt or skip I have to perform a push or a pop now you also have a stream of integers from 1 to n I have a stream of integers from 1 to n now with this stream of integers from 1 to n I have to build this target itself such that Target is built inside the stack and it is build from bottom to top which means if the target is 1A 3A 5 so the stack ultimately would should be in the form of 1A 3A 5 now as you can see it has been asked by Google but as you can see that the problem is going pretty straightforward so far not yet not sure because maybe it is saying okay the target is what if the target is 3 comma 5A 2 it can be something like this also so like still that it is not clear that what is my target but still I have to somehow make my Target and represent that in form of my stack now um it just says a few condition that okay if the stack is uh if the stream of integers is not empty then pick the next integer from the stream and just push that to a stack on the top of the stack now if the stack is not empty pop the integer on the top of the stack which means you can push as soon as you enter an element you have to push like you just can't skip it and if the stack top is not empty which means okay it's possible to actually pop that element out now at any moment if I have actually got in my target good simply just skip it and like you are good you are done simply have it done now return the stack operations needed to build the target following the mentioned rules if there are multiple valid answer return any of them so ultimately here it's still not verified that How Could my target look like my target could be something like this also it can be something like 351 also now what I'm anticipating is it has been asked by Google but if you just look go and look for the constraints it says the target is strictly increasing which simply means that how this can be solved is um if I have my stream of integers as 1 to n which means I have integers as 1 2 3 4 5 I can simply go on to all the integers if it is one okay I can I know I have my target which is strictly increased in so I know my target is 13 I will have a two pointers kind of approach I pointer pointing to my target pointer J pointing to my N I just say okay if they both are same great just do a push operation okay I just did a push operation in my answer I have a push operation simple okay I'll just go on and increment both of my values now uh my J is not equal to I okay cool which means still I can't just simply skip it I again have to do a push and a pop operation which means pushing two and then popping two back okay cool now move j 3 three matching cool matching just simply do a push operation cool both are incremented I and here it is I uh RJ 54 again not same so simply push it and then pop it out right so again a push and a pop and then increment uh sorry in this will remain same as it is and this will have a j right here 55 same oh great again uh do a simply push operation cool again a last push operation now both will increment any as soon as any of them reaches end most probably like most like for sure the target will for sure first reach to the end or like at the same time as that of the end stream because Target is a subset of n right so as soon as my target reaches my end I just simply say that oh I have achieved whatsoever I wanted and this is the following configuration so I have just simply do it now what I'm anticipating is Google might have asked a followup question on top of it that what if the target is not in a strictly inreasing order thus in that case we would be needing two stacks as in here you will see I'm just trating on the entire stream time is O of N and space is nothing but o of one because I'm not using the space it was just to show you I'm just using two pointers I and j i at Target J at my n uh stream of n integers but if I had to use two stacks just to find out um like okay what could be the POS configuration when the target is actually not in that sequence which means it is 3 5 one so I would have to keep track okay I have found a one so please push this somewhere in actual code or maybe you can just have a bit more thinking and just say okay I have pushed it three times previously so in my other stack you can just imagine in your other stack as soon as what you will do why if it's just a followup question now followup question can be of the form that what if the target is not in the cly inreasing order so you will just Skip One you will skip two now you will land on to a three as you land on to a three you just push it but this one and two you would have pushed in or you would have keeping track of okay I have got a one I have got a two previously it can be bit modification that right now it's just a push and a pop operation but maybe it can happen that okay I'm just pushing it another stock now okay I got a three I'll just simply keep on trading I'll just push a four then I'll get a five okay I'll get a five then it might happen that I have to go and check in my new stack what is the location of one I have to pop out those many elements I'll pop four I'll pop two I'll get a one then I just can simply push a one here so that it is what I'm thinking could be the followup question for this problem but yeah simple what we have to do is simply trade on my target for the current problem we have to Simply On Target simply on the in stream of integers and simply get our answer cool uh let's quickly jump on to the code it would be pretty short and simple um as we know that we have to uh simply return our answer as an it could be a push or a pop the push or a pop now as we saw that we will maintain two integers now both of the pointers uh let's name it as a Target uh pointer which is I and also our stream pointer which is um let's name it as stream pointer which is actually initially uh zero now I will just simply keep on iterating on my target pointer now why you can also have for loop with it but let's see if you can just do it by uh with the V Loop now while my target pointer is lesser than my uh Target dot size now if that is the case so what we can do is firstly we'll just check if the target of that Target pointer and for sure um push is a operation which we have to perform always so one thing I can do is I can just do okay just push back my value of push right because for sure as soon as I encounter element I will have to push it even if it is in my target or not if it is not in my target I just simply pop it out so I just have a mention if my target if my value at Target pointer if it is actually equal to my stream of integers now stream of integers pointing to a stream pointer now stream pointer will start from one itself right it will start from one itself now a stream pointer if it is actually equal great just simply increase your both Target pointer and also you have to increase your stream pointer but stream pointer will any way increase so we can just increase that in the end which means I can just do a stream pointer Plus+ because it will increase in else Plus+ because it will increase in else Plus+ because it will increase in else Loop also it's just that in the lse loop I will just have to make sure it did not match so simply push back that pop po o right not po o uh in my answer and then it should work and return our answer itself just going on that Target if it is less just simply push that element if the element is actually equal to stream pointer just put it in our vector uh increase the pointer and else for sure you have to do a pop and then simply keep on increasing uh let's see what we have Target t a r g my spellings are always wrong but no worries uh it seems fine let's push and submit yeah it is done cool thank you so much for watching uh it's time Isn and space is cool see you bye-bye
Build an Array With Stack Operations
minimum-flips-to-make-a-or-b-equal-to-c
You are given an integer array `target` and an integer `n`. You have an empty stack with the two following operations: * **`"Push "`**: pushes an integer to the top of the stack. * **`"Pop "`**: removes the integer on the top of the stack. You also have a stream of the integers in the range `[1, n]`. Use the two stack operations to make the numbers in the stack (from the bottom to the top) equal to `target`. You should follow the following rules: * If the stream of the integers is not empty, pick the next integer from the stream and push it to the top of the stack. * If the stack is not empty, pop the integer at the top of the stack. * If, at any moment, the elements in the stack (from the bottom to the top) are equal to `target`, do not read new integers from the stream and do not do more operations on the stack. Return _the stack operations needed to build_ `target` following the mentioned rules. If there are multiple valid answers, return **any of them**. **Example 1:** **Input:** target = \[1,3\], n = 3 **Output:** \[ "Push ", "Push ", "Pop ", "Push "\] **Explanation:** Initially the stack s is empty. The last element is the top of the stack. Read 1 from the stream and push it to the stack. s = \[1\]. Read 2 from the stream and push it to the stack. s = \[1,2\]. Pop the integer on the top of the stack. s = \[1\]. Read 3 from the stream and push it to the stack. s = \[1,3\]. **Example 2:** **Input:** target = \[1,2,3\], n = 3 **Output:** \[ "Push ", "Push ", "Push "\] **Explanation:** Initially the stack s is empty. The last element is the top of the stack. Read 1 from the stream and push it to the stack. s = \[1\]. Read 2 from the stream and push it to the stack. s = \[1,2\]. Read 3 from the stream and push it to the stack. s = \[1,2,3\]. **Example 3:** **Input:** target = \[1,2\], n = 4 **Output:** \[ "Push ", "Push "\] **Explanation:** Initially the stack s is empty. The last element is the top of the stack. Read 1 from the stream and push it to the stack. s = \[1\]. Read 2 from the stream and push it to the stack. s = \[1,2\]. Since the stack (from the bottom to the top) is equal to target, we stop the stack operations. The answers that read integer 3 from the stream are not accepted. **Constraints:** * `1 <= target.length <= 100` * `1 <= n <= 100` * `1 <= target[i] <= n` * `target` is strictly increasing.
Check the bits one by one whether they need to be flipped.
Bit Manipulation
Medium
2323
728
Scientist Hi Ghadi Jhadu Are You Welcome To Your Friend Delivery In Images Were Completed And Lord Of Ghosts And Evil Dual Core Processor Slow Before Proceeding Is Humble Request To Avoid In The Guys In This Video Knowledge Swiss Watching This Video Please Wrong With Screaming And Is Channel Like Subscribe And Comment B.Com Channel Like Subscribe And Comment B.Com Channel Like Subscribe And Comment B.Com Dream Of Hearts And In This Humble Request To All Please Comment And You Will Go With Screaming And Share Space With All Your Friends Laugh Butt Motivation And Tagged Airplane Mode Switch On Is Anomaly Something To Give And Just Butt You Should Give Me Something And Nature In Fiji And It's Nothing But In Its Soldiers With Awareness Question Awadhi Vegetable Question And Not Going To In-Between Time In This Should Be In The And Going To In-Between Time In This Should Be In The And Going To In-Between Time In This Should Be In The And Acid Number Is Given Asif Baj Number Container Me Digit Talibani Number is called the only body number is good so is the return contains 1281 round digits are you can be completed divisible 128 MB cases number in the morning in this app will not leave when divided into 18202 cancer devices all should cancel residents bunty ginger mix it is a Complete Sir Gaadi Number Birth Sir Number Is Not Allowed Container Zero Certificate To Difficult Times This Interior Digit And Take One By One All Is It Will Defeat In The Right To Divide December In This Manner And Will Take Two Days Against Evil Will Take 80 Against Each And Every Day I Will Take Away All The Way Will Come To The Country Which Ads Points 220 Quinn Check Weather The Length Of This And Account Is Also That Aapko Note Sudheesh The Length Of This Thriller Country Lakshmi This Is A Begum Marvaay Anojati Hai Work 3812 8383 Low Acid Divisible By 3 A Low City Account Dr To 3 And Vitamin For Vikas 12345 For R Country Ladli Begum Forces Page Number 90 Divide December Subscribe To The First Ashok Vihar And Left And Right Subah Be Written All Elements Which Online Idm Swayam Project When One does should first husband will come in defiance of welcome and passive will be instigated 100 number one what is sid and in english convert into the 2nd T20 number is mid converted into being converted into this world but not he Mohammed Akram and continue till guava This length it is and early morning method second number just tap and will come to 1518 check the number Vikram 1517 check then check the first division welcome to digit 98100 Singh's anniversary face ok 50000 subscribe to the Video then subscribe to the Page Is the in artificial yes to a division of Battu yes English in the same manner this to welcome to * is equal to learn from this is what to * is equal to learn from this is what to * is equal to learn from this is what is land for btc-2012 channel number and in this to sources on btc-2012 channel number and in this to sources on btc-2012 channel number and in this to sources on subsidies and scheduled tribes from Left to right in the middle east saffron in the and hair soft will give me trolley ok friends you comment and now so humble request to all please subscribe ok and don't go with screaming ok so in the great were so if you are interested in this question Big Guide Will Meet In This Video And Don't Forget Their Sacrifice Humble Request To All Baba Guys Take
Self Dividing Numbers
self-dividing-numbers
A **self-dividing number** is a number that is divisible by every digit it contains. * For example, `128` is **a self-dividing number** because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`. A **self-dividing number** is not allowed to contain the digit zero. Given two integers `left` and `right`, return _a list of all the **self-dividing numbers** in the range_ `[left, right]`. **Example 1:** **Input:** left = 1, right = 22 **Output:** \[1,2,3,4,5,6,7,8,9,11,12,15,22\] **Example 2:** **Input:** left = 47, right = 85 **Output:** \[48,55,66,77\] **Constraints:** * `1 <= left <= right <= 104`
For each number in the range, check whether it is self dividing by converting that number to a character array (or string in Python), then checking that each digit is nonzero and divides the original number.
Math
Easy
507
112
hello everyone today we are looking at liquid problem number 112 path sum in this problem we are given a binary tree and an integer Target sum and we should check if the binary tree contains a path which starts at the root goes all the way down to leaf such that the sum of all the values on that path equal the integer Target sum in this example here the target sum is 22 and if we go from the root along this blue marked path the total sum is 5 plus 4 plus 11 plus 2 which is 22. and yeah how are we going to solve this problem in principle trees are recursive data structures so often it makes sense to use a recursive solution and in this case we are doing some kind of search so often we can use a top down approach for finding this kind of path let's look at a few examples so we want to write a recursive function called has path sum and it should take a Chui or let's say a pointer to the root and it should take an integer a Target sum and since we want to write a recursive function it makes sense to First think about the base cases so first case wood is null so actually we don't have a tree the tree is empty and this case is already defined in the problem statement or to be more precise in example in this case we should always say that there's no path sum because there's no path the second base case happens when our tree is actually a leaf so that means that root dot left and root dot right anal and in that case we have a leaf because we have okay let's say the wood is not null because we already handled that in case one so when uh do we have to Target some in that case well our tree looks like this and in here is a value and left is null and write a snull so the only way to make the root path is to well start and end at the root so we can return whether the value is identical to the Target sum if yes then we found such a path if not then there can be no such path now let's look at the complex case where we have here our node and let's say you need some value let's say five and now we have a left sub tree and the right sub tree and our node is not a leaf so e to the left is not empty or the white is not empty it can be that one of them is empty but not both of them and where we also have a Target so let's say for example that our Target sum is 22. now um what can we do well we know that our path must start in the root so we already know for sure that we have five as part of our path so we can already subtract 5 from our Target sum 22 minus 5 is 17. and we now know that we need to find a remaining path to a leaf with a total sum of 17 and one of the subtrees so either we can go inside the left subtree and inside here find the path from the root of the left subtree down to a leaf of the left subtree and this path in here must have length 17 or we can go on the right subtree and then we must find a path from the root of the right sub tree to a leaf of the right sub tree and this path must also have a length of 17. if we can do that in either of the subtrees then we have found a total path starting at this five going to a leaf if we cannot do it in either of the subtrees then there's no solution okay let's go to the code so here's the code of our solution and we handle the three cases that we just talked about the case one is that the tree is empty in this case we just check if the wood is null and we can return false now the second case the root is actually a leaf node well for that to check we need to check if both the left and the right sub tree are null in this case we are leaf and we need to check if the value in the leaf equals the target sum now the third case which is the interesting one here first we subtract from our Target sum the value of the root and next we check both the left sub tree and the right sub tree and we do this using recursive chords in the first recursive call we check the left subtree and we look for our update value where we already subtracted the root of the original tree in the secondary cursive call we do the same but for the white subtree also with the updated value finally we use the or operator to combine the results because if there's a solution in the left subtree or in the Y subtree then we have also found a solution for the whole tree and let's run it's accepted so that's the solution to this problem if you like the video please leave a like subscribe to the channel and I'll see you in the next one
Path Sum
path-sum
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22 **Output:** true **Explanation:** The root-to-leaf path with the target sum is shown. **Example 2:** **Input:** root = \[1,2,3\], targetSum = 5 **Output:** false **Explanation:** There two root-to-leaf paths in the tree: (1 --> 2): The sum is 3. (1 --> 3): The sum is 4. There is no root-to-leaf path with sum = 5. **Example 3:** **Input:** root = \[\], targetSum = 0 **Output:** false **Explanation:** Since the tree is empty, there are no root-to-leaf paths. **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-1000 <= Node.val <= 1000` * `-1000 <= targetSum <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
113,124,129,437,666
701
hey everyone welcome back and let's write some more neat code today so today let's solve the problem insert into a binary search tree we're given the root of a binary search tree and a value that we want to insert into the tree and then we want to return the new root of the tree also it is guaranteed that the new value does not exist in the original BST and they also clarify that there are multiple ways to solve this problem there's multiple ways to insert into a binary search tree and we can return any of them thankfully now before we get started on the solution let's actually break this problem down there's a few key points to notice first of all this is a binary search tree not just a regular binary tree so there is a sorted property to the tree remember that for every single node in the tree every node in the left subtree of that node is going to be less than the value here four it's going to be less than 4 and every value in the right subtree is going to be greater than 4 and this property is recursive so it's not just true for the root node it's true for every single node in the tree now they also clarified that we're guaranteed that the new value that we're inserting in this case 5 does not already exist in the tree that's very important because that's first of all usually the case with binary search trees but it's also important because we need to find a position that we can insert this five in now technically if we wanted to we could put the 5 in the root spot and then like rebalance the entire tree around the new root value that's kind of a difficult way to do this now the simple way to do this you might already remember if you took a data structures and algorithms class but I really want to emphasize the thought process behind this problem because it's very trivial for me to solve it because I kind of know exactly how to do it the easiest way you start at the root and you basically keep searching until we get to a null position now how do you search while you use the sorted proper if we're inserting a 5 is that greater than four or less than four we know it's definitely not going to be equal to any node in the entire tree it's never going to happen we're either going to go to the right or we're going to go to the left in this case 5 is greater we're going to go to the right now for 7 are we going to the left or are we going to the right we're going to go to the left and now we reached a null position we're guaranteed to reach a null position because like I said we know for sure 5 does not already exist in the tree so every time we get to a new node we're either going to go left or we're going to go right now unless the tree is infinitely large we know for sure we're going to reach a null position and that's where we want to insert this 5 into so we put the 5 over here and you can see that's pretty much what they had in the output now how do we actually code this up well there's two ways to do it we can do it the iterative way or we can do it the recursive way let's compare and contrast these two different ways to do this very quickly if we do this iteratively we're going to start at the root and then we're going to go to seven and then we're going to end up at a null position now how do we actually insert a node here well we would want to connect this node and add a left child for it a five so therefore we don't really want our pointer to end over here because we need access to the parent node so we would want to stop at the point where we see that okay we want to go left but left is null so therefore we stop and we go ahead and insert the node that's a pretty easy and doable way to do this we could also do it the recursive way which I think is a little bit trickier because there's a very important Edge case here that I want to emphasize what happens if we have an empty tree we want to insert five into an empty tree because remember we actually have to return the root of the node of the binary search tree and in this case we'll have a new root node if our tree is empty then we have a new root node so in the iterative solution I think it's pretty easy because all you have to do is create a node and then return it but for the recursive solution it's a bit different because for the recursive solution we're actually handling that edge case that I talked about in both cases because in the recursive solution when we get to the null position over here we actually want to create that node 5 and then return it up to its parent and then from its parent we're going to say we inserted a new node into the left subtree and then we return to that tree so we're going to take that tree and set it to the left child of seven I think the recursive solution is a bit harder but I think it's also more powerful because you can apply it to other problems more easily and I think it's really important to understand so I'm going to be focusing on the recursive solution when we code it up right now but I'll also briefly show the iterative solution towards the end before we move on what would be the time complexity of inserting a node well first of all how are we going to measure it we can measure it based on the size of our binary search tree let's say n is the number of nodes in our tree and we could also measure it using the height of the tree let's say h is the height of our tree technically in the worst case this is going to be the time complexity Big O of H because we don't have to visit every single node we're going to every step either go left or go right so we're just going to basically have like a chain like this which is going to be the length of the height of the tree in the worst case though we might not have a balanced tree it might just look something like this technically the worst case time complexity could also be Big O of N I like to say Big O of H though because it's more accurate I think because H could be equal to N I think it's more correct to say that the time complexity is the height of the tree it's also worth mentioning though that the recursive solution takes extra memory because we have a call stack we're going to do it recursively we're going to call a function here we're going to keep doing that basically same thing the height of the tree so the memory complexity is going to be a big O of H whereas if we do it iteratively we don't have a call stack we just have a pointer that we keep shifting and therefore the memory complexity of that will be constant Big O of one okay now let's code it up remember the first Edge case what if we have an empty tree well then we basically want to create a new tree node we can do that with the Constructor passing in the value parameter that we're given and this is what we want to return after we've created a new tree otherwise we know we have to keep searching until we do reach null we know we're going to reach it eventually but we have to figure out which direction we want to go in is the value greater than the current value that we're at the current node that we were given if it is then we want to call insert on the right subtree passing in the exact same value of course now here's where things can get a bit confusing remember after we insert into the right sub tree what if the right subtree of the root is null that means what this insert function would do is it would just create a new tree node and then return it but if we return it like this we're not doing anything with it then root Dot right will still equal null so to change that we want root dot right to be equal to the new node that we just inserted and we want to do the exact same thing in the opposite case where our value would be less than root dot val I don't have to specify that here though because we know for sure value is never going to be equal to root dot val so I'm just going to copy and paste this and just change a couple values we want to do this now on the left side of the tree because our value is less than the current root value that we're at so we basically just change this now the last thing here is after we do that we still need to return the root the reason being what if root dot right here when we pass it in to the insert function is non-null then we would function is non-null then we would function is non-null then we would basically call insert end up in this function and then maybe we'd have to call insert again going either of the directions and keep doing that multiple times so in that case the root actually would not change the route that this insert function would call would not change we would want to return it and then keep assigning it to root dot right that would not do anything in that case where it's not changing but we know we still have to have these assignments in the case that the return value did change which would of course only happen if the route that we passed was null and then we created a new node and then returned that so let's run this to make sure that it works and as you can see yes it does and it's pretty efficient now let me briefly show you the iterative solution so this is the iterative solution we have the same base case if we are given an empty tree we just create a node and then return it otherwise we set our current Warner equal to the root and I just go while true because we know we're going to keep going until we reach null and the way I wrote this we never need to break out of this while loop because I'm just returning root inside of these but you know you could have done it the other way that's up to your preference but logically this is mostly the same if the value we want to insert is greater than the current value we go to the right otherwise we go to the left now what happens if we can't go any further to the right then we go ahead and insert the new node because we know we found the null pointer and then we return the root notice how what I'm returning is not Cur I'm returning the root because that's what we want to return for this insertion otherwise though if we didn't find the null pointer then we go ahead and just say Cur is equal to Cur dot right we're doing logically the exact same thing on the left side of the tree as you can see below and that's pretty much the iterative solution I'll go ahead and run it to make sure that it works and as you can see yes it does and it's pretty much just as efficient in terms of memory it's probably a bit more efficient if this was helpful please like And subscribe if you'd like to see code solutions for languages other than python check out neat code.io it's got a python check out neat code.io it's got a python check out neat code.io it's got a ton of free resources to help you prepare for coding interviews thanks for watching and hopefully I'll see you pretty soon
Insert into a Binary Search Tree
insert-into-a-binary-search-tree
You are given the `root` node of a binary search tree (BST) and a `value` to insert into the tree. Return _the root node of the BST after the insertion_. It is **guaranteed** that the new value does not exist in the original BST. **Notice** that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return **any of them**. **Example 1:** **Input:** root = \[4,2,7,1,3\], val = 5 **Output:** \[4,2,7,1,3,5\] **Explanation:** Another accepted tree is: **Example 2:** **Input:** root = \[40,20,60,10,30,50,70\], val = 25 **Output:** \[40,20,60,10,30,50,70,null,null,25\] **Example 3:** **Input:** root = \[4,2,7,1,3,null,null,null,null,null,null\], val = 5 **Output:** \[4,2,7,1,3,5\] **Constraints:** * The number of nodes in the tree will be in the range `[0, 104]`. * `-108 <= Node.val <= 108` * All the values `Node.val` are **unique**. * `-108 <= val <= 108` * It's **guaranteed** that `val` does not exist in the original BST.
null
null
Medium
null
1,086
hello friends we are not employed by a fan company so let's not stop lead coding till we get there today we are going to do a lead code premium problem high five and uh the though it seems like an easy problem this actually covers a pretty interesting topic that is asked by a lot of fang companies uh and the topic is max heap mean heap so let's understand the problem statement essentially we are given a two dimensional array that looks like this uh where we are given id and score for different students uh that are studying in a class and now we are given at least five scores or more uh for every single students uh and which we can see over here that over here we are given two ids so the ids we are given are student id one and student id2 and for student id one we are actually given the results of six different scores and for student id two we are given the results of five different scores now our aim in this case is to calculate the average for top five subjects uh so this is really important that we need to calculate the average of top five subjects so in this case since we are given six scores we only need to choose the top five scores and not all six of them so this is the key point to understand and we need to build a two-dimensional array in the result and two-dimensional array in the result and two-dimensional array in the result and we need to return uh the result for every single id so uh id number one and id number two in this case we need to return whatever the average we have found for top five subjects and we need to return them in an increasing order based on whatever the given id if we take a look at this example in this example for service id number one we are given following scores since we are given six scores over here we only need to choose top five so we are not going to choose the score number 60 because that is the lowest out of all and we are going to choose the remaining five scores so essentially we are going to do a sum of all these uh scores and we are going to divide it by five so that will give us the average of top five scores for this one and for student id number one the average would be 87 now we need to do the same calculation for student number two now in student number two it's a little bit easy because we are only given uh five distance different scores and we just need to do some of those so we don't have to eliminate any score we can simply do some of those to 88 so now and now we have reached the end of all the student ids and we have found the average so in this case we are going to return a two dimensional array like this and this would be our answer so the first approach we can use is we can actually sort the given input and we can sort the given input based on uh id and after we are done sorting it with using id we can sort it for every single id we can sort it using uh score so that will make our lives easier and suppose we are dealing with the same input so we can sort this input as mentioned based on id and score and this would be the sorted input okay so now since we have the sorted input it becomes pretty trivial that how we are going to actually solve it we are simply going to iterate over the sorted array and for every single id we are only going to iterate over it uh just five times so whatever top five values we found uh we can keep on adding those top five values uh once we have once we reach end of the loop and we are done with the top five values we are going to divide it with whatever the sum we have found with uh value number five and that would give us the average of that particular id and then we will move then if for that id if more entries exist we are just going to ignore all of those cases and then we will simply switch on towards new id and we are going to keep on repeating this process so let's see that in action so basically for id number one we are simply going to uh iterate over so we are going to find top five values which are these values we are going to keep adding them up and uh after that we will divide it with five so for id number one we are going to find the average as 87 and then once we are at this stage and we have already calculated the average if we keep iterating over our array we are going to find that there exists one more entry with id number one which is the 60 and because this is already sorted and we have already calculated the top five entries that we could find over here we don't need to use this case so we can simply ignore the scenario and we would move forward up until we will find the next id now in this case we will find the next id over here this id number two so again for id number two we are going to do the same process we are going to iterate over first five elements and we will keep on doing the sum of their scores and once we get the score we are simply going to divide it with five so even for id number 2 we are going to keep adding all the values divided it by 5 and we will find the average for id number 2 to be 88 now since we have both of these answers stored we can simply return and we can will simply keep on adding a 2d keep on adding these values to a 2 to a two dimensional array and we will simply return this at the end so this would be 87 88 and this would be our answer now we can notice over here that because we had the sorted input it becomes pretty easy for us and we can simply iterate over the sorted array just once and then we will be able to generate this answer now if we calculate the time and space complexity in this case well the time complexity for this case would be uh actually n log n and the reason it's n log n is because though iterating over this input the sorted input is only n work but thing is we will have to first from this input generate the sorted input and that actually can takes a big o of log n time and that is why the overall time complexity is going to be n log n and if we see the space complexity in this case it would be big o of n as well because we are creating an additional sorted array where we are storing all these values now in terms of time and space complexity the next approach i am proposing is also going to be the same time and space complexity so if you want to end your video you can end it over here there is nothing more optimal that is coming your way so essentially in the given input we are basically given two things id and score and the most critical part to solve this problem is actually to identify top five scores for every single id ah and in order to achieve that we have already tried sorting method like the thing is there exists a better approach and in that better approach what we are going to do is we are going to create a hash map now inside the hash map we are going to treat id as key so key would be id and inside the values we are going to keep track of whatever the scores we are given for this given input the thing is the way we are going to keep track of the scores is actually little bit interesting we are actually going to keep track of scores in an uh decreasing order so the way we are going to keep track of the scores in decreasing order will allow us to identify the top five scores in this case that essentially for this course we will have uh some sort of queue or list and we only need to select first five element and we can ignore rest of them so let's see that what i mean so suppose in this case we start iterating over this uh this input and we will first of all check that whether id exist in this new hash set if it does we will update the value in the score if it does not exist we will add the value so initially we find that the id is one now id number one does not exist so we will create an entry over here that id number one and now the score we are given is 91 so we will just enter the score now again we identify id number one and id number one exist now the score is 92 which means uh that inside the scores we are putting a condition that we are only going to keep the stores in a decreasing order which means that now we will have to update the score like this again we find id number two now id number two does not exist so we will have to make an entry and score is 93 now again the score is 97 so again since we are keeping track everything in decreasing order so we will have to uh replace the values now again id number one now this is 60 so 60 can directly be appended at the end of this uh whatever data structure we have now uh we have 77 again we can append 77 over here this one is 65 for id number one now 65 needs to go in over here so we will have to update the value like this and now this one is 87 so next value is 87 again we will have to update the value like this now next value is 100 so for 100 we will have to update all the values now even for i id number two we have 100 so we'll have to update all the values last one is 76 so we can simply append that value to at the end and now essentially we have iterated over this input we have created this new data structure if you see the qualities of this new data structure it serves our needs essentially we are given ids now if you see the ids they are sorted in uh increasing order so initially this is id number one id number two if we had id number three over here it would be placed somewhere at the bottom if we see the number of scores we are given for this id number one we are given six different scores the thing is they are all in decreasing order which means that since we are only worried about top five scores we only need to select first five entries and whatever the remaining values we can simply ignore that same we are going to do for this well number two that we are only concerned with this top five values and if there existed any other values we would have ignored that but that is not the case in this scenario and now it becomes really easy for us to identify that what is the average of these five values and we can simply do the sum of them and divide it by five and whatever average we find we can just create our answer uh two dimensional array and we can simply put it over here so that for value number one the average is going to be 87 for value number two the average is going to be 88 and this would be our final solution now if we see the time complexity and space complexity in this one uh first we will have to identify that how we are going to implement all of this over here and the way to implement this is actually a hash map but the thing is we are directly not going to use a hash map we are actually going to implement a tree map over here and why we are choosing tree map because stream app has a property that it automatically sorts all the values based on its uh id or key so since we or we already need that so we are good with that now in terms of the second property for this tree map we will also have to see that how we are going to store these values now these for storing these values the important property we need is that at any point we insert any value we will need to insert it in the right place and we will need to maintain the decreasing order in this case so in order to maintain the decreasing order the best data structure to use this is to actually use a priority queue in this manner and in the priority queue we are actually going to uh flip the basic condition like originally in the priority queue whenever you store the value all the value gets stored in an increasing order but thing is over here since we are using max heap we are going to need decreasing order so that's why we are going to revert whatever the entry we have for this priority queue and this is how we are going to use an additional data structure to solve this problem so now if we calculate the time and space complexity for time complexity essentially we are going to do big o of n log n work in total because uh first we will have to iterate over this input that takes n work then we will have to create this tree map and fill in all the values uh also we will have to maintain the priority queue that takes n log n work and uh in the end we will have to generate this answer so this takes and work because we will have to iterate over whatever this tree map is so the biggest the longest work we are going to do is going to be n log n and in terms of space complexity we are creating this additional data structure to store all the values so that's why we are going to use uh we go of n as additional space complexity so if you see this is also same as our sorted uh approach like time complexity and space complexity are not different at all the thing is in this approach we are actually doing things pretty smartly and as mentioned like suppose rather than in this case we are given the problem for student and scores suppose we could have been given the problem of uh any particular player and their goal scoring average so we need to calculate something related to that or we could have given scenario where any company's stock performance over the last five years and we need to select the top performing four quarters out of amongst those five years for all the companies and we need to return them in a sorted manner like these are all the different ways where how this question can be framed but we can actually use it and provide the answer using this max heap concept also there is another way to solve this problem using min heap so let me know in the comments if you want me to solve the min heap as well and i can also show you to show you that approach first of all we are going to create our tree map where in the key we are going to store the id and as the value we are going to store a priority queue we are going to name it scores now we are going to iterate over the given input array and uh we are going to store all the values to our tree map so the first value inside the given input array at the zeroth index is going to be id so we are going to create a new variable called id and the second value is going to be score so first we are going to check that if the current id already exists inside our hash map or not and if it does not exist we will add it there and we are also going to initialize a priority queue to manage the heap property where we are going to store all the values in a decreasing manner and in by default all the values in the priority queue are stored in an increasing manner so this is the way to reverse that order i'm sure that different languages will have different formatting but that is the general idea and once that happens we are going to update the value of scores uh score for every single id okay now this hash map should have all the values stored and now we simply have to iterate over it and generate our answer so first we are going to create a list of integer uh where we are going to store all the answers now we are going to iterate over the new hash map that we have created for every single id we are going to calculate the value of sum so initially we are going to have the value as zero and now we are going to iterate over the first five elements inside the priority queue and every single time we are going to increase the value of sum and since this is a queue we are simply going to poll values every single time and once that is done we can simply and we can simply store the results inside our list that we had created and for the sum we are going to divide it by 5 because we need to store the average okay so now we are done with all our calculation now we simply need to uh create a two dimensional array and store the value of whatever the answer we have found and return that so we are going to name it as answer array and now we will return the this newly created answer array and yeah that's this should be our answer let's try to run this code seems like our solution is working let's try submitting this problem okay our submission works pretty fine and i would be posting this code in the solution or in the comments you can check it out from there and you
High Five
divisor-game
Given a list of the scores of different students, `items`, where `items[i] = [IDi, scorei]` represents one score from a student with `IDi`, calculate each student's **top five average**. Return _the answer as an array of pairs_ `result`_, where_ `result[j] = [IDj, topFiveAveragej]` _represents the student with_ `IDj` _and their **top five average**. Sort_ `result` _by_ `IDj` _in **increasing order**._ A student's **top five average** is calculated by taking the sum of their top five scores and dividing it by `5` using **integer division**. **Example 1:** **Input:** items = \[\[1,91\],\[1,92\],\[2,93\],\[2,97\],\[1,60\],\[2,77\],\[1,65\],\[1,87\],\[1,100\],\[2,100\],\[2,76\]\] **Output:** \[\[1,87\],\[2,88\]\] **Explanation:** The student with ID = 1 got scores 91, 92, 60, 65, 87, and 100. Their top five average is (100 + 92 + 91 + 87 + 65) / 5 = 87. The student with ID = 2 got scores 93, 97, 77, 100, and 76. Their top five average is (100 + 97 + 93 + 77 + 76) / 5 = 88.6, but with integer division their average converts to 88. **Example 2:** **Input:** items = \[\[1,100\],\[7,100\],\[1,100\],\[7,100\],\[1,100\],\[7,100\],\[1,100\],\[7,100\],\[1,100\],\[7,100\]\] **Output:** \[\[1,100\],\[7,100\]\] **Constraints:** * `1 <= items.length <= 1000` * `items[i].length == 2` * `1 <= IDi <= 1000` * `0 <= scorei <= 100` * For each `IDi`, there will be **at least** five scores.
If the current number is even, we can always subtract a 1 to make it odd. If the current number is odd, we must subtract an odd number to make it even.
Math,Dynamic Programming,Brainteaser,Game Theory
Easy
null
139
hello and welcome to another video today we're going to be working on word break in this problem you're given a string s and a dictionary of strings we're and you want to return true if s can be segmented into a space separated sequence of one or more dictionary words note in the same word in dictionary may be reused multiple times okay so for example first we have leak code so if we have the code here and our words are leaked and code we can see that we can obviously separate this right because we can break it into two so if we have like we can separate it like this that part is pretty straightforward and we can use the two words okay our second word is Apple pen Apple so Apple pen Apple and the same thing we can obviously you know break that down so if we have apple and apple we can break that into all the words we have and then finally for the last one we have let's write that number here cats and dog and if we try to separate that so we have cat and we have cats let's maybe try cat so if we try separating with cat then we do have the only word we can use then is sand and then we have this OG at the end that we can't do so we have to go back so maybe we could try cats and now the only word we can use is and but then we have this OG again so no matter what we have this like issue that we can't get it to work right so this is going to be false so you can kind of see from what I did there essentially so let's look at this cats and dog example one more time right so if we have cats and dog essentially what we're doing and we have the letters or we have the word cats dog sand and Cat this like really helps us get a good intuition of what we're doing essentially we're trying to break this word up any way we can and get a word that completes so essentially we're starting like here so let's make this bigger maybe right so let's take this cats and dog hopefully we can take it and make it bigger I can do that and let's bring it over here there we go so we're trying to like start over here and we're saying okay let's just go through this array and see how we can break this down so we could use cats okay if we break it down with cats then we have this then we're over here at this index and we can use the only word we can use here is and then we break it down we're here and we can't do anything there right so if we then we have to like recursively go back and say okay that didn't work let's try something else right cats didn't work dog obviously isn't going to work because the word doesn't start with dog sand isn't going to work and is it gonna work so we have to use cat so we break it with cat then we check over here what's the only word that works here it's sand and then we have this OG again which is a problem so that's our algorithm you know kind of like just you know let's just write that down so start at an index Loop through the available words and keep trying to cut with that word and then if we can recurse if not go to next word and our goal is to go through the whole string right so our goal is to end up at the very end of the string and it all needs to be cut up into pieces that's our goal so if we just do that without anything how long would that take so actually you could pretty much do this and if you actually do that right you that would actually work except you need one more step which is you need memorization so you could literally just start here and you could say like okay let's just go through let's go through all these words wherever index we're at let's try every single one and if we ever get here then we say all right we did it good job and so that's actually what we're going to be doing but we're going to add a caching and that's actually pretty much the algorithm um that's literally all it's going to be so we're going to have a recursive algorithm now let's just write the state right so we're going to have a DP algorithm let's write the states so let's write the states we're going to have a DP and let's write well you know our variables in our state and things like that so parameters all we really need is just the index we're at right pretty straightforward okay what's our base case is the index is length of s that means we're done so we can return true now we also have a visited and in this case we actually only need a visited set because if you think about it there's if you ever get a true that means you were able to parse the whole like the whole word and we don't need some optimal parsing we're not asked like parse this in as little words as possible or as many words or whatever so if we ever actually get a true then we'll be done so we only need a visited set meaning like if this index is in the set that means we tried from there and we failed so it's going to be a visited set instead of a visited hash map as normally and what's a recursive case try every word in the words array to see if it fits and then if it does let's reverse an update index and that's pretty much it so we're just going to do that we're going to have a visited set and if we ever get a success if we ever hit the base case then we're done because we're not asked that we're not asked to split this up in some optimal way we're just asked to split it up and if it's possible or not and it's actually gonna be pretty much it so now we have to start coding now that we know kind of what we're doing we're essentially doing like a brute force with normalization and that's pretty much I think as good as you can do for this problem you might be able to do something like a try but this works too so and this is DP and I think DP is better than a try I think try is one of those like if nothing else works then use a try everyone tries to avoid the try Okay so let's do that so we're gonna have a visited set and then we're going to have a DP function have an index just call that I and we're going to say if and I actually want to do initialize this because I'm going to use this so let's just say length or something equals length s minus one because we do need to actually check where the last variable is and I'll show you where that is in a second so if I equals length s that means we're done that means we've hit success so we can just return true here okay now what are some other cases so if I in visited we can return false because everything invisited is false because if we ever hit a true we're not going to store it in the visited we're just going to return all the way out so we're going to return false there now we need the recursive case so the way we're going to do this is we're going to go through every single word in the word dick so we can say for word in word dict right and then we're going to need to match the letters so essentially we're going to match letters in the word dict two all the letters in the word but also think let's think about this case let's say this word Lee is actually like Lee and then a thousand more characters and we're at this character so we don't want to be comparing here and then just be out of bounds that wouldn't be good right so we're actually going to check is our string even long enough to hold this word and if it's not then we're just not even going to bother checking so that's what we're going to do here so we're going to say if I Plus and length of the word so that's going to be word minus one and the reason it's minus one if you think about it so let's say we're at index 0 and the word is two characters long what's the last character of the word well the word is going to fill up zero index 0 and index one so the last character is actually going to be at index one so that's what it's length of the word minus one this would be minus one so if I plus the length of the word minus 1 is greater than length this length variable here that means we're out of bounds for the string so we don't need to check this word so we can just say continue here otherwise let's go through the word so we can say four J in range length of the word now we can compare character by character so if uh what are we at we're at s i plus J right so let's say we're at we start at index 0 and this word is like five characters long that means the first character will be at index zero then the second character will be at zero plus one zero plus two zero plus three and you get the point so that's why you have this I plus J because you're essentially you that's where you need to be looking okay so for I if you could also I think there is literally a method to check like if there is a word like if you give it a starting index and you give it a word it will actually check for you like is that a match but I'm just doing this way because you might not be allowed to use something like that you know you want to be able to come up with it yourself so essentially if s i plus J does not equal uh word J that means there is no match so we can just break here and then move on to the next word right we don't need to keep checking the rest of this we're done now we finally need one more check and that's if the last character is so if J uh I guess this would be if J equals length word minus one that means we've actually checked every single character in the word and every single character in the string and they are true so if they are true now we need to do our recursion right like let's say we did this lead so we compared lead to this it's all good now we need to call DP with the next index so we're going to do that so we can actually have another if statement we can say if DP of and then this is going to be I uh this is going to be I plus J plus one right this is the current index we're at we need to go to the next one so if DP I plus J plus 1 I believe let's just double check so let's say the word is two characters long so we would be at character one for the next one and then this would be uh yeah I think that's right this would be I plus one and then this would be plus two so I think that's correct okay so now if this is true that means we've successfully made a break so we can just return true here we don't need to like save anything that's why I said we don't need to have a hash map here okay and if it's not then we're just done with that loop we're done with the iteration of the loop now finally when we went through every single word if we didn't find anything now we just simply say visited dot add this index meaning if you ever get to this index again this is like a no-go this just fails and we can like a no-go this just fails and we can like a no-go this just fails and we can return false here because you can get to the same index multiple times because let's say we have like leak code but then you have like um apple or something leak code right where you have these lead encode words but then your other words you can get here multiple ways so let's say you also have like uh like app and l e but then you also have um like you know a and then pple right so you can get there two ways you can go apple or it can go Apple this way and so you're gonna get to the same part multiple times so it doesn't really matter how you got here all matters is you did so now we need to do a return false here and now we just need to call so we need to call DP at index zero return that so we're going to return here and hopefully that's all correct okay it looks good so far okay so you can see it's quite efficient and uh yeah and so let's think about the time and space complexity here and we're going to think of the time and space complexity in terms of probably characters is a good way to do it right like what like imagine you know there's some number of characters what are we actually doing because yeah that's probably the best way to do it for Strings so let's think about that so time what are we actually doing well let's think about it so first of all how many states do we have so we have length s state so that's just going to be like we'll just call that n right like this can be anything in s okay now every single time we are looping through every single word in word dict and so let's just say that's like times the number of words right and also we are comparing every single letter in every single word to the string so worst case scenario we have to check the entire thing so let's just say you know this would be like worst case like Max of words or something like Max this would be like the max length of a word something like that right that would be the time essentially you're saying like Okay we have to go through the string we have to go through the all the work all the words so like this is word dict and then also we have to compare character by character so we actually have to go through every single character in every single word whatever that is right so let's say every single word has five characters and there's 20 words whatever like a hundred so technically we could write it as well like this so we could write it like n times number of characters total in word dick that would also be fine it would actually be like more yeah no actually that would be correct something like that worst case scenario you'd have to check every single character in the word dick every single time for every single state so it's something along those lines and if we actually look at like how long that would be so this would be like so words like Words length is like thousand and then everything has 20 characters let's just say that's 20 then s length is like 300 something along those right so how many zero is that three six zeros so it'd be like six times ten to the six or something roughly would be worst case for these constraints something along those lines and so let's go through the space so the space is a lot less because we only have a set and it's just going to have booleans right so this set only has booleans we're not storing like we're not storing any um anything else we're just storing booleans so this is actually all then um because you can only have n States that's like oh of like 300 or so in this case not that bad but yeah so it's important to recognize you need to set instead of a hashmap for to say some space and you because you can recognize that like one successful State means you're done and that's going to happen with a lot of problems like one success means you're done then you can use a set instead of a hash map because you're basically saying okay well we don't need to see the value at all of these they're all just going to be false because if we ever hit a success then we're done but yeah that's gonna be it for this problem hopefully you enjoyed it and if you did please like the video and subscribe to the channel it really helps grow it and I will see you in the next one thanks for watching
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,973
Hello friends welcome to my channel let's have a look at problem 1973 count nodes equal to sum of dissidents in this video we are going to share a solution based on recursion first I'll read through the statement to digest the problem requirements and then we share the idea and explain the codes so first the statement given the root of a binary tree returned the number of nodes where the value of the node is equal to the sum of the values of its descendants so here a descendants of a node X is any node that is on the path from node X to some Leaf nodes the sum is considered to be zero if the node has no descendants so here are two examples so three examples in example one so the output is two so here is the explanation for example for the root note 10 so the left subtree have sum that is six registered tree have a sum that is four so six plus four equals ten so we get one quantity then for the super tree rooted at the node map is value three so we have two Leaf nodes two and one there are also um single node trees so two plus one equals three so this Double Tree is also a valid for one so we can't we increment the counting by one so we get a two so this is example one so in example two so um we have such a binary tree so you can examine that there's no tree such that the node value equals its descendants value sum so the return is zero so in example three so the return is one so this is actually a very special one so there's a single node as the node value is also zero so in this case we're going to return but right the reason is that if there's no leftover tree and tree so we regard that there are corresponding sums are zeros so zero plus zero equals zero so we return one so however if the root value is not zero then we're going to return 0 right so this is example three so before we look at the idea let's look at the constants so the number of nodes in the tree is given by the closed interval so 1 and 10 to the power of 5. so in other words the 3 overall is not now and the Never node is bonded above by 10 to the power 5 which defines the problem sets outbound exactly the note value is non-negative exactly the note value is non-negative exactly the note value is non-negative so and it's bounded above by 18 to the power 5. so with that stats so we are ready to look at the idea and the coding so here we are going to use recursion the reason we are going to use recursion is that it's effective here and also so when we meet problems with binary tree so binary tree itself can be defined recursively or in other words it's a recursive abstract data type so recursion is a natural suit so idea is very straightforward so for each three node which also represents a tree right so we compute the three uh some three some value corresponding to every node in the process we could up this condition so for example if we examine a tree rooted as node if node value equals the left subtree sum plus the respiratory sum then we're going to increment the counting by what so as we are going to uh compute the three values sum so here is the sum let's read so the recursion relation is actually very simple so let's F so compute the answer 3 corresponding to node the sum right so the um the tree of the value sum for the whole trade so this is the other interpretation then we get F node equals node Value Plus F note left plus F know the right so in plain English it means that we want to compute the three sum node values sum so we're going to compute the root value and then compute the value corresponding to the left tree and corresponding to the rest of the tree and then add them together so right so that's the simple recursion relation so with that's done so we are ready to look at the code to look at the coding so the coding actually so for in order to make it effective we're going to introduce an attribute let's call it self result that's going to do the counting rate so we are going to write a helper function to do the above job for each subtree node for each node we are going to compute the three node value sum corresponding to that three node or the corresponding tree so in the process actually we can do the update for this result so now let's look at the hyper function so I can call this function f so if you pass a node to this the function f will compute the three sum corresponding to the three represented by the node or root so in the process we want to do another thing that is update the attribute result self result right so this way as long as we finish writing the hyper function we just need to make a function call and then return the final state of the attribute that's it so with that stage let's first treat our Edge case not educate a base case so if not root so in this case so we are going to return 0 right because there's no there's a number three so the corresponding sum is interpreted as zero so this is more we are using more like is a stop condition for our recursion call right so the in other words is the best base case so with that done so actually we can get the left and the rest of the tree sum that is f root left F root to write and then so in the process we are going to do a check right if root value equals left plus right and then this node corresponds to a valid uh content so we're going to increment the result by what the attribute that one and next what we're going to return is root value plus L plus r so that's the F itself actually did two things first is computes the um the node value sum and also in between we do updates right this updates actually is what we are divided to divide so with that said actually we can call this function so this we can call this F root so this function Returns the tree value but you know we do not implicitly use this for the return so let's use dummy thing so next we are going to return the self result because as we call this function so this attribute will be automatically updated during the recursion process so that's it so this actually forms a complete format of solution to this problem so now we are ready to do the check it passes the first example now let's look at the generic case it passes all the generic cases I guess um that's about it for this specific problem actually here the problem logic is sort of straightforward so we will uh we will stop here for this video thank you
Count Nodes Equal to Sum of Descendants
count-nodes-equal-to-sum-of-descendants
Given the `root` of a binary tree, return _the number of nodes where the value of the node is equal to the **sum** of the values of its descendants_. A **descendant** of a node `x` is any node that is on the path from node `x` to some leaf node. The sum is considered to be `0` if the node has no descendants. **Example 1:** **Input:** root = \[10,3,4,2,1\] **Output:** 2 **Explanation:** For the node with value 10: The sum of its descendants is 3+4+2+1 = 10. For the node with value 3: The sum of its descendants is 2+1 = 3. **Example 2:** **Input:** root = \[2,3,null,2,null\] **Output:** 0 **Explanation:** No node has a value that is equal to the sum of its descendants. **Example 3:** **Input:** root = \[0\] **Output:** 1 For the node with value 0: The sum of its descendants is 0 since it has no descendants. **Constraints:** * The number of nodes in the tree is in the range `[1, 105]`. * `0 <= Node.val <= 105`
null
null
Medium
null
257
hey folks welcome back to another video today we're looking at question 257 binary tree pads the way we'll be approaching this problem is by recursion um anytime you see like a binary tree question um this high probability that it can be solved by recursion and this is not a very different case we can use recursion as well so let's get started the first thing you need to do is actually cover the base case right so if um root is equal to null you just need to return an empty list so let's actually initialize that list of type string and let's call it result equal which is of type and arraylist awesome so if root is equal to null um you would just shoot down I wonder if it is empty if we have to um actually add something so okay so let's just do this so result dot add um just an empty string and then in the end you'll just rip down result awesome so if that's not the case um you need to call a method that's recursive so let's call it get next node for path so there are a couple of things that you need to start off with you actually need the root value then you need the result itself you don't really need the result if you actually move this outside the method uh but since we actually have it in centimeter and it's passed by reference that's fine and the other thing uh you need is a string it's already a manipulating so that is a recursive method that would write in a second and in the end you just need to return to result as well awesome so let's write the recursive method uh private void since we are not returning anything and then let's just copy this and all right so you have to type three node and the name for that is root um you have the resulting list let's call it fresh and then you have the string itself okay awesome the first thing that you need to do uh is you need to know how to call the recursive method right and when do you know to call the recursive method we need to call the recursive method if the given root has a left node like a left child or a right child if it doesn't have a left child or a right child you know that we've reached the end of the path so you can just um add the string that you've seen so far to the resulting list so let's do that so if root dot left is equal to no and root Dot right is equal to null what we do is you just add res Dot and SDR yeah and you leave it as is and then you check for others right so if root dot left is not equal to null what you need to do is you need to call this again right but you need to call this on the left note and you the resulting list just stays the same but the string you need to um add the value that you're seeing right now at the other root and then you need to add this like arrow that is given to us right here so basically what you're saying is that if we know that the next PATH like the next PATH which is like going downstairs does have um it does have a value we need to add the current value that we're looking at on the arrow and then the same goes for the right as well so let's just do that awesome so I think that is actually all we need so this keeps repeating um till there are any notes left and once all the nodes are done it will exit the recursor method since none of them are actually calling it and then you just return this like the resulting list okay awesome let's try compiling this and see if it's okay all right of course all right let's try that again over there did I mess up here what do we need one more yeah I think we need one more let's try that again hmm so sure I think oh okay so basically the string that you need to add here is string plus root dot value because we're not really adding that anywhere so wait okay I think this should be right that's the only thing I missed I think everything else should be good hmm we see one here this past so fruit is equal to 91 what is it your address and string place for that value is not equal to now dot left Value Plus oh I see I guess that's the problem then close this because this was causing a problem okay now this should actually be good all right let's try again third time's a charm okay all right obviously errors all right so let's try at least getting seven like this all right so that solution does pass all the test cases so let's talk about this based on the time complexity of the entire solution is of n since you have to go through all of the nodes uh individually to um get to get all the parts and then the space complexity is also off and um since you do need an entirely new data structure to store all of the paths awesome if you have any questions please let me know in the comments below don't forget to subscribe to the channel and like the video I would really appreciate that um thanks so much and I'll see you folks on the next video peace
Binary Tree Paths
binary-tree-paths
Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[1,2,3,null,5\] **Output:** \[ "1->2->5 ", "1->3 "\] **Example 2:** **Input:** root = \[1\] **Output:** \[ "1 "\] **Constraints:** * The number of nodes in the tree is in the range `[1, 100]`. * `-100 <= Node.val <= 100`
null
String,Backtracking,Tree,Depth-First Search,Binary Tree
Easy
113,1030,2217
883
yeah hi hello everyone I'm an independent member today I will introduce to you a math problem with the following formula: the you a math problem with the following formula: the you a math problem with the following formula: the area of ​​the projection of a area of ​​the projection of a area of ​​the projection of a 3d cube we will go into the details of the problem. As follows, we will be given a box, a two-dimensional array with n rows and box, a two-dimensional array with n rows and box, a two-dimensional array with n rows and n columns and we will be given a ruby ​​block whose dimensions are long but vertically and ruby ​​block whose dimensions are long but vertically and ruby ​​block whose dimensions are long but vertically and horizontally high, which is a powder nucleus like 1 for the equivalent function. With xy&amp;z, in the for the equivalent function. With xy&amp;z, in the for the equivalent function. With xy&amp;z, in the oxyz coordinate system, each value v at the value of row i column j of the led matrix will represent a tower consisting of v ruby ​​blocks that are placed tower consisting of v ruby ​​blocks that are placed tower consisting of v ruby ​​blocks that are placed on top of each other at the position of the box at position y&amp;j now let's at position y&amp;j now let's at position y&amp;j now let's see the projection of these ruby ​​blocks above the one these ruby ​​blocks above the one these ruby ​​blocks above the one at home the oxygen coordinate plane has oyz news and a projection just a projection will have a shadow that we can connect them together to form a shape a 3 dimensional shape we can form a 3 dimensional shape into a shape or dimension and there we will see get the shadow when we look at this ruby ​​block when we look at this ruby ​​block when we look at this ruby ​​block from above or from the front or from the side on the side, we will return the sum of the areas of those three projections. Notes is that we will return to the total area of ​​those three projections, area of ​​those three projections, area of ​​those three projections, according to the view above, actually top down from the front and standing from the front looking out and from the side on the side and then we will go to work. good example by good video it has this picture that is easier to visualize then we see that in the position no then we have a ruby ​​block only a ruby ​​block like ruby ​​block only a ruby ​​block like ruby ​​block only a ruby ​​block like has a height of some must be The tiny thing here and there, if there is a dimension in the zero position, there is a ruby ​​block, zero position, there is a ruby ​​block, zero position, there is a ruby ​​block, the kobe ruler is one and the same. We see that the child is in position 01, which means the line has no column, then we have 2 ruby ​​blocks overlap each other, here we ruby ​​blocks overlap each other, here we ruby ​​blocks overlap each other, here we see that it is these blocks because there are two rubies overlapping each other so it is twice the size of the previous block and then in the 1st position around a column otherwise there are three rubies. Then here there are three ruby ​​blocks, it Then here there are three ruby ​​blocks, it Then here there are three ruby ​​blocks, it goes around 1 plus 1, then there are four, there are rubies, the tallest tree here and there, you see it, the tallest tree is here, now we're close to finding the picture. The projection of these three guys is on the first coordinate plane which is the xy coordinate plane ha this is the oxygen coordinate plane which means we look from the sky so we should always look down huh look slide top look down look at the scene 90 degree angle, we see that looking straight at a 90 degree angle, it is only a square of 4. See 4 consists of four and these four vertices, right, four vertices, but we look straight at 90 degrees so we I don't differentiate between setting the heights of those different vertices. Actually, as you can see, here the ruby ​​cube is one high. This is high. Here, the ruby ​​cube is one high. This is high. Here, the ruby ​​cube is one high. This is high. Here, the Rubik's cube a3 and here are also four high. But I'm looking at it from above 90 degrees. Looking down, I imagine it's just a square block like that, so we have a shape. Now let's imagine the next thing we'll see is that the axis is at least z, then translate to z. first we look across look from here we look over who wins here look out here we look over just it out look take a look less directly from the front and straight into the sandals then we have this meet The less straightforward sister calls z, so it's column 3 and column 4. Now I can only see column four and three, it's lower than column 4, right? Shouldn't it be this? No, this is the only number 14. Right now, looking straight in this direction, we have column 1 and column 2. We can see that we can only see column two and it's covered by the pole or is it covered. Then we look straight up and look in. This is the image that after we quickly looked at the acting quality, yes, the last image is the shadow image, so we can look horizontally, do you think we can see it from the hospital photo, we can see it directly. The weak side is to look straight at it, so we have column 4, it will still be covered by this column two, which can cover 3, column 4, there is currently one and four, and this column one is covered with column 3, so We still have three left, so we still have the old lady here, so now our task is to calculate the area of these three shapes and + total back to the these three shapes and + total back to the these three shapes and + total back to the modern program, the area of ​​this shape modern program, the area of ​​this shape modern program, the area of ​​this shape is 4 areas. The product of this figure is that we have to come to the number 1 2 3 4 5 6 2 6 1 2 3 4 5 6 7 + come to the number 1 2 3 4 5 6 2 6 1 2 3 4 5 6 7 + come to the number 1 2 3 4 5 6 2 6 1 2 3 4 5 6 7 + 6 + four is you 17 oh 6 + four is you 17 oh 6 + four is you 17 oh stupid then similarly in example 12 is example 3 or example For example 4, example five, you can take out a pen and paper and draw this picture yourself. I have already imagined it. Now we have grasped the requirements of the test. Now we will go through it. As we will go through the algorithm to think of an algorithm to solve this problem, as we can see, these three pictures actually call us a lot of ideas, right? This is exactly what I think. These are also three types of suggestions for the answer to what you have that will solve this problem. Okay, now that we know that we need a little bit, we can see that if we have a hope Loc , let's go through the number of rows, then there are , let's go through the number of rows, then there are , let's go through the number of rows, then there are 11 nested filters inside, going through the number of columns, we see that we will destroy all the elements of the original two-dimensional array, right? original two-dimensional array, right? original two-dimensional array, right? the areas of the first rows, you see the area of ​​the first image you see the area of ​​the first image you see the area of ​​the first image , let's just go through an element , let's just go through an element , let's just go through an element so we just need to add the area of ​​this image, you add one of ​​this image, you add one of ​​this image, you add one unit then the you see we call almost the three matches we are two times two then in the end we go back and forth I will add 1 plus 1 is the last shape area of ​​figure 4 why because we area of ​​figure 4 why because we area of ​​figure 4 why because we but do From top to bottom, we don't care how much the value here is. In America, you're here and it's not impossible. We just need the value here and it's bigger. Otherwise, it's like I'll be able to see an area of ​​11 square meters at the hospital for area of ​​11 square meters at the hospital for area of ​​11 square meters at the hospital for you. We don't care about the US height, it's okay, the cold, the value at position a, y position. of the calcium clothing line if it is larger or not, I increase the area here, it is easy to deduce the area of ​​this image, it is very deduce the area of ​​this image, it is very deduce the area of ​​this image, it is very easy to calculate it, just go through all the elements each time to get the value. If it's larger than that, then I add a value and I get these pictures. Now I only have this picture, so for this picture, I look a little and see that I just need to take out the price. maximum value of the number of the department when we just need to get the maximum value of the department, that is, when we enter the hospital, we will have a maximum value through the maximum value color column of the row, we see that we only need to get the highest value of the item according to the column, let's say in this case we see that we have a column of two strange columns, the column of value is two If the column has a value of four, we just need to take its maximum value and we will get back four. In the column values, you can see that this is the price. The largest value is of the line ha, we see that this whole line reads as round 1, there are 1, 2 sisters, we just need to take that the largest sister is two is what you want to put and now The hour of three and four has also taken the maximum value, strangely 4 of which is four. Now this is this picture, that is, we find the maximum value of the circle of each line and then we weight it again or you guys. As you can see, if we add them together, this largest value is four, so the most important thing is two. 4 plus two makes 6. And in the picture here, it's the opposite, that is, we take the largest value of the column, then we The first column is a lady, right? The aunt in the final position is 13, so because it's covered, I'll take the number 3, so I'll just take the largest value, which is three, on 24 days. Let's just take sister four, the largest value is three and strange four is 7, then the problem here becomes simple again, so each time we go through each prince of the column, we increase its value. If the value of some position y&amp;j is larger than increasing by one position y&amp;j is larger than increasing by one position y&amp;j is larger than increasing by one unit then we will calculate the largest temporary value according to the column then we will again evaluate the value at the positions of the ring. That's the largest column, and finally we get the total sum of all 3 images. Okay, then I'll go into the settings using the callback programming language. As you can see, we'll have a depth equal to If I don't declare a variable from deep then I wo n't calculate it, why won't I get j later and now I will declare a loop to create my learning as y rose then I go through all the lines with the last key of Okay, now I'm going to call a declaration of a variable, let's say Lam is equal to 0 and Straw is equal to zero. I mean, around this column, I keep the largest value along the line. Why tie the hottest wire to the big sister with the pole and then we will have a second set up gate, I call it reedy di and value manh viet through this perch mine, I will browse each gate for each strawberry. Looks like you're the only one wondering if the value of the suitcase is big or not. If you ask about this first picture, I'll increase the plus sign by one and then go to the second picture. The one in the second picture is a strawberry, right? Or do I have to get the value of the one and now I take it and kill it at the position of the Y column that is larger than the strawberry? This vegetable means what to do. a yeah I have this perch it has the same name so maybe we should read this ha this is the only thing I'm worried about is my eyes going out this time and I've lost my pro then here I'm bigger than the macro if it's big then The face then I give this checkered eye and it equals the list at position j and y. Well, we are comparing, we want to take advantage of these filters, so we change the y&amp;j here and it will If we change the y&amp;j here and it will If we change the y&amp;j here and it will If we go back, we'll take the perch, but for the warehouse, it's too easy for me, my children. I'll just take the current suitcase that's larger than the one, so I'll give it the same amount as the warehouse and risk it, then after Let's compare this filter powder and we will get three pictures. Two, we will get the value of not yet the full value of these guys but it 's only half but this total 's only half but this total 's only half but this total is still correct. So if we deposit then we will get zezo plus equal to zezo ro plus equal to green dich eye microphone here is macro and eye got it so we have installed the math department now let's try to run Let's see the return results of the program. If you're here, then you must be out of trouble because Marco Reus is here. I said that, so we have succeeded. For example, one return result is five results. return more wishes request is also the year we try to create a nick to solve the remaining examples I say like that we have successfully solved all the remaining examples then we analyze the logic of the math axis Hey, the complexity diagram of this algorithm will be we see that we call n a number. A while ago he said that you said n right, so we infer that it is n, the complexity of the algorithm, but I don't know everything. I have now given rows equal to the number of columns yeah and then there is also storage space or oh one we will use some variables then say constants and thank you for watching the video If you find it interesting and please give me a like, sub, like and share the experience. If you have any questions, comments or better solutions, please write them down in the comments section below the video. Thank you for your time. special and me yeah
Projection Area of 3D Shapes
car-fleet
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes. Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`. We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes. A **projection** is like a shadow, that maps our **3-dimensional** figure to a **2-dimensional** plane. We are viewing the "shadow " when looking at the cubes from the top, the front, and the side. Return _the total area of all three projections_. **Example 1:** **Input:** grid = \[\[1,2\],\[3,4\]\] **Output:** 17 **Explanation:** Here are the three projections ( "shadows ") of the shape made with each axis-aligned plane. **Example 2:** **Input:** grid = \[\[2\]\] **Output:** 5 **Example 3:** **Input:** grid = \[\[1,0\],\[0,2\]\] **Output:** 8 **Constraints:** * `n == grid.length == grid[i].length` * `1 <= n <= 50` * `0 <= grid[i][j] <= 50`
null
Array,Stack,Sorting,Monotonic Stack
Medium
1902,2317
89
Tigers Vitamin When I give you a question and absolutely okay how to define a record your A like if you have 12 2010 90 it goes from one number to two numbers just put one so liberally okay this is gravity is broken and vanshi ho this Vitamin C is there, loot that one son, change of 1 minute, change of your limits M University, this increase has increased, change in this, so if you subscribe in this way, then I will write you 240 and 1510 team, triple 0 Subscribe Gai appointed in the video Here see how we can make it and that we need this trick The front person will say give me the tweeter If I get a name like 0 Submit how it is not only one in a year then we If all four are zero and in front of all three, one will come out and in front of all three, we will put zero in front of all four. Village Yo, if zero is put in front of all four, then I have looted them and in front of everyone, so if these are all cameras but you The weight above this side had changed, the one below it was decorating from here, Wipro Limited was changing, we go from here, we wanted to become a hero, so it is also in these that the breakup changed because it is sitting, because all are starting from zero, the rest is fine. All this is in the voucher itself, it is in all this and it was difficult in the lower limit itself, okay, now I will pick them up again, I will put bun in front of them, we will put one 0000000000 hr, first this has come in front of 10, now let us know in all these There is a big difference in all these and the good thing is that even in 0101 temples, the alliance time is common in both and things became that once. Let's write again, see this, now we will be sorted out, I will complete Krishna's Tripitaka, you want it, we don't have it, we have broken ones, it is okay for those who are broken, if it takes time, then it can be erased, mp3 It is there every morning, no, he has planted Bittu, I am one. Bit I give you two returns and now see how it will make a broken 098. This is that zero symbol has been put in front of them, both of them have taken a limit cup of sugar, then add 108 to it, in reverse, bad, first one has appeared, then 84 has come in front of you. Now these four to five will become eight for humans. 01 I am in front of all of them, I have called you, I have to write in my kitchen, what we said is the upper level, we have been given the next video according to grade-2 of you and minus one, we have been given the next video according to grade-2 of you and minus one, O Pappu. If we have to make my result then what will we do, put a loop in AR result, R string in all results, start our wi-fi, start applying oil, start our wi-fi, start applying oil, start our wi-fi, start applying oil, festival festival festival that I will go to plus rostring, remove art strain AR result dot, O my O my O my 208 If you do then tell me the hotel settings, ok, they are fine, so I have tightened them, look for them here, what should I do now, all school science - when what should I do now, all school science - when what should I do now, all school science - when those days open to zero - - those days open to zero - - those days open to zero - - I will now turn upside down and healthy will be placed on the front. Will make the shirt wet - shirt wet - shirt wet - This is the trend of the base of the shirt, so we two people in it Raghava meanwhile add the result to the best result 0 that this time it happened, it was made by Sonu Nigam's direct magnet, it takes time and a picture to So friend, you must have understood the basic promise I have - pick up the phone, stick the basic promise I have - pick up the phone, stick the basic promise I have - pick up the phone, stick the cover upside down, put it on from time to time, then you will have it from now onwards and that too will remain gravity. You should go for a dedicated mission and have access to it in a year.
Gray Code
gray-code
An **n-bit gray code sequence** is a sequence of `2n` integers where: * Every integer is in the **inclusive** range `[0, 2n - 1]`, * The first integer is `0`, * An integer appears **no more than once** in the sequence, * The binary representation of every pair of **adjacent** integers differs by **exactly one bit**, and * The binary representation of the **first** and **last** integers differs by **exactly one bit**. Given an integer `n`, return _any valid **n-bit gray code sequence**_. **Example 1:** **Input:** n = 2 **Output:** \[0,1,3,2\] **Explanation:** The binary representation of \[0,1,3,2\] is \[00,01,11,10\]. - 00 and 01 differ by one bit - 01 and 11 differ by one bit - 11 and 10 differ by one bit - 10 and 00 differ by one bit \[0,2,3,1\] is also a valid gray code sequence, whose binary representation is \[00,10,11,01\]. - 00 and 10 differ by one bit - 10 and 11 differ by one bit - 11 and 01 differ by one bit - 01 and 00 differ by one bit **Example 2:** **Input:** n = 1 **Output:** \[0,1\] **Constraints:** * `1 <= n <= 16`
null
Math,Backtracking,Bit Manipulation
Medium
717
1,926
Nearest Exit from Entrance is a medium level problem and trust me it is a very simple problem, there is nothing to worry about, so first of all let us write down what Pinku Given is in this question and what is this question number trying to say. If you understand the question from this example, then there is nothing straightforward in this example, Apne is a matrix and wherever Apne is standing is Apne entrance, meaning Apne is given your entrance and what is Apne to do, Apne is your entrance. The shortest path to exit from Takkar has to be calculated and returned. Now what will be the exit? Exit from all the open borders which are given to us, meaning where there is no entrance, on the borders, we have our own exit, so one, our exit here is zero. Kama tu pe ek apne exit yahan pe hai van kama zero pe aur ek apni ek set yahan pe hai tu kama three pe but now it is such that apne can only move horizontally or vertically. Is there any way to go to this exit? To go, you cannot move diagonally, if you come down, there are hendrons below, then you cannot move here. If you go horizontally, there is an entrance here too, then you cannot move here, so basically you If you can never reach this exit, then you are left with this choice or this choice here. If you move your vertical upward, then this one will be reached first, which means this van path is getting completed in the line. If step one is being completed then which is your short test exit i.e. which is the which is your short test exit i.e. which is the which is your short test exit i.e. which is the exit with shortest path. If this is the one, then we will return to this one, that is, we will say that on our path van, that is, on the van length part, from our one. If it is present then what will be its output? Okay, now if we look at the next example, in this matrix Apni is the entrance here and all these are given to Apni from the hidden and Apni object is only one present here, Van Kama Tu Pe is ok. So you do not have any option to go anywhere up or down, even if you first move your horizontal here and then move it horizontally here, you will get your exact path length, so the answer is you are here, it is ok. Similarly, if we look at this example, we are standing here, there is a matrix of only two columns and here we can never reach the exact because the entrance can never be exact and we cannot say that where We are standing here, we will move from there to this side and we will get our exit. Apna can't do this Apna second meaning is minimum van path length so you have to travel to get the exit then Apna will say that mines van hai means find. Ca n't do it here, okay, this is a simple question, I take the example of those who solve it and see that they can solve it, both sides do not have borders, okay, so both of them can go right and by going on both sides, they can solve it. We will see where our answer short test is coming. Okay, so now our punch length has been covered. Okay, after that we will go from here to here and from here to here. Now from here means move from this tree to here. Karne means to move down and this side means to move to the left side, take one part for both of them. This is an add on trick, so apni yahan pe plus hoke path length kitna ho gaya tu ho gaya and apne ko here. It is visible that you have reached your border. If you move this download side, then you have reached your border here. And here you have not received any answer yet. So if you have reached your border, then click on any one of them. From the direction we will tell you to return your answer here, now we have reached the border, okay, then this will be a simple solution to this problem. Now once you code it one by one, you have understood that What to do to Apne, every direction which is possible from the entrance to Apne, like Apni, only two directions were possible here, one is this one and one is this one, if this part is also open, let's assume here this plus. If it is not there, it means there is no break here. If this part is also open, then we go here also and check in all three directions. And in fact, if this part is plus B, it means there is no break here either, this also does not become a plus. Hota Tapan is in the current direction, which is from the four possible directions, go up, down, left and right in these four directions and see where your short text exit is. In this case, your shortest exit is coming here. One set of van path length is coming here. But this is because it is closed, so your shortest object will come here, that means you have to go in all four directions and check where your short testing set is coming. Okay, now let us see how we will solve this. I have come to know what I have to do, now what will I do within this? First of all, I have given my van team, okay, I am going back, it means that this should not happen, have I come back here, I don't have to reduce this, okay, so what have I done? Made this entrance also a break that you can come back here anytime. Now what will you do? I will see in all four directions. One is this direction and one is this direction. Is it possible? If it is possible to go in these four directions then We will check whether there is a border on any of these four directions. If there is a border on any of these directions, then as far as we are concerned, we will return, otherwise what will we do, we will keep going back to the other direction. Meaning, after following them, we will keep going to other parts. Okay So, the entrance was at our place, we made our entrance a bridge, now we will see where our place is, this has become a break, if ours, why did I stop this? So we will see where our entrance is, then we will compare our entrance from here, okay, now we will go up one from the entrance, okay [ praise] and inside this there will be a plus and we will leave it like this, meaning it will become zero here. Okay, so what does Apn do to go up, Apn Is Zero Kama Four valid? Can we go to our place on 04? So can we go to our place for break on 04? If we can't go here for break, then this direction has been canceled. Okay, then we will go to our place and see, so why should we go to our place? If we do our own, we will do plus van inside the A axis, then it becomes van here, and how is it like this, that is, here we have to do zero and van plus, then what is our direction, 1, earn five, okay, then go to our van, earn five. Let's see, there is a break here, so it is canceled in this direction, okay then you will go down, what happens to go down, what happens is that there is a plus van there and how do you let it stay like this from the bike. If you add Apna Idhar then it will become 2 4. Okay, you earn four, can you punch me? Can you go at all, then one is your path, you earn four and one is Apna Path, this one is okay, so let's go here and see. So to go here, what will happen is that we have to keep our X-axis from and keep our X-axis from and keep our X-axis from and minus van in the A axis. Okay, so what will happen is 1 3 Can we go here van Kama three pe han absolutely go. If it is possible, then a van or three is also a valid direction. Okay, so I told you how to go, here I mean, what calculations will you have to do to go in the current direction. Okay, a van or three, I can go on your own. Van Kama Three Pay is fine, then we will check on both your sides whether you have got the border or whether you have got your exam, then on both here and here too, if you have not got your exam, then what will you do with these two? When will we take the same parts as ours? First of all we calculated that 2.2 will be kept then we will keep it as ours. Then we will keep it as ours. Three 2.2 will be kept then we will keep it as ours. Then we will keep it as ours. Three 2.2 will be kept then we will keep it as ours. Then we will keep it as ours. Three is okay then ours because what is in the last is now ours because in the last it is 2 4 meaning this location is now what is ours. I will make this location a break. Okay, I have made this file location also a break and I will move it in every direction. I will try to move it here. We will try to move this Stephen, we will try to move here, okay, then inside this also, we will first move here, we will go back to the entrance, this part is not possible, okay, then if we try to go here, then going here is also possible. No, this is also a break, okay, then Apna will go down, so what happened to Apna to go down, so this is possible and this one Apna is possible, meaning you earn 5, Apna is fine, Apna border has been achieved, so Apna is this one. On the possibility of this, if your border has been achieved on three or four, then what will you do, your direct path, plus van, that means, where the punch length was, here the path length was van, okay, so plus van means, if we go down one more. Apna border will be received that Apna path length plus van means you will return it. Okay, if Apna border is not available here then return Apna and enter these two coordinates. Okay, so what do I put in Apna K? 3 and If you can go to Kama Five, then it will take three directions to reach your border and then what you do is that when this level is completed and you do not reach your border, then by adding plus van to your path length, you will be considered an athlete. Okay, then let's continue like this, Apna completes this level, here too, if border is not reached, then I used to reduce the path length to three, thinking that Apna will be 3G but if Apna border is reached here, then return after doing Apna Plus van. Now once he sees its code, he comes to the function for the court, in the function pen, first of all, what did I do, why did I create mine? Okay, within this, Apna Entrance means entrance, which is the person with this entrance, inside this he created his The zero location of the co-entrance zero location of the co-entrance means both the What did I do? I placed my feet inside and stored it in my store. Okay, then I said that my path is currently seeded. See, standing at the entrance, I have calculated anything and this path itself will give me the answer. Yours is fine, then what did you say that the entrance is, that is, the whole matrix that you have said, then your base entrance is right, do a plus there, that is, make a break there, okay here, these people have used it to depict. I have made a tree but when I have given myself in the question, I have given plus in the question instead of breaks, then what I said is that add a plus to the entrance and make the entrance also a break, I ca n't come back here right. Then I checked whether I have KMT or not. If I have KMT, I will return it like mine van in this case. Let me explain to you in this case where it is not possible to go to your exit. Is it possible or not? If you go to the exact direction then you will go up. The upper direction is not valid. The left direction is not valid. Only this direction is valid. So you will go here. Okay After that he said If you were to calculate from here, how much distance would it take to go anywhere, from here, if you go up, if there is no one above, if you go down, then below is also not valid, meaning, you popped it out of the box and Let us see in which directions it is possible to go, from where we can reach our border, so on one hand, it was not possible to go up, here we went to the left, there was a break here, it was not possible to go down, and here I was a bridge, meaning our If you are not able to go anywhere then nothing will come to you because the directions of all four are not valid and then when you will reach your destination and see why anti and nothing is coming back then you will return your mine van. That it is not possible to go here, that is, it is not possible to bring an exit here, so it is okay to do the same here, and till you do n't agree, that means Tapan created a variable size and inside it because the size was taken, then As long as the size is mine, that is, as long as the size is yours, that is, like here is the entrance of yours, in this example it was possible to go to two places, like this one, which was this one, this is your entrance, okay, so one is to go from here to here. It was possible not from here, it was possible to go from here to here, and one, it was possible to go from here to here, sorry about my entrance, one, it was possible to go from here to here, and one, it was possible to go from here to here, meaning one is on the left and If it was possible to adopt the word down, then we would calculate for both and after that we would add the punch line plus van, meaning we had calculated for both, the entrance was in all the directions, we had calculated to go in all the directions, after that we had calculated. You had done plus van in the path length. It is okay that this path length of yours means that even if you go down here, you will have to walk at least one step, that is why you had done plus van in your path length, now within both your locations Wherever it is more possible, we will go there and see that if the border has been reached then we will return by doing plus van that we have reached our border and there is no border anywhere, then we will calculate for both our directions. Where is it possible to go there, add all those values ​​in K and then calculate all those values ​​in K and then calculate all those values ​​in K and then calculate your plus van that to go to this location at least this distance means one more path length you will have to cover, okay and till there Then I ran it and saw that my current is true, so first of the friend's front, there is my roast inside it and because my friend's problem is stored in the second, I took my role column, then because the value pops, it is okay. What did you take inside? Wait, you took four inside and then got it popped from here, that means it was eliminated from why. Okay, then what did you say that your four directions can sleep? What are your four directions? What can happen is, first of all, you can go to your entrance, up, down, left, right, okay, we will calculate for four directions four times, okay, then we will create a new row in the new room, first of all, we will add the personal of rodiriction inside our row. Meaning, element was zero, apne, road direction was created, vector was created in the beginning, column direction was ok, van four mines [ mines [ mines [ praise] what will become of zero, earning zero, going in the upward direction, calculate from this example, apna to apna If we are going up from here means this is our entrance then from here we mean van kama tu se apan ja hain zero kama tu pe ok 0 2 pe hain apan yahi apan saw kya zero kama tu valid hai meaning we can go here Is it possible or not to go, meaning is there a brick here or not and if there is no break then is this direction valid, means is it valid, is it ok, then to validate, we will come here, to validate, we will see the function, we will say here. What is the row, is it not less than zero, that means it is -1 here, that means it has means it is -1 here, that means it has means it is -1 here, that means it has not gone above this border also, that means it has not become mines, if the row is row, then give less in M, which means I am its size. Okay, the column that is there is bigger than zero but I is less than its size and the break here is also not present here, meaning the break is also not present at this location, then what will we do, we will do it in these conditions. If we pause any 2 meters from it, that is not our valid direction, that is, it is not a valid step, if this is our own valid step, then what will we do, it is our own step, okay, so here also we have put a brick and then What will you do, is there water here, so for the border, I called this function, okay, what will you see in the border, whether the row index has become zero or the overlay index, it should be equal to the size of your mesh. If there is any of these two, then you will do your return and will cry for your similar column. Where is the zero, one is there, it is here, okay, if zero means here, then you will be here, okay. Where is the border in both these cases, sorry, every row is here, every day is zero here, or if it is here, then in both these cases, these are the borders and where is the column zero. Column is zero here. It is equal to its size in the column here. Okay, so both of them also have a border in this. Okay, so you will return your return in these two. If the main size is, the size of the column is either zero or Which is equal in size in both the row or column, then in both the cases, if you return your value, then your return will be false that it is not on its border, then if you have gone above, then the value of that row which is above is zero. If there was zero [praise], then by adding plus van inside it means that we will was zero [praise], then by adding plus van inside it means that we will was zero [praise], then by adding plus van inside it means that we will return the van. How much border has been reached at the first location itself. Apni path length van. Okay, so what will we do if Apna Path has come, meaning this above direction has come to him. We will push our feet inside it is okay and then we will continue to do it for all the locations, somewhere we will find our border, then we will return our border and if we do not find it anywhere, that means our If water does not exist anywhere, then check your mines van. You are absolutely sure. Submit means this is the accepted solution. Hope you have understood. If you understood and liked the video, then like the video and channel. Subscribe and if you have any doubt then please mention it in the comment box. We are always present to solve your doubt. Thank you so much.
Nearest Exit from Entrance in Maze
products-price-for-each-store
You are given an `m x n` matrix `maze` (**0-indexed**) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where `entrance = [entrancerow, entrancecol]` denotes the row and column of the cell you are initially standing at. In one step, you can move one cell **up**, **down**, **left**, or **right**. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the **nearest exit** from the `entrance`. An **exit** is defined as an **empty cell** that is at the **border** of the `maze`. The `entrance` **does not count** as an exit. Return _the **number of steps** in the shortest path from the_ `entrance` _to the nearest exit, or_ `-1` _if no such path exists_. **Example 1:** **Input:** maze = \[\[ "+ ", "+ ", ". ", "+ "\],\[ ". ", ". ", ". ", "+ "\],\[ "+ ", "+ ", "+ ", ". "\]\], entrance = \[1,2\] **Output:** 1 **Explanation:** There are 3 exits in this maze at \[1,0\], \[0,2\], and \[2,3\]. Initially, you are at the entrance cell \[1,2\]. - You can reach \[1,0\] by moving 2 steps left. - You can reach \[0,2\] by moving 1 step up. It is impossible to reach \[2,3\] from the entrance. Thus, the nearest exit is \[0,2\], which is 1 step away. **Example 2:** **Input:** maze = \[\[ "+ ", "+ ", "+ "\],\[ ". ", ". ", ". "\],\[ "+ ", "+ ", "+ "\]\], entrance = \[1,0\] **Output:** 2 **Explanation:** There is 1 exit in this maze at \[1,2\]. \[1,0\] does not count as an exit since it is the entrance cell. Initially, you are at the entrance cell \[1,0\]. - You can reach \[1,2\] by moving 2 steps right. Thus, the nearest exit is \[1,2\], which is 2 steps away. **Example 3:** **Input:** maze = \[\[ ". ", "+ "\]\], entrance = \[0,0\] **Output:** -1 **Explanation:** There are no exits in this maze. **Constraints:** * `maze.length == m` * `maze[i].length == n` * `1 <= m, n <= 100` * `maze[i][j]` is either `'.'` or `'+'`. * `entrance.length == 2` * `0 <= entrancerow < m` * `0 <= entrancecol < n` * `entrance` will always be an empty cell.
null
Database
Easy
1948
1,021
side effects of getting Ajay tied photo gallery, so today we are going to remove turn off parents, what to do on this question, I have given you a basic string of bath on which opening and closing date is song A, okay, only guest. If you have such a racket then you can get it as if you got it with money, it will also be velvet, it will be valid, that means the balance current will be like this, what do you have to do with it, basically the record output is going to be made in two steps, the first step is this. On what basis will you split the track, see the example and for example, if it was at that time, then you can write something like this in the parents of this track, your closing plus your closing, this is valid from both the screens and both of them By adding this, you will get practice in Admit. This can be basically split. An example here is based on this, so it may not be clear that if you submit it in any way, this is the first part and then the second part, then both of these Melted tight invalid but you don't have to speed up as long as the work giving this message is valid like this then you will make that flat, we can spread it on this case, so the opening is closed, this guy has become a part. Plus look at this second part here on the inside, no, these two guys can return, so this is a little less, you have to work only on the top level, we have to go inside and fit it again, this means you will leave so much cloth, this is the first point, this is the second part. You will not work by taking it inside and back. Okay, so the first task is to speed up this and the second task is what to do. The second task is to remove the outermost parents from all these split strings. What are the after mach here? But according to this, tomato is this one, here is this one and here is this one, height specific will go and here on Plus, this will go on Plus, you don't have to pay the full amount, this is Mukesh's, so let's see the example, if it is with Let's see from the next example, okay, this is planet costing. Oh, so if you do two parts from the first task, then this task will be done. Open Close in Amlon Singh. Okay, the plate is done, now this item from this one is on that, now remove this one, so this one. But this is self and term insurance, here you will get MP Singh, this and this will also become MP Singh, if you join these two, then we are the testing answer, there is a single person on this and there is no one here, so this person is going to split. Even after that, there will be only one pet. If something is important to you in which split is not possible, then you will not pet it. Possible mothers, just remove the items in it, then take this anti-complaint remove the items in it, then take this anti-complaint remove the items in it, then take this anti-complaint on Hariom. If you had got it at all, then I would have found it in this. When I did the plate, it did not split further, I am the only person, removed the items, so it is done ok, let me see another example, look at the one who has to make the hotspot for one month, the palace plate is done from here till here, it is ok. That this first task is done, second, hence from here to here, processing, opening, prosecuting, history plate will be bought from here, the third part is its closing, opening and closing project. Okay, look at this whole thing, you do not split fate with anyone. You can, okay this one but this one is here, so this one's foot is here, he is absolutely last here, if you ca n't recite it according to the tight, then this one is first, so many ca n't be, what was the second name, the first commando went. The second task we will do is to remove the items and here the auto Muslims will follow Singh Yadav in the school. If you do your clothing or footer Muslims, then make your closing, opening, crossing clothing tight Abhishek Kumar, then something like this trick becomes tight and this is what you will print. If you want to tell if Tikriya is cancer then on this question the East England which is there can go up to 2010 1000, there is torch light and it will always be a valley and there will be only opening illuminated rackets and nothing else, ok then you can try. Yes, and we will be fine in the positions we get to do, one can do this, now basically if you have this trick, opening clothing and then here is something like this, okay, so we are not going to do the actress plate, okay, seeing what to do. First of all, velvet the Indian Air Force guy and solve it. If this guy is the innermost, then my answer is tight. After this, who is the innermost, then both of them are completely independent. So, even if you solve them separately, one head will remain the same. We will not pack that after this one is the innermost, so this one's incarnation is seasonal, the man has a smile on his lips, after this and this one is outside of all, so we will not write it here, the only work is to look at the file now. What is this, have we come to this worship is neither terry nor made, this note is made like this, then this is made, mute with most deadly is seasonal, so don't make it an answer, do n't write like this here, it is okay, the complete answer will be made like this, then our work will be looted. What is there, make the most profit here and make more, talk about these things, do cancer, when the inner most items become yours, then don't work for it, okay, then we can understand something else to verify this idea, at least for some time. Let's see, like this one, this guy and this Bandhwa, okay, here we have to see the call, so let's see whether this one does this or not, so first of all, this is made, you see, Kinnar Most, we have to process it, but more tomatoes. If it is also tight, then you processed it but did not make the answer, then it is of cancer and distic. Okay, so for this, it is doing the correct work. Who is the most enormous person on this? It was this one, you processed it and made the answer of this. If the person outside was not made the answer then it was not according to these rules, torch light, we do not have to add it, we know that it is working on this also, I asked in my closing, okay, so the investment is according to that, this is all this money. Let us consider these rules, Victor is the one, call it and then invest, this is the one, but do not cancel it, then this cancer was to come, we have seen it before, the right answer was this, it is also working, after all, let's see then. If the person involved in this will go then how is this the innermost, this is a closed Jhala, consider the phone winner mostly is becoming, consider the phone period most is this guy, you center that innermost is this guy, don't do it in this town, there is no one else outside it. The complete answer is here. If you press it once then it will not be able to be plate. If it cannot be plate then it will remain okay. Now tomato two items are the real issue i.e. i.e. i.e. Aishwarya was not there and our answer is okay so basically inner most. Keep solving and when that guy becomes the outermost, then do n't add all these to him, this will work, then all this will go, okay, so how do we write a test, let's take it to identify what should be the hottest, like that. So let's do it first so for this to call this tax this can do this we are already ready to do this we are okay first of all made this done this over here this look this which items Swaha was without note on this This is the first one made right. This is the first close to go into the straight. Before this the tack was completely anti. If I go here, I have not processed it. Right now I saw this one opening light. There is no one on the wrist at this time tight because This was the first one to be made, now I have made it that way, then when the inner element comes, what is the meaning of the inner element, is there anything else outside it, if there is anyone else, then you must have read this tattoo, so what do we know here? Give Hey we can default it is outermost or not so from the side of that track we can do it is tight so let's look at it here it will ask either what will it do with it and it has come out work After doing this, out it has come out work After doing this, even after this comes out, there will be someone on this who will be outside because he is different from everyone, if you remove Hello How Too Much then no one will be left, everyone inside has made his profit, okay one more time. Let's look at this second one 's own forces for this, Singh Anil Singh, this one 's own forces for this, Singh Anil Singh, this one 's own forces for this, Singh Anil Singh, this one is fine, so let's process it, so first of all, there is no one on the set, now after most, it is okay, then there is our aya, if there is anyone, then there is no one. Height is not in the last section so it is valid for the answer. This guy is for a ballet dancer. After today, I did not add it in 'I want a cigarette.' I today, I did not add it in 'I want a cigarette.' I today, I did not add it in 'I want a cigarette.' I removed it according to him. He will remove his leg. 'It is removed it according to him. He will remove his leg. 'It is right, even after the work of both of them is completed, he is still a pack guy.' It means that someone outside pack guy.' It means that someone outside pack guy.' It means that someone outside was definitely the President, so this is also not an item, this also has to be made an answer, I have to make the answer again, if there is someone on the state, it means there is someone outside, then you are also the lead for the answer, okay, Firoz cigarette came, so your After getting this report of foot return, he saw that there is some guy remaining on this track too, so this is also a bill for the answer, finally he came together again, he removed his feet and saw that now the step is fine, so this relation This diet is famous for computers, so this time another one from Britain, let's try the process that we have done to fit the algorithm, let's test it, so what do we have to do, so this is my first one. Opening Racket When the opening date came, what did I do? I checked. If there was no tax for hotels and malls, it would not have been in the footer. It is tight, so first check the phone. There is no one in the hair pack. It will almost strike but it is ready to answer. If it is not there, then do n't do it and Salim, we can even make it a cancer for this, okay, we will put those for the answer on this track, created the next answer on this track, opened it again, checked that there is already one here. It means it is almost. What will we do after clicking? Check this further. If everything is correct then add it to the answer and add the pack also. You have to put straight line. You can measure the tempered glass outside later. Put all these. It is there and then you don't have to type it like this. Checked. If after checking, the result comes, put it on the answer. You did not come or you came, meaning it came unnecessarily, put it on the track. Do n't confuse this with America, I am fine with you. Next band Jhala Singh Rakhra or project or will do with his leg or waist Answer I did not do this guy What should I do Jim removed the project What will you do with your stomach Will you remove it Ok removed Even after this there is a guy here It is still present, meaning there was someone else outside it, so when the closing racket came, what did you do, first remove your foot and then check, okay, so we can write a little correctly, checking and then straight. But the work of testing can be combined, okay now Lavnaya Opening Racket, checked that there is already a guy here, it's almost, put the project here, removed my hair first and then checked that there is already a guy here. There is someone on the interest rate, I just checked that friend, there is no one here, now it means this is the northernmost, if there is no one, then it is okay, first check your profit, if there is no one on the phone, then it becomes the outsider, enter this. But don't just do the phone again. Checked the opening racket. If there is someone bigger here than before then this is the innermost and I have made a lot of mistakes. Is it time to make the answer? I have made a mistake in my improving. I have to cut it back. Use it. The answer given by so many readers was this: this: this: Okay, okay, and here I did this opening process, checked that the young man is already there, then this answer came and the stock is gone, if it is sung, will it remove it or is it there? Velvet is loose, came to remove, will it do this, there is no one, there is no heroine, I checked, if there is no one, then there is no answer, then added and got frustrated or checked, there is a guy here, so he made himself like this and also on strike. When the officer came to rotate, he removed it in the process, checked if there is a person, then this is his belt, checked his singing, the first task is to check, if there is a person, then this is the answer, then enter the track number, then make the opening enter, check batala, reposing removed, then see here. But the answer is closed, then the closing is made, see here, some are made, so removed before the remote, some guys are the answer, again the closing is removed or there is no one, there is no cancer, okay, so this is our highest whole, it turns out to be so much. Reach your website, set the answer, otherwise don't post it on the phone, remove the approach, check, if there is any person then do Android, if there is no person, do it in report, okay then let's try to blend it and see. That this work is written on the free treatment, so basically when an opening appears, you first check it and then push it in the pack. When employment comes, you first remove it and then check it. Okay. So let's keep running it with both these data, then we have to create a pack, character type is Jhal and foot is acting builder, Jhal, I will set it now, so were the current character sequence dot in airtight now here if this guy is the opening racket. So we will do some ginger shooting also and in the last add to and ping okay opening racket that kiss love do Om ne Bigg Boss first check ific dot acid 2009 acid beach okay that this is basically the pillar of this one that your -My everyday style of Singh your -My everyday style of Singh your -My everyday style of Singh is anti now, it is a treatment made, so I have not added it on my answer, it is going to be packed, a text message has been sent, ok, this is when the closing is left, see what happened again next time. Once again he came to his profit, he saw if there was anyone big in the step, if he wanted to find the tablet, then he added himself on the answer and this time he added, he was in love with what his sons would do, first he stopped it and removed it, now he checked state wise. That if the head is there then it is out Ustad greater than that which is there then items are not there were president 's paint ch is okay with this Kayan it was 's paint ch is okay with this Kayan it was 's paint ch is okay with this Kayan it was sitting close he first topped this opening here also it is not there now chakli size greater thans Whatever it is, yes, there is a person in it, so it is valid, it is almost, okay, till the time I had made this, do not add it here, add it so that it will not be added, okay, next off, according to this, he has potted it, cannons, so now. This is the outermost. You have seen that the size has become zero. If zero is not much, then you did not add it. Then your entire contribution has been completed. Okay, let's run it and see. Jhal is putting Amit on WhatsApp. If the MP3 character is visible then I am. Hop you get this version of understanding Thank you for watching Jhal on the next video
Remove Outermost Parentheses
distribute-coins-in-binary-tree
A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation. * For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings. A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings. Given a valid parentheses string `s`, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`, where `Pi` are primitive valid parentheses strings. Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`. **Example 1:** **Input:** s = "(()())(()) " **Output:** "()()() " **Explanation:** The input string is "(()())(()) ", with primitive decomposition "(()()) " + "(()) ". After removing outer parentheses of each part, this is "()() " + "() " = "()()() ". **Example 2:** **Input:** s = "(()())(())(()(())) " **Output:** "()()()()(()) " **Explanation:** The input string is "(()())(())(()(())) ", with primitive decomposition "(()()) " + "(()) " + "(()(())) ". After removing outer parentheses of each part, this is "()() " + "() " + "()(()) " = "()()()()(()) ". **Example 3:** **Input:** s = "()() " **Output:** " " **Explanation:** The input string is "()() ", with primitive decomposition "() " + "() ". After removing outer parentheses of each part, this is " " + " " = " ". **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'('` or `')'`. * `s` is a valid parentheses string.
null
Tree,Depth-First Search,Binary Tree
Medium
863,1008
1,013
okay I should welcome to this new programming video in this we are going to solve something as partition a day just ahead okay and this we are trying to solve the partition area into three parts with equal so this was one problem I must say that I did not figure out the solution so I was thinking too much which was not needed okay so I just briefly what the question was in which we are given a list okay so like listen to this with utmost concentration there will be many types of sums of relating to this please focus on this I was a fool to not recognize this okay so we are given a list and we want to partition them in such a way so that there are three equal partitions whose summations are exactly the same I was not able to figure out a single solution in which I could even predict that first I will find the summation of it and if that summation is divided or modular 3 is equal to 0 then only there is some chance of being equally divided I was not able to figure out that as well so that was one of the part of strategy I will explain it in a detail as we move ahead okay so what the thing is that we will be given a list and we have to return it in a boolean form that is true or false true if we can partition the array in three equal parts having the exact same summation and fault if we cannot do okay so how do we do this the basic strategy as I just told is that find the summation of the entire like all the elements and if that summation modulo 3 is equal to 0 that means that there are some chances that we could partition them but if it's not modulo 3 then there are no chances first step elimination we did that now what if the summation is divided by 3 what if what in that scenario so that what we will do is that lets say the summation of all the element is 2l so 12 by 3 is equal to 4 so we have to find every partition whose submission will before ok then only something can be done with it ok then what we'll try to it's not mandatory before but like every partition has to be four so what we will try angry we will use the summation to like go to that element whose submission becomes exactly the ideal scenario okay so once that case is achieved then we will do the various partitions and then if the partitions are greater than or equal to three at least then the answer is we can find the answer okay these guys really very important question okay let's do this so the first submission okay we evaluated this now what we are thinking is that let's maintain the let's say number of partitions okay then let's also try the summation already and let's take at something as temp I don't know for I'm a let's see if you are doing something else for I a and let's say temp is equal to temp plus I if my temp is equal to the ideal so what's my idea so ideal is equal to summation by 3 so if my temp is equal to ideal then I will again have to decrease my temp to 0 and partition I'll have to increment by 1 so if my partition is greater than or equal to 3 that means I can do this else I cannot reverse partition is not defined okay this spelling address is killing me oh it's done that's all very important question please focus on this we are not approaching Beco n square anytime unless that's needed all the big text will find or will like force you to do the optimized way so search and train your brain like that
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,742
all right let's talk about maximum number of balls in the box so the first favorite is redundant and you just have two uh the limit ones load them in the other one's high limit and it's inclusive so uh i'm going to summarize the whole entire question so you have a bow so you have to assign the bow to the correct box so how do you assign to the correct box you have to split your number the whole numbers into a one by one and then you add every digit together to get a correct number this number is actually the box number so the three to one will assign to box six right 10 will assign to box one and i mean you just have to split your number and then just assign to the correct box now um this is a constraint 10 to the fifth right so what is 10 to the fifth this is ten to one two three four five right so this is assigned to box one this is because uh these numbers assigned to plus one is because one plus zero so what is the maximum number uh maximum box number isn't it supposed to be 99999 right which is 45 right and if you do know like uh what i'm gonna do is because i'm gonna use an array so in the race actually for every space for every box it assigned to uh a space for the box so i'm going to say this is 45 right so if you're including box zero there will be 46 so i'm going to enter a count equal to mu in 46 and here we go so uh what i would do is that i need a full loop to traverse the limit right so low limit i listen to high limit ipod plus now i need to assign my uh my numbers which is i to the correct box right so i need a what i need a double function both uh probably in i'm gonna say sum sunday and then go to enums and then i'm going to say inside i'm going to do well nominees will then 0 i need to add every digit the num digit to the sum and then divide by my sorry num divided by 10 and i will return my sum and for the only array factor for loop i need to call this function with i and every single time i need to implement so how do i actually um need for this question i need to return the maximum number in the box so i need to try work conversion array i put 0 i listen from the length i plus then i would say i need a variable to store my value the maximum value so result would become and then it's either a result or the contact right and you just have to return results and this will pretty much it so they just run it and here we go so without any uh questions this is supposed to be an easy question and for timing space complexity is pretty simple and for the spaceship uh full time sorry four times definitely all of that right it's between the high limit to the low limit or low limit to highland so uh you can say all of h minus l which is highly minus low limit and that will give you the time complexity and if you want to be more uh be more specific right be more specific you need to think about it this is 46 the space you there are 46 space for in array right so it's going to be like i minus l or 46 the maximum between the high minus l or 46 because you will have to transverse the uh in a rate at the end so this is pretty much it so the speed could be 46 but i will just making sure that this is all of h minus l and in this question the digit i mean the maximum loop for every uh every number is actually although 506 right over six this is because of constraint and this is constant be honest and if you just want to think about it like h minus l times a constant which is uh i mean which is h minus l and this will be a solution and if you feel helpful subscribe like if you want it and i will see you next time bye
Maximum Number of Balls in a Box
widest-vertical-area-between-two-points-containing-no-points
You are working in a ball factory where you have `n` balls numbered from `lowLimit` up to `highLimit` **inclusive** (i.e., `n == highLimit - lowLimit + 1`), and an infinite number of boxes numbered from `1` to `infinity`. Your job at this factory is to put each ball in the box with a number equal to the sum of digits of the ball's number. For example, the ball number `321` will be put in the box number `3 + 2 + 1 = 6` and the ball number `10` will be put in the box number `1 + 0 = 1`. Given two integers `lowLimit` and `highLimit`, return _the number of balls in the box with the most balls._ **Example 1:** **Input:** lowLimit = 1, highLimit = 10 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 2 1 1 1 1 1 1 1 1 0 0 ... Box 1 has the most number of balls with 2 balls. **Example 2:** **Input:** lowLimit = 5, highLimit = 15 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 ... Ball Count: 1 1 1 1 2 2 1 1 1 0 0 ... Boxes 5 and 6 have the most number of balls with 2 balls in each. **Example 3:** **Input:** lowLimit = 19, highLimit = 28 **Output:** 2 **Explanation:** Box Number: 1 2 3 4 5 6 7 8 9 10 11 12 ... Ball Count: 0 1 1 1 1 1 1 1 1 2 0 0 ... Box 10 has the most number of balls with 2 balls. **Constraints:** * `1 <= lowLimit <= highLimit <= 105`
Try sorting the points Think is the y-axis of a point relevant
Array,Sorting
Medium
null
127
hey everyone welcome back and let's write some more neat code today so today let's solve word ladder this is a hard problem but i don't think it's super difficult there's just one little thing that kind of makes it really annoying to get this to pass on leak code but the idea is we're given a beginning word and we're given an end word and we're given a list of words we want to create a sequence from this beginning word to the end word and the end word is definitely going to be need to be a part of our word list but the beginning word actually might not be a part of the word list and so we want to create a sequence from the beginning word to the end word that sounds pretty easy but there's one restriction that we have to follow and that restriction mainly is that every adjacent pair of words in that sequence can only differ by a single character exactly one character they have to differ by exactly one character and so we want to find a sequence from that beginning word to the end word where every word in between is a part of the word list and we want to return the shortest sequence so the sequence will basically be the number of words so for example in uh this example down here we can see that there's a sequence from the starting word hit and notice how this is the beginning word so it doesn't have to be a part of our list of words but every other word in the sequence does have to be a part of the list of words and that includes the end word so cog does have to be a part of our list of words and so in this example the shortest sequence is of length five because it has five different words in it now the convenient thing for us is that every single word including the beginning end word and every word in the list is going to be guaranteed to be the exact same length in this case every word has three characters in it so it's pretty easy to take two words and figure out what's the difference in characters between them right we can just compare character by character and see that there's one character difference therefore we could form a path between these two words right and each edge between these words let's say log and cog is going to be bi-directional right we could go from bi-directional right we could go from bi-directional right we could go from log to cog or we could go the other direction right so this is starting to look like a bit of a graph problem right we want to find the shortest path from the beginning node hit all the way to the end node cog and the way the edges are going to work so hit could be connected to any of the words in this word list where it has a single character difference so let's think about this so hit which one of these words could it be connected to is there a single character difference between hit and hot yes that's the case so hit and hot are going to be connected in this problem what about dot nope it takes two character difference between hit what about dog again two character difference lot again two character difference same with log and same with cog but hot could be connected to some of these characters or some of these words right so we're realizing that building a graph like this with all the edges like an adjacency list pretty much between the words is going to be very helpful for us and there's a naive way to create this adjacency list which is going to basically be a nested loop on the entire list of words which let's say ends up being n squared where n is the number of words and let's say the length of each word which is always going to be the same is m because we're going to need to compare character by character between the words so creating that adjacency list is going to be something like n squared times m but and you might think that's good enough unfortunately this won't pass on leak code and i really think that's kind of stupid that it does that the main thing to notice to build the adjacency list faster is to look at the constraints they tell us that the length of the list of words in our case that's n so it's going to be n squared right is going to be less than or equal to 5000 whereas the length of the word itself is going to be less than or equal to 10. so there's actually a way where we can change this time complexity to at least generate that adjacency list to something like n times m squared because the m is going to be smaller than the n so we can actually make it kind of like this but i'm pretty sure that the overall time complexity because after we actually create this graph we are going to run a breadth-first search algorithm to run a breadth-first search algorithm to run a breadth-first search algorithm to find the shortest path we could do it with dfs but usually to find the shortest path breadth first search is much more efficient and i'm pretty sure even in this case the breadth first search solution is going to be n squared because this is going to be the number of edges we could potentially have right because that's how many words we have we could have n squared edges and we're also going to have to compare words so on each operation when we're traversing the graph it's going to be multiplied by the length of the word so the overall time complexity for the bfs is still going to be n squared which is you know pretty much this so you might think well then why isn't it passing on leak code and you know that's a good question i think in general though doing it like this is going to be faster we use this to generate our adjacency list and then we do a bfs with this time complexity and basically there's kind of a small trick that i'm going to show you which will get it to pass on leak code so like i said the first part is building an adjacency list and the naive way would be to go through every word hot compare it with every other word that's going to be n squared and then the length of the word which is m but there's a little bit of a trick so how about we do it some a different way right we know that for any word we want at most one character difference right so let's take a look at hot our first word and let's take a look at every pattern it could fall into if we changed one character at most if we changed the first character to any other character we could transform this into star for the wild card and then o t right we changed the first character we could also transform it into h change the middle character star and then t right and then also to a third word h o and the last character is going to be a star right so these are the three patterns that hot fits into and now let's take a look at a different word dot and let's quickly do the same thing for this so the first pattern will be uh star o t next d star t lastly d o star so notice how okay these two patterns between the words are different but the first pattern for each word is the exact same since these both of these words hot and dot have the same pattern when we remove the first character that means that they have a one character difference between these words and that makes sense right if we change the first character from here to a d or change the first character from here to an h these two words will be the same that means they have a one character difference so using this idea we are going to create an adjacency list where the key of the adjacency list is going to be the pattern by pattern i mean one of these wild card type strings and the value of this adjacency list in our case it's going to be a hash map or a dictionary so each pattern is going to be mapped to a list of words so each pattern to a list of words so for example if we take the pattern star o t we'll have a corresponding list of words for all words that fit this pattern right we so far we found hot fits this pattern we also found that dot fits this pattern and by just looking at our list we can see that lot is also going to fit this pattern so we have three words that fit this pattern so if we wanted all the neighbors of hot in our adjacency list how would we find them right because the key we're not it's not like hot is the key of this adjacency list so to find all the neighbors of hot what we have to do is first for hot find all of its patterns right the first pattern star ot will go to that straw and say okay these are all the neighbors of hot these are all the neighbors in the graph of course we can't include itself so we'd say okay dot and lot are going to be the neighbors of hot but we also know that hot could have a couple other patterns that it fits into h star t are there any other words in our list that match this pattern well hit is going to match that right hit is going to match the pattern h star t so in that list we would have hot and hit so that's how we'd get another neighbor for hot and lastly we'd see are there any other words that fit this pattern h o star in our list you can tell that i don't think any other words are going to fit that pattern only hot itself fits that pattern so it doesn't have any additional neighbors so the all the neighbors of hot are going to be dot lot and hit from up above here and so how are we finding the neighbors so basically what's the computation of what i just did it's going to be since to find all the neighbors we're going to have to go from hot consider okay if we remove this character or remove this character so basically we're going through every word in our list which is n and then we're going through every single character that we remove which is m right so that's how many possible different patterns we could have in total and then to actually add each word to the list is going to be another m so that's kind of how you can get the complexity n times m squared to at least generate the adjacency list now let's assume we have that adjacency list and we have a graph then the algorithm is actually pretty straightforward it's just going to be a basic bfs search so this is something like how our graph is going to look like we know that the beginning word is hit the destination word the end word is cog so we want to find the shortest path from here all the way to here so we know that a good way to define a shortest path is a bfs search so from our first initial spot we're going to look at all neighbors that it has from the picture it's pretty obvious hot is the only neighbor so far we have a path of length 2 because we're counting the number of words that is what determines the length of the path and of course it's not going to be this simple to get the neighbors because we know that our adjacency list is a little bit more complicated and again from hot we're going to go to its two neighbors and we're never going to revisit the same neighbor twice but we are going to potentially have to go along each edge at least once we're also not going to go along the same edge twice but the number of edges i'm pretty sure could be the number of words n squared and for each neighbor to find each neighbor we're going to have to do an m operation where m is the length of a particular word is which is where i'm getting this time complexity n squared times m i'm pretty sure leak code has the wrong time complexity for this somebody can correct me if i'm wrong though because for a graph with n nodes the maximum number of edges could be n squared and again from here so we don't want to even though there's an edge between these two nodes we don't want to go along that edge because that's going to be revisiting the same nodes twice so now we're going to go along our next layer so from dot we can reach dog and from lot we can reach log one now there's just one last unvisited node both of these log could visit it or dog could visit it but at the end we're gonna have a single another node so what was the path so we had one word two word three four five it took us five layers of our bfs to reach this so we're gonna say that our result is five and when you look at the output that's exactly what they had as well so with that being said we can jump into the code now so now let's get into the code and like i mentioned we want to make sure that the end word is actually in the word list because that's a requirement if it's not then we have to return 0 because that's what we want to return if there doesn't exist a path from the beginning word to the end word we're going to have a list of neighbors this is going to be our adjacency list and this is the first time i'm actually going to do collections.default dict i usually avoid collections.default dict i usually avoid collections.default dict i usually avoid doing this i actually manually create the dictionary but in this case it's going to be helpful to do this basically this is a dictionary where we if we're inserting a new value for the first time the default value is going to be an empty list also to our word list i'm going to go ahead and append the beginning word because it's not a part of the word list initially so beginword now let's actually build the adjacency list so first let's go through every single word in this word list and now for each word we want to find every possible pattern for this word so i'm going to use a pointer j just to go through every single position of this word of course we know every word is going to be the exact same length and for each position of this word i want to replace a character with the wild card character so i'm going to transform this string word into a pattern string where we're going to take the first uh j characters initially j is just going to be zero so we're going to take that we're going to replace the j character the 0th character with a star and then we're going to get the remaining characters skipping the jth character so j plus one to the end of the string so we're just gonna go through every position replacing a character with the star and then for this pattern we're gonna say okay in our neighbor list the all the strings that fall into this pattern so for this pattern we want to append the current word we want to say this word is a part of this pattern and that's going to help us traverse the graph later on and of course we're going to do that for every single word in the entire uh list and we're gonna do it we're gonna have that star go in every position of the word next let's do our bfs there's a couple data structures we're gonna need we don't wanna revisit the same position twice so we're gonna have a set to make sure we don't do that we know we're gonna start at the beginning word so let's add beginning word to the set and we also need a cue and we're gonna similarly add the beginning word to this cue and we're just gonna continue popping we're gonna go layer by layer until we get to the end word and initially our result or our length of the path is going to be 1 because we have at least one word the length is going to be the number of words along the path and now we're going to continue going while the q is non-empty if we find the word we're non-empty if we find the word we're non-empty if we find the word we're going to end up returning the result if we don't find the word when the loop exits we're going to end up returning 0. so let's do that and so we want to go through the entire layer and then we want to increment our result by one so i'm gonna increment result by one after we go through the entire layer and then we're gonna continue going layer by layer until our q happens to be empty so let's go through whatever the length of the queue currently is let's go through every single node and pop that note so q dot pop left and when we pop we're going to be getting a word that we ended up adding if this word equals the end word then we can return the length of the path aka the result if it's not the end word then we're going to go ahead and take the neighbors of this word and add them to the queue how can we get the neighbors of this word well first we have to see all the patterns that this word falls into and then we have to get all the other words that fall into the exact same pattern because that's the most efficient way to get the neighbors so first let's go through for every j in range of the length of this word so that we can replace each character with the wild card character so let's transform this word into the pattern so basically the exact same thing that we just did up above i'll literally just copy and paste it so this word could be replaced with the pattern right and now we're using this pattern we can get all the neighbors of this word so let's go through four neighbor word in neighbors of this pattern now of course we might be able to get that same word but the reason we're not going to get the same word is we're going to check if this neighbor word is not visited so if neighbor word not in visit that's when we're going to be processing that word so we definitely won't be looking at the same word twice so if this neighbor word has not been visited we can of course add it to visit and we can add it to the queue so q dot append neighbor word uh for some reason up above i said if end word is in the word list i meant to say if it's not in the word list in that case we're going to return zero but other than that the code is correct you can see that it's pretty efficient that's because we kind of use this trick to find the adjacency list i feel like this shouldn't be required to pass this problem though i think that's kind of dumb on leak codes part but for some reason it is but once you kind of know that trick this problem basically just reduces to a breath first search so i hope that this was helpful if it was please like and subscribe it supports the channel a lot
Word Ladder
word-ladder
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that: * Every adjacent pair of words differs by a single letter. * Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`. * `sk == endWord` Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._ **Example 1:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\] **Output:** 5 **Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long. **Example 2:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\] **Output:** 0 **Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence. **Constraints:** * `1 <= beginWord.length <= 10` * `endWord.length == beginWord.length` * `1 <= wordList.length <= 5000` * `wordList[i].length == beginWord.length` * `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters. * `beginWord != endWord` * All the words in `wordList` are **unique**.
null
Hash Table,String,Breadth-First Search
Hard
126,433
134
hi everyone welcome back to a new video today we are going to discuss a new question from Top interview 150 lead code and the question name is gas station this is a medium level question and in this question what we have been given is we have been given n gas stations okay so basically what we have to do let's say we have a circular route okay and we will be starting from an index we can start from any index and like let's say we have this uh like we have this example okay so we can start from any index and like we have five gas stations here right so let's name it as 0 1 2 3 4 right now we have five gas stations and we can start from any gas station right and what we have to do at every gas station we can get some amount of gas and also we have been given here that our car tank can contain any amount of fuel so we don't have to worry about anything like um what about the amount of gas that has to be int taken the car has unlimited gas tank so you can add any amount of gas as required and we have been given a cost so to travel from one place to another we will be using up some gas right so we have been given that cost to travel from one gas station to another and like let's say I have a cost of three here and the gas station at zero is giving me 4 L of fuel okay so I can travel from zero this zero gas station to the first gas station right because the cost is three only and I have 4 L of fuel now let's say if at the zero index or the zero gas station I got only three 2 L of fuel right now it is not possible for me to start this journey from the zero Index right so we need to take care of the of this thing that whenever the gas at that station gas will become less then we will not be able to start a journey from that index so now we know that we have some conditions that if we are starting from the index where the gas station become less than the cost then it is not possible to start a journey from there now let's say we are on the first index okay so the journey from 0o to one let's say it took 3 l of fuel so we were not able to start our journey from there now from 1 to two let's say the like cost for the journey is 4 L and I am able to get 4 lit of fuel at this Index right at the first index so I can start my journey from the first Index right so this is what we are supposed suppos to do here we need to find a way such that we will be able to start a journey from one index to another and then we will move forward in that way okay so now let's go through the problem description properly again now here what we have been given that we have been given n gas station which follow a circular route now from whichever index you are starting if you have a proper Journey you will come back to that means to that starting index only then only you will have a proper circular route if you are not able to reach that same index that means you cannot find a root if it is not able to reach the starting index means after the last index you are not able to reach the starting index okay it is only possible if we start from an index and we reach the same index at last so if we are not able to get that root then we have to return minus one otherwise what we have to do here we need to return the starting index okay so what we have been told here we have a car with an unlimited gas tank and it costs cost of I of gas yeah so as I told that every from for traveling from one index to another we will be using up some gas and the cost is also provided okay so it uh it has been mentioned that we start our journey with empty uh with empty gas tank and from whichever gas tank we will start we will be taking up like uh let's say now we are starting up from the zeroth index okay and the cost for that index is three so it is not possible for me to start the journey from here right because the gas tank only can only take one liter of fuel and the like possible value to start my journey or the cost for starting the journey is 3 l so I cannot start from the zeroth index that is what mentioned here that you begin the journey with an empty tank at one of the gas station and after you have started it should complete the cost of the means value that is required for the uh completion of the journey okay so now uh we have been given two arrays gas and cost and we need to return the uh like starting index from where we can like complete our entire route and if we are able to complete the entire roote well and good we can return the answer and if we are not able to do so we will be R returned minus okay so let's see this example okay now we have the gas as 1 2 3 4 5 and the cost that we will be having is 3 4 5 1 2 now we see that if we are starting from the zero index okay so the cost is three and I only have one liter or one unit of fuel I cannot start my journey from here right because the cost is more than the amount of gas that I have so I cannot start from this index now I move on to the like first index so I see that the gas amount is two but I need four unit of fuel to start from that index I don't have that much right so I will just uh move on to the other index and I will see if it is possible from the other index or not so the cost for starting from this index will be five and I only have three units right it is not possible for me to start from this index also therefore what I will do I will simply move on to the other index now I will be reaching to the third index I see that I have four units of fuel and the cost required to start the journey from here is only one unit so I find a possibility that yeah I can start my journey from this Index right so what I can do here I will be um like we have a prediction now that my start Point can be from the third Index right so we see that we have a proper difference here okay now let's see how we have like how we can predict that we can start from here okay so the difference between this is 4 minus 1 it is three so now I have three units of like three unit of fuel to move forward right so when I move to this index I see that I have five units of fuel and I will be utilizing only two units of fuel so simply my three will be getting added up with five and only two unit of f will be subtracted so what I will be getting here I will be getting six here right now I have traveled from 4 to five now let's see if I can come back to one or not right so let's see if I can come back to one so I see here that the amount of fuel that I have is six here and one more unit will get added so I will have 6 + 1 7 will get added so I will have 6 + 1 7 will get added so I will have 6 + 1 7 and the cost will be only three right so what will happen I have four unit of fuel left out with me right so from 5 to 1 is possible so from four to 5 to 1 is possible Ro route now we see that if we can go to two or not so the amount of fuel that is left with us is four so 4 + fuel that is left with us is four so 4 + fuel that is left with us is four so 4 + 2 we will be getting minus and we have to reduce the cost also so we will be reducing the cost here and what do we get here we get two right now we will be moving on to the second index and we see that we have three so we will be adding 2 + 3 and the amount or the cost we have 2 + 3 and the amount or the cost we have 2 + 3 and the amount or the cost we have here is five so we are left out with zero now we started from the third index and we were able to reach the like second index from here means we have completed a complete circle right so now we have a possible route right so we can go from 4 to 5 to 1 and then we can go back to 2 and three also so if like we were subtracting this value before only now let's say I have I start from here I do not subtract it right I can I will be subtracting this value only after I reach fifth right so let's say I have done 4 - 1 + five in this way say I have done 4 - 1 + five in this way say I have done 4 - 1 + five in this way if I do I will see that I can reach four okay and we have been mentioned this like we have been mentioned this in the question that if there is an there is a solution that is possible it is guaranteed to be unique okay so if you have a solution you will get a proper starting index okay so let's say we if we like there is a condition we have one more uh condition such that we are starting somewhere but we are not able to reach the last index what happens then is the total cost that we'll have the total cost will be greater than the total gas amount that we have in such condition we will not be able to reach the starting index after completing a circular route right so in such condition when the total cost will become greater than the total gas that we have we will be returning minus one okay so we need to be clear about this that the total cost should be less than or equal to the total uh gas that we have okay total cost will should never be like greater than the total gas otherwise we will not be able to complete a circular route okay now what we uh like uh let's move on to the approach for this question so we know this that we will be iterating in a loop right so we will be starting from the zero index and we will be going to less than n that is clear to us and we know that somehow when we have come like calculated the total value total gas and total cost then this value should either be greater or equals to the total cost right so if let's say I am storing the difference of both of them right now let's say I have a total value in which I am storing the difference for both of them which means that I have a total value where I'm storing the difference like this gas of I Minus cost of I so if I'm doing like uh like I'm finding the sum of the differences this means if my total is greater than or equals to zero then only I can return a valid result right if it is less than I have to return minus one why means I am subtracting gas from cost right if the gas will be like more than the cost then the total value will already be positive or if both are both amounts are equal we will get a zero value so we are therefore like equating for greater than or equals to zero right so uh let's say we are uh storing the start index okay in index value so uh we will be initializing it with zero and when the total value is greater than or equals to zero we will return the index here now we know that we have to return an index value only when the total is greater than equals to zero and otherwise what we have to do we will return minus one now we have the basic concept of what we have to follow now the question comes how do we find the starting Index right means we have this array okay we have the gas value as 1 2 3 4 5 and the cost is 3 4 5 and 1 2 okay so what I have to check here in order to get a valid start index I need to have a like the difference between these two right it should be a positive value right means if uh like I am doing 1 Min - 3 then I if uh like I am doing 1 Min - 3 then I if uh like I am doing 1 Min - 3 then I am getting min-2 as the result if I am getting min-2 as the result if I am getting min-2 as the result if I am not having the proper uh gas amount to complete the cost I will not be able to move forward so it is not valid right it is not valid starting point therefore what I can do here if I am maintaining a current cost okay and in that what I doing I am adding up the values current cost plus gas of I Minus cost of I okay so uh this is not the total value this is the current value to check every position if we are getting a positive value or not okay now let's say we have this okay now what we can do let's say I move to this um this is not a valid like condition right because when I do 1 minus 3 I will be getting a negative value and I cannot start from this index so this is for sure that if my current cost is less than zero then I cannot put any value in that right so I will simply like continue from here if my current cost is less than zero I will continue and where will I continue right means the value that I have here if it is less than zero this is not a possible start Index right but I can expect that my start index will be after this so what I can do here before continuing I can assign a start index which will be I + 1 so what I will do here I will update + 1 so what I will do here I will update + 1 so what I will do here I will update the start to I + 1 and I need to update my current to I + 1 and I need to update my current to I + 1 and I need to update my current cost also because I cannot carry a negative value because let's say now if we have value here we have min-2 we have value here we have min-2 we have value here we have min-2 and let's say we had the cost here as four okay so we required four uh we had four unit of gas and the cost required was also four and if I was carrying the negative value from previous one then this value will also turn into negative value and I cannot like I can means this could have been a possible start position and I would have missed that because I was carrying a negative value with me so in order to avoid that what we can do if the value of current cost is less than zero I can like simply re-update my current cost to like simply re-update my current cost to like simply re-update my current cost to zero and change my starting like or the expected start index to I + 1 okay so expected start index to I + 1 okay so expected start index to I + 1 okay so this is zero and this is I + 1 now we'll this is zero and this is I + 1 now we'll this is zero and this is I + 1 now we'll move back to the previous example only now my I is here right and this is the like this is the cost I am seeing that again I am getting a negative cost here so again what will happen my start index the valid or the expected start index will move on to the second index because if I'm having a negative value it is not possible for me to move forward so for that what I will do I will increment the start index with i + 1 and what will happen here this + 1 and what will happen here this + 1 and what will happen here this current cost that I have here it will be reupdated to zero now I will be moving on to the second index I see that I have three and the cost required is five again I am getting a negative value here right so what I will do here again my start will get updated to I + 1 so start will get updated to I + 1 so start will get updated to I + 1 so start is three here and uh the current cost is again updated to zero so current will become zero now when I come to this index do the third index I see that I am having a positive current cost so I will not be going inside this condition now means I already uh I have already found a satisfied starting index where I can start my journey as I am getting a positive value here so I will simply uh store this uh this will not uh there will be no Chang is in the start index now and the current will also carry the value as mentioned okay so what we have the current cost here we have three as the current cost this will get updated to three and again we will move here now we will find the difference we have uh 5- 2 which will give us 3 and 3 + 3 will 5- 2 which will give us 3 and 3 + 3 will 5- 2 which will give us 3 and 3 + 3 will get updated to six now we will reach the end of the uh array right till now we have positive value and now since we found a possibility to start the index or start our journey then we can say that the route the circular route is possible so we will simply uh return that um start index with three now why do we do that because we are already checking a condition here if the total value is greater than zero or not if it is not greater than zero or not greater than or equals to zero then we will not be returning this index or the start that we have taken here we will only return the value if we are getting the total like the total difference as greater than or equals to zero okay so we are already checking the edge condition here let's say we already like in the previous question uh we have proper gas and cost we are getting zero so it is returning the value now there can be a condition where we are getting a start index but the cost will become greater than the gas okay so in such condition we need to return minus one and if we are not checking this condition we will get a wrong answer to avoid that we are checking if the total gas amount is greater than the cost amount or not okay so now let's move on to the code and we will see our um uh see how this code works so let's see the code now okay so what we were doing first we were declaring a start index okay and the other thing what we were doing is we were iterating in the array right so we will start iteration and we will see how it goes so we will be starting the iteration for in n and we will declare this n length of we will be using total for storting uh storing the total value so we will be having a total and current value so current also we will be initializing with zero right now we have total value so we will be finding the total plus is equals to gas of I Minus cost of I current as I said previously Let's uh see before moving on let's see this example okay so we have been given the gas as 234 okay and the cost here is 343 now when we were going through the like implementation let's say we are not checking the total okay and we are just um we are totally depending on the current value to get the start index and we are returning it okay so what will happen now let's see we have okay the for the zero index we are having gas value is less than cost okay so we will not be taking this value again now three for the first index also we are facing the same problem now when we come onto the second index we see that the value of gas is greater than the cost so we will be getting a start index here but now let's see if we can complete our journey or not the total for gas we are getting here is nine right and for the cost we have 10 means we have the total gas value less than the cost value so anyhow we will not be able to complete our journey but we are getting a start index here and if we are not checking the total then we will be returning the start index but the expected value might have been minus one right so in order to do a proper uh verification we are checking if the total is greater than equals to zero or not okay so now we have a current value and we will check if current is less than zero then what we have to do we were uh starting uh incrementing the start index by one and what we were doing we were uh imp like reinitiating current with zero right we can write continue also we cannot also it is your choice and now what we have to do out of this Loop we need to check if total is greater than or equals to zero then only we can return the start index okay otherwise you need to return minus one so else you need to return minus one now let's try to run this so the sample test cases have passed let's try to submit it so this code has been accepted so that's it for today guys thank you for watching if you found this video helpful please let me know in the comments and in case you have any doubts let me know in the comment too so I can try to clarify it more and in order to continue with me in this coding Journey please subscribe to my channel and hit the Bell notification so you will be notified every time I post a new video thank you for watching
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
122
okay back to leak code again today working on best time to buy and sell stock two so in this one you're supposed to loop through an array and find uh the differences between some numbers to essentially get out of profit so the way to think about this one is that every time a number in here in this sequence increases then you want to take the difference of that and add it to your total profit so because one here is less than five there's an increase right there we would add that to the total profit from five to three we'll have to decrease so we don't add that but from three to six there's an increase so we would add that to total profit so to do this one we'll start out by declaring a max profit and then we're going to loop through all the prices which is the input array okay then what we want to do here is we want to compare let's grab this right here so here's the input so we want to compare all of these numbers against each other but we want to do it like this so we want to do it in the sense of if prices i is greater than the previous item in here so when we're looping through this we go and also we don't need to start here at the beginning we need to start here at 1 because we can't test to see if this is greater than the previous one because there's no previous one so if we start here we go okay is this number greater than this number it is not is this number greater than this number no it is not is this number greater than this one no it is not so in this case that's probably not the best array to loop through let's grab this one instead you get the same concept though okay so is this number greater than this one no does not but this one is greater than one five is greater than one so from here all we would need to do is take max profit oops and set the current value of whatever max profit currently is so right now it would be zero in this first iteration and add the difference between the value of that number and the previous value like this oops and then at the end here there we go then at the end there we'd want to return it so just like that so let's make sure i don't have any typos in here by submitting it oh we got a runtime error what did i do wrong oh a typo in there let's try this again okay great that got accepted and one thing you can do here if this is looking a little confusing still you can always grab let's see i'm just going to copy paste this in here it's a lot of typing but you can always grab the values here and print them out so in this case i'm saying okay what is prices i and then what is price is i minus one and if we run this oops now we can run this uncomment that code there we go so prices i is five prices i minus one is one so if you go back up here price is i is five prices i minus one is one you look again prices i is six i'm i minus one is three come back up show you six and three so we're just taking the difference right between these two numbers and adding them
Best Time to Buy and Sell Stock II
best-time-to-buy-and-sell-stock-ii
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day. On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**. Find and return _the **maximum** profit you can achieve_. **Example 1:** **Input:** prices = \[7,1,5,3,6,4\] **Output:** 7 **Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Total profit is 4 + 3 = 7. **Example 2:** **Input:** prices = \[1,2,3,4,5\] **Output:** 4 **Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4. **Example 3:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0. **Constraints:** * `1 <= prices.length <= 3 * 104` * `0 <= prices[i] <= 104`
null
Array,Dynamic Programming,Greedy
Medium
121,123,188,309,714
1,822
how's it going guys so today we're going to solve the uh coolest question which is sine of their product of an array so this question is like saying like we have a function sine s that returns 1 if x is positive so like if this x is positive then it will return 1 if this x is negative then it will return uh minus 1 for that if this x is 0 then it will return 0 for that okay so we have to uh check these things all right so this is like quite simple like so basically like how i did in the first instance is like i just simply use an brute force approach in which what i will what i did is like uh i'm just you know kind of just uh taking too much time complexity in that one because of o n square i'm using omega square time complexity why because like what i'm doing i'm just going to the loop for two times i'm using nested for loop okay and i'm multiplying nums like that i'm just doing like that so that's like a stupid thing like a if you like you can do this in front of the interviewer but like actually you don't have to do this question by using that i'm just giving you an idea like if you want to do it by the brute force like in the in front of the interviewer this question will come then how you can do it okay so just like simply multiply and if is less than zero then it is a negative it's greater than zero then you say is positive if it does product is uh zero then you say like it is equal to zero then just return zero for that so that's a simple one like and i'm going to do with an another simple approach it is very quite simple like in which we are not dealing with uh any time complexity i get the time complexes off and uh i think yeah and space is like uh off one only okay so what i'm doing is i will simply say okay let's take into negative in the first intense as zero okay we don't know what is our negative so let's say at it is neutral it is zero i will use the foreign loop for this one i will say it will go for into i till nums till our array okay all right in this one i will say if i is 0 if i 0 then i will simply return 0 for that as simple as that now i will say if my i is less than zero then i will increment my negative okay now here's the things come what did i mean by doing this is let's just take an example like if you look at over here so we have one minus sign over here one minus sign so minus give us plus so again we have one minus sign and we have one minus sign so minus plus okay so i will say like how many times i will go to the minus sign for example like if i get minus sign by even times like even times okay then it means it is positive it is it will give definitely it will be positive but what if i get the negative sign only one time okay like in this zero is given okay let's talk about this one so we have one over here one over s three so we if we get the o times our negative sign then it means it will definitely be negative okay so for that how will calculate like e like even we will simply uh modulus it by two and if we get a zero then it means like it is a positive number and if we don't get zero uh then it means like it is negative number so we are doing the same thing over here so let me just show it to you guys just simply using it okay let's go so it's quite simple i'm just returning it i'm using the terminating operator if you know about reality operator that's good if you don't know that then just google it is it's nothing is it's kind of like a you're using a fast condition it's kind of like that okay so let me say return negative more or less two is zero okay then i will say question mark i will say is one this two minus one it can be positive one or it can be my negative one okay so according to this i will according to this written condition according to this relating condition i will manage this one okay so that's what i'm doing over here so let's just finally run this code and yeah so finally submit it and here we go guys so as you see the time compress is zero mean like it's faster than 100 submission so this is the very easiest and solution guys so like you can show the interval my stick yeah this pen is okay you can show the intro the brute force and this approach as well so i hope this question is crystal clear to guys i will see you in the next one till then take care bye
Sign of the Product of an Array
longest-palindromic-subsequence-ii
There is a function `signFunc(x)` that returns: * `1` if `x` is positive. * `-1` if `x` is negative. * `0` if `x` is equal to `0`. You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`. Return `signFunc(product)`. **Example 1:** **Input:** nums = \[-1,-2,-3,-4,3,2,1\] **Output:** 1 **Explanation:** The product of all values in the array is 144, and signFunc(144) = 1 **Example 2:** **Input:** nums = \[1,5,0,2,-3\] **Output:** 0 **Explanation:** The product of all values in the array is 0, and signFunc(0) = 0 **Example 3:** **Input:** nums = \[-1,1,-1,1,-1\] **Output:** -1 **Explanation:** The product of all values in the array is -1, and signFunc(-1) = -1 **Constraints:** * `1 <= nums.length <= 1000` * `-100 <= nums[i] <= 100`
As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome.
String,Dynamic Programming
Medium
516
365
so hi everyone today we're going to discuss the water and jug problem it's lead code 365 problem okay so let's just get to it uh i hope you've read the question but i'll tell you in brief we are given two jugs okay this has capacity x let's say and we have another jack this has capacity y okay initially they're both empty and we have an infinite reservoir of water from which we can take water and we can pour water into it okay and we want to measure a target amount of water which is let's say z okay so but the catch is uh we can only perform one of three operations first is we can fill this well any of these two jugs completely okay second we can empty any of these jugs okay and third we can pour water from one jack to another till the first one is empty or the other one is completely filled okay so by doing these three operations only we have to achieve this amount of water okay so let's take an example it will be more clear let's say x equal to 3 y equal to 4 and we want to measure z equal to 2 okay so what do we do let's write the initial state this is jug one and this is chuck two initially they're both empty okay so what we can do first we can fill x okay fill the first chuck so this will look like this okay first one is full second one is empty now we can pour water from this jug to this jar okay so this will look something like this now then we can fill the first jug again so this is it and then we can pour water from x to y like first up to second jar it will look like this and then we can empty our first chart and there you have it okay so we are able to measure our target amount two so uh this is not a very straightforward question okay so there are actually uh two three methods of solving this we can solve it using bfs okay also using dfs and third is using gcd it's the fastest method but we're not going to discuss it today we'll discuss the bfs solution and if you understand the bfs solution you can do the dfs solution too dfs is actually a bit slow i'll tell you why later but yeah so how is this problem how can this problem solve or be solved by bfs let's see okay so this is actually a quite complex scenario right two jugs and a target amount so what i'm going to do is i'm going to transform the problem okay and we'll transform the problem into an equivalent problem okay which will be easier to solve how let's see let's say we have x equal to three and y equal to four okay so effectively what we have is one jug okay hear me out essentially we have effectively we have one jug okay of capacity seven okay it's all max capacity of seven okay and let's look at these operations closely so here let's look at the total capacity here is zero okay here is three so basically plus x here it's three again so nothing like zero here it's six so basically plus x again here it's six nothing here it's two so basically minus y so effectively you can check whatever operations we can do among the allowed operations we are effectively reducing the total uh amount of water by we are increasing the total amount of water by x or by y or we are reducing by x or reducing by y or we are not doing anything we are just shifting okay so essentially what we have is this problem is now this problem we had two jacks now we have one jug of max capacity seven okay and we can perform these two operations these four operations on the water of this jar okay and we want to reach z this is effectively what the problem has reduced okay so now we've transformed the original problem to this okay so now we can solve this uh let me uh dry run okay let me make a graph okay along the way so initially we're at zero state what does that mean initially our jug is empty so it is zero state which is shown by this node okay so the operations allowed up plus three plus four minus three minus four okay so let's add plus three and by the way since we're doing a bfs we're going to keep a visited map so zero is visited and three is visited okay so you can also add 4 and 4 is visited can we remove can we do minus 3 and minus 4 on this node the answer is no because since our jug is empty now we can't remove anything from it okay so these are invalid operations basically in our condition for bfs when we check uh if this state is visited we're also going to check if it's making our uh sum negative basically because we want to reach target and we're dealing with water and negative doesn't make any sense okay so from here uh we'll go to this we'll remove this from the queue okay so we can add three okay we can add four as well okay can we remove three you might say yes but i'd say no because when we remove three from this we're going to reach the zero state which is already visited okay by the way six is also visited seven is also so the state is already visited we're not going to enter it and 4 we can anyway not remove because the jug has only 3 liters of water so from 4 let's see can we add 3 liters and get to 7 no because 7 is visited can we add 4 liters and get to 8 no because max capacity is 7 and you can't put 8 liters of water in capacity seven jug okay so can we remove three liters yes can we remove four liters and make it zero no because zero's zero state is already visited by the way one is also visited now instead of keeping a visited array we are actually going to keep a visited map because the constraint might constraints might be large and we might not be using all the values okay this is not a graph where we have every value from 0 to n okay so from here from 6 we can't add anything because it will go out of bounds can we remove 3 liters no we can't because 3 is already visited and it will take us to 3 we can remove 4 liters though and it will take us to this state and this is actually our target state okay so you reach the target state so we have basically found the answer as yes we needed to find whether it was possible and it is the answer is yes for this okay we are we can measure two liters from this capacity seven jug with these operations we have remember we are transformed the problem so don't think about that this is the problem now and we have solved it and as soon as we reach 2 we can return this return yes return true basically a boolean variable okay and in case we keep reaching visited states and q becomes empty then we'll say that okay we couldn't find the target state so the answer would be false so the time complexity for this would be order of v plus e and the vertices at max can be x plus y because we have this capacity and we're not going beyond it and we're not going below zero and in the worst case we'll go through all of them and the edges okay the edges of this graph actually it will be quite less than that because once we if the target capacity can be found will we break early but the edges in the worst case can in a complete graph as we know can be n into n minus 1 by 2 if i'm not wrong where n is the number of vertices okay so basically the time complexity would be the time complexity of a bfs a graph with x plus y nodes that is the time complexity and dfs actually uh would be the same but it would be much slower why because the edges this is not a static graph right we can keep exploring and we can keep reaching edges so in case the capacity is quite large okay 1000 or 10 000 or something like that what dfs will do it will keep exploring one path only okay and let's say the target capacity isn't found on that path so then it will backtrack and then it will come back again and again okay so that would be very time consuming whereas our bfs would just go here and it will grow radius wise like it does okay so it will be more efficient okay so let's quickly write pseudo code for this okay be a boolean function let's call it bfs okay and we'll get input the capacity of jug 1 the capacity of jack 2 and the target capacity okay so right off the bat if x plus y is less than z we can directly return false right because these uh we'll never be able to reach the target because the sum of both the jugs capacity is less than them right so let's keep all the operations that we can perform in an array okay we discussed these that these are the possible operations right keep a visited map as well right you can keep in an ordered map okay c plus okay so let's initialize the q as well since we'll be doing bfs and q initially let's push zero into it or why because initially uh our jug is empty okay let's mark visited as visited of zero as one okay so while the queue is not empty okay what we're going to do let's pop out from the queue first right let's assume uh while popping out it returns the popped out element as well okay so when we pop it out first let's check uh if this popped out value is equal to our target capacity because in that case we shouldn't go further okay so we can return true all right so now for our operations or the edges you can say since there are four operations right so this will be the state after we perform the operation we can add x we can add minus depending on the value of i so uh we can check if this state has become equal to target state in that case we can return true directly and in case we're going out of bounds as we discussed right we can simply continue now for the main part if the state or the node is not visited we can push it into the queue and mark it as visit right basically we're doing a bfs only it's a modified bfs okay so that's it we can return false in the end because in case uh q becomes empty and we never when these two conditions never become true we'll know that it wasn't possible so we'll return false okay so that's it thank you
Water and Jug Problem
water-and-jug-problem
You are given two jugs with capacities `jug1Capacity` and `jug2Capacity` liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly `targetCapacity` liters using these two jugs. If `targetCapacity` liters of water are measurable, you must have `targetCapacity` liters of water contained **within one or both buckets** by the end. Operations allowed: * Fill any of the jugs with water. * Empty any of the jugs. * Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty. **Example 1:** **Input:** jug1Capacity = 3, jug2Capacity = 5, targetCapacity = 4 **Output:** true **Explanation:** The famous [Die Hard](https://www.youtube.com/watch?v=BVtQNK_ZUJg&ab_channel=notnek01) example **Example 2:** **Input:** jug1Capacity = 2, jug2Capacity = 6, targetCapacity = 5 **Output:** false **Example 3:** **Input:** jug1Capacity = 1, jug2Capacity = 2, targetCapacity = 3 **Output:** true **Constraints:** * `1 <= jug1Capacity, jug2Capacity, targetCapacity <= 106`
null
Math,Depth-First Search,Breadth-First Search
Medium
null
1,184
e Hello everyone, we are together again with another Lipo question, the last name of today is this pin Bus stops Zile Friends, the numbering of the bus stops are numbered from zero to minus one. This part of the question, friends, I am skipping because this part can be a bit confusing, here is the dissonance for good, if with the value in it. Well, plus he stated that there is one model between the other. This part is a bit confusing. His mother does not give us much information about his solution logic. As far as I see, here are the friends at the bus stops. You can continue clockwise or counterclockwise. That's why in these parts Oh this is that When the starting and ending stops are overthrown, when we are given the starting and ending stops given here as parameters, we need to find the minimum distance we can go from these stops to the start to the end stop, as I said. Let's go ahead, we can also go counterclockwise, it may be a little confusing, this part is now a little better with examples. I think it will be descriptive. If you look at it, friends, it is 0123. Because our bus stops numbers started from zero, this is friends, zero, one at a distance, one to two of us, brother, two to three distances, 3 to zero, 4 distances. In other words, it starts from zero as a band specified to form a loop. You also need to go. Well, if we go clockwise, we can go this one length. If we go counterclockwise, 43 more 72 more 9th house. Since one of these is the candle one, we are asked to rotate it backwards. This is the second one. Let's look there again. This time, the lengths are given as 0123 again. It is given as a1234. Their area is the ears. Start is zero. This time, stations are two. So I can either go like this. Clockwise, it is a plus 2 and 3 length, or I can go like this. 463 is given as 73. The smaller one, that is, three, wants us to go back. This is the third. If we look at it that way, friends again. The same lengths are given, 1234 shape, this time you are asked to start from zero and go to three. Therefore, if I go clockwise, one plus two plus 3 equals 6, it will go one way, when I go counterclockwise, I go A 34 one way. That's why I'm sending four back to my friends. distance within the distance, friends, some values ​​​​are distance within the distance, friends, some values ​​​​are distance within the distance, friends, some values ​​​​are specified here, it makes the most sense here. I will find the distance I will go clockwise between this stop, and also friends, I will do this in the total distance of my bus stops in this cycle Because I will go in front of the total length. If you subtract the distance, this will be the distance I will get when I go counterclockwise. So, the distance I go clockwise. For example, here I need to go from heat to two. I may be calculating the good distance in the clockwise direction. For this, Friends, I am creating two variables, one of them is ear varicose epic, I am paying for it is a good one. Friends, this bus is equal to dust and hazelnuts. These two will be the distance I went clockwise, and this will be my total distance. The total distance between this bus. This will also happen. So, it will actually calculate the total of the elements in this directory. Therefore, Friends, first of all, I will make an iteration in all things in the form of a and social Plants Plus, which is better than zero, and I will iterate within their lengths. First of all, it says plus is equal to restos month. Here, in this rule, the sum of all the elements in the array would give me that total length. Yesterday, Friends, I sent two different ones here, call them counterclockwise, I can use the additional distance calculation in the clockwise direction, the first one here is not specified for us, as far as I can see, the Start value in the examples here is Destination We can also call it an Akkadian thing that is smaller than the other one. Start 3 Destination 2 can also eat it, that is, I will start from here, I will go here, should I go this way or should I not go counterclockwise? That is the check. There is Esmer. Actually, there is a rule of two out of two that I have to take into account when calculating the lengths in the clockwise direction. If the Start change is smaller than the Destination home and the current index is between the start and the Destination, then I go clockwise. Additionally, friends, if the Park variable is larger than the deck age, for example, if it is from 3 to 2, and again this is Star TV, My good variable in it is mstart lade. If it is between the station, I make a check to see if it is going in the direction of the line here. Therefore, is the clock ear Valide class variable increasing? Cam Here, I am waiting for a 13 check immediately. I am here. As stated here, reset something, if my good variable is greater than March, equal to vegetables and fruits, if my good variable is less than the age of westen, it means I am Oo Isparta de Station clockwise for the others. So I come here and the messenger Governor talisman again plus Equals vistas. Am I going to increase it and which I am copying here and using the same logic. If the Start change is greater than the Destination value. For example, Start is equal to 3 and Station is not two. I am going in this direction. Actually, the same logic is good. If my skin at that moment is not good. Destination is smaller than the other one, that is, Isparta let's assume that the revolution is 3. Defne, let's now imagine that I have two in my hand, for zero, it is in the part here. If I am really going in front of the tree, let's say that the increase here must be greater than or equal to my skin here, then I understand that let's say Start. This part is bigger than the supporters and I'm going in the direction of the horse. Friends, it can be a little complicated. You can actually do this by checking a little bit more on the visual here. Between the two, between 02, it had to cry in both conditions, it was supposed to cry with sapphire. But now, if it is greater than Station in my place, it is enough for me if it meets any of these two conditions, that is, it must be either greater than the Start value or less than the Destination value. Friends, we calculated these, what did he want? He wanted the minimum between the two lengths between these two things. So from here, return to watch women with dipmo interest. That is, the length of the clockwise direction and the length of the counterclockwise direction, that is, bus tosec O wyzant kiss like that. Are you okay, let's create the camera like this. I want the distance that I went to home hours ago and the minimum distance when it goes counterclockwise from me. Because there are suggestions like an annotated one here, our code is subject to success form, now our code is Ahmet I can also screen Time 96 April and if I do all the skewers, the beam is faster than fifty percent. It worked, famous friends, in the structure here. The important thing is that there are two logics that we need to check, one of them is to find the length in the distribution direction and to find the total length. The Start value is here for me. I looked at the colors of the count and saw what he said. Start the Destination is always the Start value, and the Station can be small. Something in the form of something is given. So, in cases where the Start value and the other one is greater than the Station value, I make a second if check here and say again in the lower direction. I make a check on the attachment. Here again, I will change the ear suitcase and add this leather. Yes, friends, that's all I will explain to this question in the next video. see you bye
Distance Between Bus Stops
car-pooling
A bus has `n` stops numbered from `0` to `n - 1` that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]` is the distance between the stops number `i` and `(i + 1) % n`. The bus goes along both directions i.e. clockwise and counterclockwise. Return the shortest distance between the given `start` and `destination` stops. **Example 1:** **Input:** distance = \[1,2,3,4\], start = 0, destination = 1 **Output:** 1 **Explanation:** Distance between 0 and 1 is 1 or 9, minimum is 1. **Example 2:** **Input:** distance = \[1,2,3,4\], start = 0, destination = 2 **Output:** 3 **Explanation:** Distance between 0 and 2 is 3 or 7, minimum is 3. **Example 3:** **Input:** distance = \[1,2,3,4\], start = 0, destination = 3 **Output:** 4 **Explanation:** Distance between 0 and 3 is 6 or 4, minimum is 4. **Constraints:** * `1 <= n <= 10^4` * `distance.length == n` * `0 <= start, destination < n` * `0 <= distance[i] <= 10^4`
Sort the pickup and dropoff events by location, then process them in order.
Array,Sorting,Heap (Priority Queue),Simulation,Prefix Sum
Medium
253
496
hey guys welcome back to my channel and i'm back again with another really interesting question video today guys we are going to solve question number 496 the next greater element part one before i start with the video guys i just want to request you that if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications or more such programming and coding related videos let's get started with the problem statement so basically guys we have to find out the next greater element which is quite obvious from the headline uh but let's see how we are going to do that so basically we are given two arrays here nums one and nums two okay now we first have to find out the one element in the nums two arrays so for example in this case you can see that the nums one element four is on index uh is on index two in nums to array right and once we have found that numbers were element in numbers 2 then we have to find out in nums 2 array which is the next greater element that means the element towards its right which is greater than the value 4. so in this case uh there is no other element which is greater than 4 so my output corresponding to 4 is going to be minus 1 uh if it if you check 1 then you can see that 1 is on zeroth index of nums two array but the element which is uh which is greater than one uh the next greater element is three right it numbs to array so we just have three as our result corresponding to 1. similarly for 2 so 2 is the last element in nums to arrays obviously there is no greater element after 2 so that's why for 2 also the output is minus 1 hence my output array becomes equals to minus 1 3 and minus 1 so this is what we have to do we first have to find out if the element exists in the nums to array if it doesn't exist then obviously it's minus 1 if it exists then it numbs to array if there is an element which is greater than that means the element that is on the right hand side and it's greater than the uh the nums one element value then we have to put that element in our output okay so i hope that is clear now constraints are pretty straightforward guys the uh both the arrays uh range from one to one thousand values ranges from zero to ten to the power four all the integers are unique and all integers of nums one also appear in nums two so this is pretty certain that all the values appear in nums two they might not be a greater element next to them okay now follow up can we find a order of one dot length plus nums two dot length solution okay so now uh let's jump to the solution part and where i will explain the follow-up also pretty quickly so uh the follow-up also pretty quickly so uh the follow-up also pretty quickly so uh let's take a brute force solution approach first i'm not going to code it i'm just gonna explain it to you so in a brute force approach guys what we are going to do we are going to loop through the element uh like 0 to nums1 dot length okay so we are going to loop all the elements of nums one array then for every nums one element so for example my element is nums one and every is element i am going to loop through entire nums to array and whichever element is greater than so whichever nums to element is greater than the element value then that becomes our result okay so that becomes my ies result value right but what will be the time complexity of the solution obviously this solution is definitely going to work and i have tested it that solution is also accepted in lead code ah but the time complexity for this solution is going to be order of n square 2 n to the power 2 because we can see here that we are looking through the entire numbers one and for every noun so one element we are looping through the entire numbers two so this is not uh nums one plus num student solution this is sort of numbs one into uh nums to solution okay so we are not going to do this approach we are going to do this in a much optimized manner okay so now let's see uh this example first okay let me copy this example and try to understand it in a different way so we can see guys uh in the nums2 array let's forget about nums one for now let's see nums to array okay if i can find out a way in which i can just keep a record of every element which is greater than the iaf element then my job will be done right for example if i can note down that the element greater than 1 is 3 the element greater than 3 is 4 the element greater than 4 is there is none the element greater than 2 there is none right so if i can create a hash map in which i can store the all the elements which are greater to the previous element then my job will be done right so to solve this problem what we are going to do is we are going to create a stack okay we are going to create a stack which can keep a decreasing subsequence uh which means that whenever we will encounter an element for example this is a element x lets say x is my element and then what we are going to do we are going to look into our stack right for example if i am my x is equals to one so obviously my stack is going to be empty right there inside my stack i'm going to push 1 so let's say now my stack is having value 1 now my x becomes equals to 3 so whenever i'm at this x element i'm going to check inside my stack i'm going to peak inside my stack and i'm going to pop out all the elements which are lesser than this x right so in this case the only element which is lesser than x is 1 right whatever elements i am popping i am going to add it in a map and i am going to put the creator x element as the value of the map and the key will be the popped stack element if i continue this process what is going to happen is ultimately i will be you know i will be left with a hash map of integer pairs in which the key value will be the element of nums to array and the value is going to be the next greater element for that corresponding element in nums to array then i can use that map to create my result set of nums one elements right so i hope this solution approaches a bit clear to you guys and it is going to get more clear when we start implementing it so let's jump to the coding part so first of all i am going to create a hash map of integer data type let's name it map new hash map so this hash map is going to store the number and the next greater element of that number the next thing i am going to create is a stack of integers so let's name it stack new stack okay now what i'm going to do i'm just going to traverse my nums to arrays for integer num in nums 2 so for every number in nums 2 what i am going to do is i am going to find out if the stack is empty or not so while stack dot is empty so until the stack is not empty and i am going to check that if stack dot peak is lesser than the num value okay if that is true then i will put inside my map that for that particular stack value the stack dot pop i am going to put the next greater element as num okay now understand this guys because we are popping out the stack elements also for example like in this case i have already popped out one and i put the one and three in a map next time will i when i will go to the next element which in this case is going to be four my stack is uh so now after this my stack will have element three only it is not going to have any other element it is only going to have element three so when i will go to the next element four i will not be processing all the elements i am just going to process the previous element or the previous smaller elements right so in this way because we are not reversing all the elements of norms 2 we are only traversing the previous element this becomes the order of n solution okay also okay now coming back to the solution so once uh we have a while loop until stack is empty we are going to check if the stack value is less than num if it is less we will pop that element out put it in our hash map so mat dot put and corresponding to that element we will put the greater number as num okay once this thing is done we will push the current number value to our stack so stack dot push num so that the next element can be compared to it now when this for loop is going to get over my map will have the number and the next greater number pairs so now i can simply i trade the uh i can simply iterate the nums one array so integer i zero to i less than nums one dot length i plus and i can create a result and actually don't have to even create a result here um you can simply make nums one i becomes equals to now if map dot get uh math.get or default uh math.get or default uh math.get or default uh simply say nums1 dot ayat element if it is present so if inside the map the nums one element ith element is present you will get that value that means there is a greater number next to it if the number is not present then you have to put it minus one finally return the nums array itself so we are just manipulating the same array which you created but to make it more clear you can also create your own array and update those values okay let's run this code let's see if this works um okay there is an issue here um uh there is some issue sorry so we push this number inside the stack when the while is completed not inside the wall so that was my bad sorry so basically when the stack is completely empty and there is no number which is uh greater than the stack value uh after that after this while loop we will push the current number in stack not before that so this stack dot push comes after the file statement so let's submit this code guys let's see if this solution gets accepted and there you go as you can see that the solution gets accepted now so now if i talk about the time complexity so the time complexity is simply order of um you know the length of nums one and nums2 which is what we wanted to do in the first place okay so now the time complexity is this one okay uh talking about the space complexity guys space complexity is definitely going to be order of n uh the reason being is or i would say the order of nums two dot length uh the reason being is because we have created a hash map and that hash map is storing all the nums two values so that's why uh the space complexity is numbers without length uh so that was the solution guys i hope you guys like the solution and i hope your coding practice became a little bit better with it if it did help you guys then please do not forget to like this video share this video with your friends do subscribe to my channel guys and hit the bell icon for future notifications write down in the comment section below guys anything you want to say to me any comments suggestions feedback is definitely welcome if you get a better solution for this problem please post that also so everyone can benefit from it uh thank you so much for watching guys i'll see you guys in the next video until then take care and bye
Next Greater Element I
next-greater-element-i
The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array. You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`. For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the **next greater element** of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`. Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **next greater element** as described above._ **Example 1:** **Input:** nums1 = \[4,1,2\], nums2 = \[1,3,4,2\] **Output:** \[-1,3,-1\] **Explanation:** The next greater element for each value of nums1 is as follows: - 4 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1. - 1 is underlined in nums2 = \[1,3,4,2\]. The next greater element is 3. - 2 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1. **Example 2:** **Input:** nums1 = \[2,4\], nums2 = \[1,2,3,4\] **Output:** \[3,-1\] **Explanation:** The next greater element for each value of nums1 is as follows: - 2 is underlined in nums2 = \[1,2,3,4\]. The next greater element is 3. - 4 is underlined in nums2 = \[1,2,3,4\]. There is no next greater element, so the answer is -1. **Constraints:** * `1 <= nums1.length <= nums2.length <= 1000` * `0 <= nums1[i], nums2[i] <= 104` * All integers in `nums1` and `nums2` are **unique**. * All the integers of `nums1` also appear in `nums2`. **Follow up:** Could you find an `O(nums1.length + nums2.length)` solution?
null
Array,Hash Table,Stack,Monotonic Stack
Easy
503,556,739,2227
4
hello everyone in this video I'm going to explain to you the solution for the lead code problem median of two sorted arrays so basically in this question we're given two sorted arrays num1 and else you having the size m n N and we have to find the median of the two sorted arrays within the time complexity of log of M plus n so what we'll be doing is we'll be simply merging those two arrays into a new array having the size M plus N and then if M plus n is odd we'll simply return a of M plus n by 2 and if it is even then we have to return the average of the two middle elements so let's get to it so int M is equal to num shoot-out so int M is equal to num shoot-out so int M is equal to num shoot-out length now one node length taking the size of the given integers array and int n is equal to nonsuit or 10th and then creating a new array int a is equal to new int of size M plus n so with this we've created an array a having the size M plus n now to traverse and to put the values into a we'll be using three integers and K is equal to 0 now within a while loop we'll put the condition while I less than M and J less than n so we'll be using I to traverse through nums 1 and we'll be using J to traverse through all the elements of nerves to and while either array still has elements left will keep on going so if they lumps one of I is less than no-show they lumps one of I is less than no-show they lumps one of I is less than no-show J so if the I ate element of I of num so on is smaller than that yet element up now so we'll put that inside a new array times 1 or Phi I plus K plus or you can do K outside so in the first case I enjoy a zero so if the first element of numbs when is smaller than the first element of numbs to we'll be putting that in the first position of okay and then so on and light weights for the else part if num stew happens to be smaller then we'll putting that inside of key as you have to make a of K in a sorted order I'm Stewart J then J plus and then outside so that we can put the elements in the correct position k plus so using I will be looking at all the integers of nums one using J of noms two and whichever element is smaller loading that in its correct position in a you know we have to consider the possibility that one airy has finished while other array still has elements left so for that we need some mole to mole oops so while I less than M suppose that the first Irish Eli's elements left and the secondary has been finished has been completed so we can simply put all the remaining elements as they are as the second area is turn to number seven of I plus then k plus and we have to consider the case that the secondary Sheila's elements left while the first generation so that this loop so the second additional as elements left for sure resistant simply put all the elements of that area so Ananse two of J then J plus then cabe plus so with this we have considered all the possibilities and then we filled our array a and we have done so in such a way that a remains sorted now as I said if M plus n is odd so percent to not equal to zero if then what will you do simply return a of M plus n by 2 which is the middlemost element the median but suppose it is not having the size odd suppose it is an even size then say int X is equal to M plus n by 2 so M plus n by 2 and then double P a of X minus a of X double Q a of X minus 1 so in the else case where M plus n is even the size of the new array is even will be taking the two middle elements which happens to be a of X where X is M plus n by 2 and a of X minus 1 and I'm using double because we want the value up to the decimal point and so if we taking tedious it will be rounded down we don't want that and so after taking double P and double Q as the 2 mill elements simply return the average of that which is P plus Q by 2 so in a nutshell what we did basically was we traverse through numb so and enzymes too and we took the elements in a sorted order and we put it inside a new array a and then when a was finished a was completed if M plus n the size was odd will return the middlemost element if it was even then we took the two middle elements and we returned the average of that so let's try to see if it works and let's see if we didn't miss anything okay it seems okay so to submit it so as you can see it got accepted and the rent time is - MS lasted the ninety nine time is - MS lasted the ninety nine time is - MS lasted the ninety nine point eighty percent of Java online submission so we very much called the vlog of M plus n so this is how you to this question meeting of two sorted arrays very simply by merging the two given arrays thank you
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
1,877
hey how's it going had to have this up to make sure that it was recording so ignore the cat he just wants attention or something uh okay leak code 1877 minimize maximum pair sum in Array the pair sum of a pair a is equal to a plus b the maximum pair sum is the largest pair sum in a list of pairs for example if we have the pairs 1 5 2 3 4 the maximum pair sum would be Max of 1 + 5 maximum pair sum would be Max of 1 + 5 maximum pair sum would be Max of 1 + 5 comma 2 + 3 comma 4 + 4 or Max of 6 5 8 comma 2 + 3 comma 4 + 4 or Max of 6 5 8 comma 2 + 3 comma 4 + 4 or Max of 6 5 8 so it's eight given an array nums of even length pair up the elements nums into n uh divided by two pairs such that each element of nums is in exactly one pair and the maximum pair sum is minimized return the minimized maximum pair sum after optimally pairing up the elements um so obviously uh we're going to have to put the largest number with uh some other number and so uh we want to know what the largest is so we're going to say m equals numsp z and nums do pop uh so the end and the beginning right um uh there's no way that you can get smaller than the smallest element when you're forcing yourself to lose to use Excuse me the largest element so um yeah while nums so as long as there's something in here we're going to say first number equals nums popop that'll take it from the end uh and then we want to choose I believe the largest number that is lesser than or equal to M and if that's not possible then we need to increase M um I think this will work uh if we are forced to raise it then would we need to do backtracking I don't think so uh well we'll find out if we get the wrong answer so uh let's see so we want uh bisect uh left nums of um M minus FN first number all right and uh let's see what is bisect left give us I mean obviously if there's an exact match it'll give us that but let's see what it does okay import uh what is it import BCT from bisect import bisect left ah good that worked okay so let's uh let's see how this works here 1 2 5 6 7 so BCT left um nums one aha so far off to a bad start nums is not defined shut up okay so it'll give us the index now if there isn't what we're looking for it'll still give us that so then it's going to give us something bigger than or equal to um what if we're looking for 200 that's five so 0 1 2 3 4 five that's off the end of the array and what if it's something that doesn't exist then I think it should give us the index of five right 0 1 2 so yeah so if I equals length of nums then that means that anything is fair game so m equal Max FN M comma FN plus um now you know what we don't need to do this second number equals none assert second number is not none now we're going to say second number equals nums do pop and we'll have all of the handling down here at the bottom so this is the only way that it could be off the edge um if I equals z then maybe it works or maybe it doesn't work but we don't really have a choice um else if uh if M minus FN equals nums of I that means that we found the value that we were looking for so nums do pop I um otherwise we return something bigger than what we wanted so we want the one before so minus one CT SN is not none which it shouldn't be and then m equals Max of M comma SN plus FN so second number and first number and then we just return the max the idea being we want to if we might need a smaller number later if the middle numbers force it to be bigger and maybe you can just always choose the biggest and smallest but I don't know I don't want to risk a wrong answer all right cool beats 5% of answer all right cool beats 5% of answer all right cool beats 5% of users oh my God that's terrible um what is this I did it a long time ago interesting H so you don't need all this you really can just interesting I guess it was uh easier than I thought so 4 I in range length nums divided by two and then we're going to say uh M = -1 m equal say uh M = -1 m equal say uh M = -1 m equal Max of nums of I plus nums of -1 minus I so from the left and from of -1 minus I so from the left and from of -1 minus I so from the left and from the right uh previous value return m I guess I made it harder than I uh needed it to be I thought that there was some gotcha you know though as I'm sitting here thinking about it ah whatever that's good we got it done
Minimize Maximum Pair Sum in Array
find-followers-count
The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs. * For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`. Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that: * Each element of `nums` is in **exactly one** pair, and * The **maximum pair sum** is **minimized**. Return _the minimized **maximum pair sum** after optimally pairing up the elements_. **Example 1:** **Input:** nums = \[3,5,2,3\] **Output:** 7 **Explanation:** The elements can be paired up into pairs (3,3) and (5,2). The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. **Example 2:** **Input:** nums = \[3,5,4,2,4,6\] **Output:** 8 **Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2). The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. **Constraints:** * `n == nums.length` * `2 <= n <= 105` * `n` is **even**. * `1 <= nums[i] <= 105`
null
Database
Easy
null
463
hey guys how's everything doing this is Jason is not a good hobby in this video I'm going to take one represent LAN and 0 represent water great cells are connected horizontally vertically not diagonally the grid is completely surrounded by water there is exactly one on one or more connected on the cells the island doesn't have legs one side is the square with a side near the one the grid is rectangular with and high the tone exists exceed 100 determine the perimeter of the land for that fringe like this 4 we get the perimeter like the size marked with yellow and so let's see how we can solve it suppose that the islands are not the land are not connected to each other then they each cell have 4 borders right so the 4 times the cell count but now since they would might be connected to each other when they are collected the joint order will be gone oh right mm-hmm now let's take a closer right mm-hmm now let's take a closer right mm-hmm now let's take a closer look so for all the parameter sites they belong to only one cell right if they are connect to each other there will be no border so all the borders belong to only one cell which is the border hit this tree belongs to this cell these 3 belong to this cell so we can actually check how many cells one a harmonious site could be counted as parameter for each cell and can't sound some of them up right for this one there will be no cell above no cell left also right so three ones bottom so 3 but for this cell in the four directions all connected to one cell so the side will be 0 so we can check this one by want to count them up could we improve it Wow we can see that actually the parameters to left-right primaries would must be if we look looking from left the vertical sides must sum up to the border size right like this the vertical one here would be like this why this happened hmm well it's not right because there might be some like some corner islands like this if that's the case were some shuffle assumption is not true so let's stick to our original plan we do cursor or look through all cells and check how many possible sites could be on Canada's parador's for it send them up okay so let the result to be 0 and create a function called get site possible get parameter what is Hawking itself as well probably we're meter of sell the it receives as coordinates as a parameter okay now we live through all the cells let's get the rows and columns first the input is padded we're not tell that the input is bad it's Oh rose 0.9 that the input is bad it's Oh rose 0.9 that the input is bad it's Oh rose 0.9 so he's might generate all error with your equals 0 return result now okay so now I use T equal 0 these women close to a cross bars now we just say result for us would be happier cell and finally we return the result how we get how it could be improved in this well check the for Direction Center um what if okay let can't it was zero so the laptop order if there is no cells above it and plus what right so I equals zero or correct I'm a swan j-20 count plus one now we I'm a swan j-20 count plus one now we I'm a swan j-20 count plus one now we would do the same for the audience let's see the bottom so I equals Rose Stockman -1 or great time plus 1 J 0 and that's -1 or great time plus 1 J 0 and that's -1 or great time plus 1 J 0 and that's what if J equals 0 left right so Phi 1 see those two boys the return count yeah I think we're done let's try to review our code one more time before we summon our code this problem and result I should put the result okay who's out here is okay and this one count is zero we check for each direction if it is there is no grade above minus 1 if it is no great if there's no cell it's the bottom mmm there's no cell to left no cell to right okay this should work ah we've got a run answer what really got for one no oh haha we need to determine it is a LAN first right God if it is not land yeah I'm so careless as you say okay we're accepted and let's see what the time and space complexity while time is because it's grad I suppose the greatest amen so we look through all the cells and get the prep parameter these actually check it's constant time so and by in space we don't use any array or something so it's constant okay cool so that's all for this problem hope it helps I'll see you next time bye
Island Perimeter
island-perimeter
You are given `row x col` `grid` representing a map where `grid[i][j] = 1` represents land and `grid[i][j] = 0` represents water. Grid cells are connected **horizontally/vertically** (not diagonally). The `grid` is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes ", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. **Example 1:** **Input:** grid = \[\[0,1,0,0\],\[1,1,1,0\],\[0,1,0,0\],\[1,1,0,0\]\] **Output:** 16 **Explanation:** The perimeter is the 16 yellow stripes in the image above. **Example 2:** **Input:** grid = \[\[1\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0\]\] **Output:** 4 **Constraints:** * `row == grid.length` * `col == grid[i].length` * `1 <= row, col <= 100` * `grid[i][j]` is `0` or `1`. * There is exactly one island in `grid`.
null
Array,Depth-First Search,Breadth-First Search,Matrix
Easy
695,733,1104
1,788
hello everyone let's take a look at click code 178aa maximize the beauty of the garden so it's a log problem and it's a hard problem let's take a look at how to solve this problem so let's take a look at the problem first there's a garden of un flowers and each flower has integer beautiful value the flowers are arranged in a line so we are given integer over flowers of size n and each flower's eye represents the beauty of the ice flower note a garden is valid if it meets the two conditions first the garden has at least two flowers secondly the first and the last flower of the garden have same beauty value for example in example one the first value is one but the last value is true so it's not a very gathered so we are as appointed have the ability to remove any flowers from the garden so we want to remove flowers in a way set makes the remaining garden valley and the beauty of the garden is some of the beauty of all the remaining flowers we need to retain the maximum possible beauty of some valley garden after we have removed any flowers so in first example we can remove this one so we get two three one two which is eight and for this example we know there's only one 100 so it's we have to remove it and we can remove this negative three so we keep one which is three for this example we can just keep negative 1 so that we have negative 2. of course it's okay to keep this 0 as the value does not change okay let's take a look um at how to solve this problem okay and so the constraint is pretty large this is an so we know an o n square solution cannot pass so maybe we need a like o n square cannot pass so properly we need our own solution first of all if it's interview we can give a naive solution first we can just follow every index and we use a double for loop if for this two index if the beauty are same then we can use i as a start point and use two as end points then calculate some maximum sum between i3 right for example x i is zero so when g is three we can get a and one j is here we can get another value and when you is here we can get another one next is one so when you is four we have um here right next i j can be like this and we keep move i and can be this so for each screen block we calculate the sum and the way updates the result but it's a like one two three solution how can we improve it to calculate some we can use perfect sum so we can improve this algorithm to o and square but it still gets theory right okay let's take a look so assuming this is our tree we need to find and this is end point so we need to find a start point but we have three uh possible solutions right let's think about if this is any point which start point is best point so this is a little bit greedy we know that as long as the earlier the start point is that we can include more elements since we can remove any negative elements so the earlier the start point is x and maximum next small number we can include and it's the more value the more beauty we can get right so the first one is the best if we fix the tree as this position okay so and to calculate sum we can just use perfect sum let's just go through one example so we just have a pointer for every element at first we point pointers here so sum is one we update our perfect sum so for beauty value one the prefix sum is one and we only update it once since the first time we met this number the prefix is a greedy one so it's the one we want to use later next summer is three so beauty two has perfect sum three and business three has fake perfect sum six okay next we're at one we find in the map there is already a one in the map so we can use this at endpoint and use this one as a start point and we can calculate the beauty sum so sum is this sum minus the perfect sum and we need to add the start point and end point so we plus 2 multiply 1 which is uh seven here okay now result is seven we keep moving okay for two it's also a star point in the map which calculates this sum minus map 2 plus 2 multiply 2 which is 8. okay next it's 1 then we can calculate again and we update our result to 10. next is 5 we update the map to include prefix sum of 5 which is 15. okay next one we calculate the result which is our sum minus map one plus two multiply one which is sixteen okay let's take a look at implementation we have this map and we initialize result into minimum and return results at last and system is our perfect sum so one thing we need to like i need to um point out our thing is for this sum we only record supportive sum since between the start point and end point we need to get the maximum beauty and for negative beauty we can just remove them right so for our prefix sum we don't need to include negative building so there's some only real cards the positive number it's a positive beauty okay so we follow each flowers and the fourth beauty if it appeared previously so we can use accountability as endpoint and use the previous and use built in the map as the start point and we can calculate the result and the for this sum we only record the partition number and if it's the first time we see this beauty then we update our map to set the perfect sum for this building okay this solution is very short it's our own solution thanks see you next time
Maximize the Beauty of the Garden
stone-game-vi
There is a garden of `n` flowers, and each flower has an integer beauty value. The flowers are arranged in a line. You are given an integer array `flowers` of size `n` and each `flowers[i]` represents the beauty of the `ith` flower. A garden is **valid** if it meets these conditions: * The garden has at least two flowers. * The first and the last flower of the garden have the same beauty value. As the appointed gardener, you have the ability to **remove** any (possibly none) flowers from the garden. You want to remove flowers in a way that makes the remaining garden **valid**. The beauty of the garden is the sum of the beauty of all the remaining flowers. Return the maximum possible beauty of some **valid** garden after you have removed any (possibly none) flowers. **Example 1:** **Input:** flowers = \[1,2,3,1,2\] **Output:** 8 **Explanation:** You can produce the valid garden \[2,3,1,2\] to have a total beauty of 2 + 3 + 1 + 2 = 8. **Example 2:** **Input:** flowers = \[100,1,1,-3,1\] **Output:** 3 **Explanation:** You can produce the valid garden \[1,1,1\] to have a total beauty of 1 + 1 + 1 = 3. **Example 3:** **Input:** flowers = \[-1,-2,0,-1\] **Output:** -2 **Explanation:** You can produce the valid garden \[-1,-1\] to have a total beauty of -1 + -1 = -2. **Constraints:** * `2 <= flowers.length <= 105` * `-104 <= flowers[i] <= 104` * It is possible to create a valid garden by removing some (possibly none) flowers.
When one takes the stone, they not only get the points, but they take them away from the other player too. Greedily choose the stone with the maximum aliceValues[i] + bobValues[i].
Array,Math,Greedy,Sorting,Heap (Priority Queue),Game Theory
Medium
909,1240,1522,1617,1685,1808,2002,2156
446
all right guys welcome to our channel code with sunny and in this video i will be talking about the problem arithmetic slices its index is 446 and it is the second problem of the series of problem arithmetic slices and note that it is going to deal with the subsequences criteria okay so before moving on to discuss this one i would strictly recommend to do this the first version of this problem like the arithmetic slice uh like in this problem the first version it is going to deal with the sub address like we need to find out the number of arithmetic sub arrays of the given array okay so that it is a valid arithmetic sequence so deleting the subarrays is like pretty much easy and you are going to deal with the oh in of n time with the help of dynamic programming but uh the problem lies here in this question like arithmetic slices second and dealing with the subsequence in this case you need to build up a db like you are going to use a dynamic programming over the elements such that the following sequence that we need to find it out should be a valid arithmetic subsequence of the given array and we are going to return the all the count of those valid arithmetic subsequence and we are going to do this with the help of dynamic programming and the hash map i am going to discuss all over that for now you what you have to do is like before solving this current problem like today's problem you need to solve this problem so that you have a basic idea what type of solution these two problems is going to demand and how we are going to interlink these two problems to find out the problem like we would be having some hints to solve this problem like a subsequence type because you would be having the idea that how we are going to transform your current solution and your ideas also to solve this problem like dealing with the subsequence part and this is going to be like very much important if you are doing the competitive programming you need to have a good idea about how we are going to link two or more problems so that you are going to easily identify what is the actual difference between the these problems and how we are going to have the best and efficient solution for every type of problem okay so let's discuss this one and uh okay yeah so let's discuss this one given an integer error nums return the number of all arithmetic subsequence of the given adding note that we need to find out the subsequence okay and that sub sequence that we have chosen is a valid arithmetic sequence let's talk about what is the arithmetic sequence it is like a and sequence of numbers is called arithmetic if it consists of at least three elements like the frequency of the number of elements like total number of elements should be at least three and the difference between any two consecutive chosen elements is the same like we need to choose a subsequence first and then that sequence of elements should be have like the total number of elements should be at least three and every consecutive element of that chosen sequence of elements should have the same consecutive difference like same difference of the consecutive elements if you focus on these elements one three five seven nine let's try to find out the consecutive difference you can see everything is true so this is a valid arithmetic sequence and this array that we have chosen right now must be a subsequence of the given array that is that has been given in the input okay so we need to just find out all those arithmetic subsequences okay and there is a definition of subsequence that is being given to us i am not going to deal with these type of definitions okay so let's look over the constraints numser.length is thousand so constraints numser.length is thousand so constraints numser.length is thousand so we will be having a o of n square dynamic programming solution to find out the total number of subsequence valid arithmetic subsequence i am telling the dynamic programming because like in most of the cases when we need to count on the total number of sub sequences for a given error under certain conditions and the constraints are these types like 10 raised to the power 3 in general most of these solutions are based on dp so you'd be thinking for that also like when i first seen this problem i was like thinking about the dynamic programming solution to be honest and here comes it is and we have been telling the dp solution okay so let's try to understand this problem with the help of examples okay so let's try to understand first the concept of like arithmetic slice like the first version of this problem because this is going to be important suppose we have this two four six seven and eight okay and this is like we'd be dealing with the sub arrays right now so badass means we need to find out the total number of arithmetic valid arithmetic sub arrays okay now you can see that uh like the valid arithmetic subarus means the sub array is having at least three elements okay so let's pick out this one like two four six so this is a valid arithmetic sub array you can see yes it is a valid one and can you pick up four six seven no you cannot pick up because the difference between four and six this two and six and seven is one so we cannot pick up can you pick up six seven eight yes we can pick up six seven eight so this two four six is a valid arithmetic sub array note that i'm talking about the first version of this problem valid arithmetic sub array okay and again is six seven eight okay and uh like this is for length equal to three can we have length equal to four like two four six seven not possible because you would be having difference as two as well as 1 can we have 4 6 7 8 no it is not possible 4 6 has the difference equal to 2 6 7 has a difference equal to 1 so it is not possible every consecutive element should have the same difference can we have the entire like entire array as our answer no it is not possible so there are two uh ways of finding like there are two answers valid arithmetic sub arrays now how we are building up the answers this is going to be important we will be finding it out with help of dynamic programming and how it is going to be done let dp of i is going to say that the total number of valid arithmetic sub arrays ending uh up to like ending at the element a i total number of valid arithmetics of address ending at the element a i okay now you can see that the sub array should be having at least length equal to 3 so here our answer would be 0 and here also our answer would be 0 now here starts the answers now if you are saying that the dp of i is going to have the like statement as total number of arithmetic slices ending at the index i means the last element is going to be a i okay if this is the last element you are going to check the previous two consecutive elements like 4 6 and 2 4 yes the difference is 2 and here also the difference is 2. so our answer would be like 0 plus 1 so our answer for this state will come out to be 1 and you can see that yes the number of arithmetic slices ending up to this position is 246 yes this is the valid arithmetic slice now you have to answer for this state you are going to check with these two consecutive elements these elements are having the difference two and one this is not possible so you will leave it as it is as zero now you will check at this position six seven eight find out the difference six seven and eight has a difference one six and seven has a difference one so total number of arithmetic slices ending at this position eight will be zero plus one that is a value at 7 plus 1 it is going to be 1 and your answer for this array would be like cumulative sum of all these tp values you can see that it is coming out to and it is matching with our brute force solution and the valid subways are 2 4 6 and 6 7 8 so in this case also you would be dealing with the idea like for answering the current state of the dp you would be dealing with the like you'd be finding out the answers for the previous two states like dp of i minus 1 and dp of i minus 2 okay like the you'd be having this solution of dp of i minus 1 and you would be checking for a of i minus 1 and a of i minus 2 so this is case of this is for the case of sub array so how we are going to modify the solution for the subsequence let's try to understand that okay so you can see over here i have taken an array and we are going to find out the total valid arithmetic subsequence of this one okay and here also we would be having dealing with the dp of i where the ith state is going to say that total number of what is the total number of valid arithmetic subsequence ending at this ai it means that the last element of the subsequence is going to be ai okay so how we are going to deal with that and you can see that here like we are not having the values of different values like you need to find out the subsequence right and let's say the subsequence is like this type like we would be having some ai being the last element and the previous element is going to be aj and let's say we have some another element a k and there are small elements to the left of it we don't care okay now you can see that the j and i is going to like k j and i is going to satisfy this relation okay and it is not obvious that k j and i is going to have hold the index of being consecutive like it is not going to be possible like four five six like it may not be possible subsequence is going to be like uh sub array is going to be like a subset of this you can say that yes subset of this subsequence but you cannot say that subsequence is a subset of subarray like you can have a k j and i as four five six and you can also have a k j and i s two five and eight also okay and in the previous case what you are going to do you are going to deal with the sub address you are going to just check out the last two elements right and here also you don't have any choice so you need to find out the difference you need to just figure it out what could be the possible value of d where d is the difference of the arithmetic slice current arithmetic slice note that a is going to be the last element right and let aj be the second last element of the arithmetic subsequence note that i'm talking about right now is the valid arithmetic subsequence we don't know the value of aj okay so what we are going to do is like let's try to fix some i like at this position okay and since we are unaware about the value of the difference we are going to i treat j over all these position okay so let me write down i belongs to 0 to n and j belongs to 0 to i okay for every i will be i treating j from 0 to i minus 1 both inclusive if i am able to do that it means that we have some certain aj being fixed and if and we have certain ai being fixed in o of n square time and if we are able to do that you can easily figure out the difference and let's call the difference as d a i minus a j okay and let's call this as like uh we need to answer for dp of i right now okay so dpf phi is the total number of valid arithmetic sub sequence ending at this value a i and this second last element being aj okay and now the here comes the very important role how we do like how do we find out the answers let's try to analyze that okay so i is over here let's say and let's say j is over here because j is going to be less than equal to i now focus over one thing that we have this a i and we have this a and the difference is already being known and this difference is t okay so we would be having something like that dp of i and this difference d okay so dp of i is going to denote the total valid arithmetic subsequence ending at this ith index and this d is the difference value that is ending at ith index and having the difference value as d now this is going to be important let's try to understand that and this value that is being given to us is some integer now the very important thing is here is that d is not going to hold some fixed value it can vary from minus i and like sorry int minimum to i t maximum okay so in that case we would be having some deep like this matrix as like this type vector like if i'm in c plus i'm doing like that vector of something hash map of int comma int we would be having this type of uh orientation of our dp okay and it is like the this is being fixed and this vector is of size n where n is the size of the given input array and we have the correspondingly mapped because this d value is going to hold any value between int minimum and id maximum okay that's why we are going to have this dp as vector of map of nt comma int okay now the thing is like we would be having aj right over here and we would be just claiming it to that we are going to have this as the valid arithmetic subsequence where the last element is a i now you are going to have some sequence of elements over here let's call it as a k and all that so our answer is going to be incremented by which value let's try to understand that okay now dp of id i is going to be like the index this one and this d is going to hold the difference should be incremented by or you it should be like holding the value right now one why i'm going to initialize dp of id with one because you can see that this is the last element and this is the second last element and this is the valid sub sequence okay and the count of the subsequence is exactly one you can see over here like this is the only one subsequence you can see aj and ai is the one of the subsequence and their difference is d that's why we initialize it with one now you can see the dp of id let me write down the first this statement and then i will explain it out will be also incremented by dp of jd why i am going to write down this statement that is whatever the number of sub valid arithmetic subsequence ending at this index j and their differences d should also be added to dp of id because whatever the sub sequence that are ending at this position they all have the difference exactly equal to d and this ai and aj is also is uh sorry is also holding the difference exactly equal to d it means that the whatever the sub sequence that are ending at index j and having the difference d can also be extended uh with a i where a is going to be the last element and can be appended with that it means that our subsequence count is going to be increased by dp of jd where dp of j is the uh index that is the total okay so let me explain some another words like uh total number of valid arithmetic sub sequence ending at this index g and having the difference as d okay so it means that your subsequence is going to be increased by this last element that is being appended right now which is ai okay so note that i'm not incrementing our answers actual answers that is i am going to return for all that uh when i will when i'm going to increase it so let me write down over here our answer is going to be increased by this value let me change the another color like our answer is going to be increased by like answer plus equal to dp of j and d now this is going to like a tricky part like why i'm going to write down dp of jd why not dp of id and the reason is behind simple like if you write down dp of id there is also one key like you are going to include the this one of the sub sequence like sub sequence of a j and a i whose length is true which is not possible and so that you need to always include that subsequence which has length at least three and if you include the answers for dp of jd then you can see that whatever the subsequence it is like up to the length so like we don't care about the length and ending at index j and having the difference d we don't care about the length i'm telling it right now again but if i will include all those valid arithmetic subsequence and i will append a i to all these subsequences that i get up to the index j and having the difference t you can see that all those subsequence length would be like greater than or equal to 3 i am appending a i right now all those valid arithmetic subsequence that are ending at j and having the difference d then it becomes the like the all the arithmetic subsequence will have the length at least equal to 3 and this is going to be valid okay that's why we are just writing down dp of jd otherwise we are going to write down dp of id which is not correct one because if i will include dpf id then subsequence of length 2 may also be included okay so let's head over to the code to analyze all these in detail where i'm going to explain the more concepts if required and i will explain the coding part majorly okay so let's move further okay so let me show the latest accepted code yes so my answer is going to be initialized with 0 and i'm going to use vector of hash map and i'm going to use unordered map and let's call it as tp and it is being initialized in nums dot size as i've already said i'm going to use the map in the beginning map in the between because the difference value is not known and it is not fixed that's why we are going to use a dpf i difference and the third parameter is the frequency okay and okay so let's iterate for every i comma j pair i know of n square time okay so we need to find out the difference also let's call it as t and we are going to find out like this one and it go it may exceed the anti-min or and it go it may exceed the anti-min or and it go it may exceed the anti-min or like it makes it max value or it may be smaller than 90 min if it is going to happen like this one like d is going to be less than 90 min or greater than int max you can see that the values that is being given to us as num supply is going to lie in this range so if the difference is going to exceed so it is always possible that like it is obvious that we are not going to get the answers because that's why i'm going to use the continue function no need to do the operation for right now otherwise i am going to say dp of id plus the subsequence length that is going to be like increased by one for up to the length for the last element ai and having the difference t because we will be having subsequence ai and ag and let's find it out whether the difference d is going to exist in dp of j or not why i'm going to do that because we need to increment your answers for this one and increment the values for dpf id also and if that value is not going to exist we are going to say continue that is move forward don't do anything otherwise increment your answers and increment your answer for the current dp of i and having the difference as d that is dp of id will be incremented by for all those arithmetic sequences valid arithmetic subsequences ending at the index j and having the difference d okay and finally written the answer this will give you all test cases first okay so if you have any doubts do let me know in the comment section of the video and i will ask the viewers to like this video share this video and do subscribe to our youtube channel for latest updates thank you for watching this video
Arithmetic Slices II - Subsequence
arithmetic-slices-ii-subsequence
Given an integer array `nums`, return _the number of all the **arithmetic subsequences** of_ `nums`. A sequence of numbers is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same. * For example, `[1, 3, 5, 7, 9]`, `[7, 7, 7, 7]`, and `[3, -1, -5, -9]` are arithmetic sequences. * For example, `[1, 1, 2, 5, 7]` is not an arithmetic sequence. A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array. * For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`. The test cases are generated so that the answer fits in **32-bit** integer. **Example 1:** **Input:** nums = \[2,4,6,8,10\] **Output:** 7 **Explanation:** All arithmetic subsequence slices are: \[2,4,6\] \[4,6,8\] \[6,8,10\] \[2,4,6,8\] \[4,6,8,10\] \[2,4,6,8,10\] \[2,6,10\] **Example 2:** **Input:** nums = \[7,7,7,7,7\] **Output:** 16 **Explanation:** Any subsequence of this array is arithmetic. **Constraints:** * `1 <= nums.length <= 1000` * `-231 <= nums[i] <= 231 - 1`
null
Array,Dynamic Programming
Hard
413
911
hello guys welcome back let's solve the fourth problem from weekly contest 103 the problem definition is that we are given to integer array person and time uh in an election the eighth vote was cast for person i and time i for each query at time t we have to find the person that was leading the election at that time uh vote cast at time t will count toward our query in the case of a tie the most recent vote among the tight candidate will win and we have to implement the top voted candidate class where top voted candidate uh initialize the object with person and times array and the query returns the number of person that was leading the election at time t according to the mentioned rules now let's see the example one uh here we have to initialize the top booted candidate class to do so we are given two array one is person and another is times then there are some queries uh where we have to return the person that was winner at the time there are some constraints that are given to us that is the person length can be from one to five thousand and the person i is also between zero to person length and we are also said that the person length and time length is equal and time is sorted in a strictly increasing order now let's see how we can score the solution first i need to save the times array now i need to initialize to hashmap first to keep track of the port of the person so let me name it person good i am initializing this hatch map with zero so the key of this hash map will be person and the value of this hash map will be the vote count now let me initialize another hash map and let me name it time winner and for this hashmap the key of key will be time and the value will be person the person that is winner at that time now let me enter it through the person and times array i need to populate the person vote added actually personal good hash map so let me populate that of p plus equal 1 now i need another variable to keep track of the winner at that time so winner let me initialize it the first person of our personality so the winner will be winner if selected person vote or winner is greater than self.person boot p otherwise it will be p now it's uh greater than because if it's equal uh then it will be p because p is the current person that is getting the vote now let me add the winner to our time winner hashmap this should be self yeah now this is it for our initialization function of the top ported candidate now let me write the function for the query of our top put it in class so what we're gonna do is just return self dot time winner of that time but there is a catch that is this time can be anything uh it is not necessarily that this time have to be an item from the times array so uh if it's not inside our time set then uh this is also not inside our time winner so what in that case what we need to do is the return the previous time which is present in our times array and return the winner at that time so let me first try to return this one and if this is this fails because if uh this time is not present in the times array then uh there will be a key road because time winner will also not have the time uh winner at that time so then i will have a key error and we will get in the accept except part and then we need to find the previous time index so let me write that will be bisect left actually what i am doing here is using binary search to find the previous time index from our times array this should be sales top times yeah now this will give us the time index of that time so what we need is the previous time index so i will just need to subtract one from it and then return sell the time winner and get the time from the times array using the time index now let's run this and see if this is accepted or not we have a runtime error spelling is strong so c pt now let me submit this again a person is not defined to you mean person saying persons so let me run it again yeah this one is accepted
Online Election
profitable-schemes
You are given two integer arrays `persons` and `times`. In an election, the `ith` vote was cast for `persons[i]` at time `times[i]`. For each query at a time `t`, find the person that was leading the election at time `t`. Votes cast at time `t` will count towards our query. In the case of a tie, the most recent vote (among tied candidates) wins. Implement the `TopVotedCandidate` class: * `TopVotedCandidate(int[] persons, int[] times)` Initializes the object with the `persons` and `times` arrays. * `int q(int t)` Returns the number of the person that was leading the election at time `t` according to the mentioned rules. **Example 1:** **Input** \[ "TopVotedCandidate ", "q ", "q ", "q ", "q ", "q ", "q "\] \[\[\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]\], \[3\], \[12\], \[25\], \[15\], \[24\], \[8\]\] **Output** \[null, 0, 1, 1, 0, 0, 1\] **Explanation** TopVotedCandidate topVotedCandidate = new TopVotedCandidate(\[0, 1, 1, 0, 0, 1, 0\], \[0, 5, 10, 15, 20, 25, 30\]); topVotedCandidate.q(3); // return 0, At time 3, the votes are \[0\], and 0 is leading. topVotedCandidate.q(12); // return 1, At time 12, the votes are \[0,1,1\], and 1 is leading. topVotedCandidate.q(25); // return 1, At time 25, the votes are \[0,1,1,0,0,1\], and 1 is leading (as ties go to the most recent vote.) topVotedCandidate.q(15); // return 0 topVotedCandidate.q(24); // return 0 topVotedCandidate.q(8); // return 1 **Constraints:** * `1 <= persons.length <= 5000` * `times.length == persons.length` * `0 <= persons[i] < persons.length` * `0 <= times[i] <= 109` * `times` is sorted in a strictly increasing order. * `times[0] <= t <= 109` * At most `104` calls will be made to `q`.
null
Array,Dynamic Programming
Hard
null
1,684
hey guys peng here so today i'm going to talk about question 1684 count the number of consistent strings so what's given it's two given a string and a string array called allowed in the so let's make let's see how it works so let's see the info right here allows a b and what is this bunch of strings so what make a string consistent is basically if we're going to check if every single character in this strings it appears in the lab so basically a appear here but these now appear here so it's not allowed same thing here d is not here so it's not but a and b all of the characters in this string is appearing allowed so consistency plus one and this thing is same thing right here but this one have d so it's not allowed so the result for this strings is two there's two consistent strings so what we can do we're gonna use a hash set because hashtag contains only unique elements so we're gonna use that to check and then basically we're going to implement this right now so we have integer for camp and then we're going to put all the characters in this allowed to hash set so we're gonna create headset first type character hold it set okay and then one of the two each character in the allowed okay and then just set up all right so next step we're going to check i want to go through each string in this words and i want to go to each character in this works in history okay so we're gonna check if the set contains the character at each string if he not contains it we just it means it's not consistent so we break we don't add to the result but if it's if we want to owe the character if we want to order character make sure yep this should be working yep and then the term complexity so for how many words the length of these words is 10 to the fourth all right so it's for the time context that is 10 to the fourth times how many what's the for each words the length is 10 so 10 to the fourth times 10 to the fifth so it's 10 to the fifth all right thank you guys have a nice day if this video helped you like it says subscribe to the channel share to your friends and college freshmen who study computer science i'm going to make this speed on terrificator fan facebook apple google see you next time peace out
Count the Number of Consistent Strings
find-latest-group-of-size-m
You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`. Return _the number of **consistent** strings in the array_ `words`. **Example 1:** **Input:** allowed = "ab ", words = \[ "ad ", "bd ", "aaab ", "baa ", "badab "\] **Output:** 2 **Explanation:** Strings "aaab " and "baa " are consistent since they only contain characters 'a' and 'b'. **Example 2:** **Input:** allowed = "abc ", words = \[ "a ", "b ", "c ", "ab ", "ac ", "bc ", "abc "\] **Output:** 7 **Explanation:** All strings are consistent. **Example 3:** **Input:** allowed = "cad ", words = \[ "cc ", "acd ", "b ", "ba ", "bac ", "bad ", "ac ", "d "\] **Output:** 4 **Explanation:** Strings "cc ", "acd ", "ac ", and "d " are consistent. **Constraints:** * `1 <= words.length <= 104` * `1 <= allowed.length <= 26` * `1 <= words[i].length <= 10` * The characters in `allowed` are **distinct**. * `words[i]` and `allowed` contain only lowercase English letters.
Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map.
Array,Binary Search,Simulation
Medium
null
1,046
welcome back to our Jess today's question is leak code1046 the last stone weight so you're given an array of integers Stones where Stone's eye is the weight of the ice stone we are playing a game with the stones on each turn we choose the heaviest two stones and smash them together suppose the heaviest two stones have white X and Y where X is less than or equal to Y the result of this smash is if x is equal to Y both stones are destroyed and if they are not equal to each other the stone of weight X is destroyed and the stone of white y has new weight y minus X at the end of the game there is at most one stone left return the weight of the last remaining Stone if there are no Stones left return zero so in example one we have the stones array the output is 1 and that is calculated as so we had two of the largest values which is eight and seven we extract those we calculate the difference which is one we add that back into the array so now we have two four one we extract the two largest values two and four which calculate the difference two and then we add that back into the array so we have two one do the same again so we remove two and one calculate the difference which is one add it back into the array we'll have three ones left and then we remove two ones calculate the difference is zero and when X is equal to Y both the stones are destroyed so neither are added back in and then we return the last Stone within the array so with this solution soon as we are calculating or seen as we are looking at the two largest values calculating the difference adding it back in a good solution for this would be to utilize heaps but within JavaScript there isn't a heap API to use but thankfully the leak code provides us with a Max priority queue that we can use interchangeably as a heap so that's what we'll do so let's run through the solution firstly we need to create Heap so a heap is a complete binary tree Filled from left to right so this is our Heap to start off with now we need to convert this into a Max Heap and in order to do that seven needs to flip with two once those flip two needs to flip with eight and then eight need to flip with seven so it'll look something like this now this is a maxi as you can see each value is greater than its children the size of this Heap is going to be six and this would be important to keep track of and you'll see why in a bit now we need to remove two largest values to calculate the difference and then add that back into the Heap so in order to extract eight from this Heap we need to flip it with the last value within the Heap so eight and one are flipped and now 8 can be removed as you can see this is no longer Max Heap so we need to converse into a Max Heap so seven flips with one then one will flip with two now we have a Max Heap we remove the largest value so seven flips with one and then seven can be removed we need to update this now to make sure that it's a Max Heap and now we calculate the difference between these two which is one and we add that back into the Heap size is now at five now we can just repeat the process so we grab the two largest values so four is flipped with one and then four is removed so if we can go here we convert this into a Max Heap and then we remove this largest value so this is flipped with one down here and then removed now we calculate the difference between these two which is two and we add this back into the so this is going to be added here then we convert it into a Max Heap the size is now full we get the two largest values two and one calculate the difference which is equal to one add that back into the Heap now the size has been decremented to three we take out the two largest values which is one and one the difference here is zero so nothing gets added back into the Heap so we're left with one size is now equal to one and as soon as size is equal to 1 we can return the value that is within the Heap if size is equal to zero however we just return zero and that is the basic structure of this solution time complexity here is going to be o n log n where it takes n operations to create the Heap and then log n operations to create the max Heap and then DQ in and on qn so add in and removing from the Heap is also going to be the login operations so time complexity in total will be n log n and then space complexity is going to be on we're restoring endnodes within our Heap so like we said in the solution walkthrough we're going to be using what leak code provides us with and that's Max priority queue and we'll be using this interchangeably as a heap so let's initialize that now we need to build this Max priority queue or this Maxi so const ellar stones Heap dot On Queue we're going to cue the stone now we need to create a while loop that checks Heap size so as long as Heap is greater than one we'll calculate the difference of the two largest values within the Heap so we need to dequeue from Heap in order to get the first largest value and we do this by saying Heap dot DQ dot element and we do that again to grab the second largest element and then as long as the difference is greater than zero we can enqueue back into the Heap so we can add that difference back into the Heat then lastly we need to have a condition in order to determine what we're going to return if Heap size is equal to zero we just return zero else we want to return the first element within the Heap we do this by saying heap.front dot we do this by saying heap.front dot we do this by saying heap.front dot element let's give this a run submit it and there you go
Last Stone Weight
max-consecutive-ones-iii
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone. We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is: * If `x == y`, both stones are destroyed, and * If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`. At the end of the game, there is **at most one** stone left. Return _the weight of the last remaining stone_. If there are no stones left, return `0`. **Example 1:** **Input:** stones = \[2,7,4,1,8,1\] **Output:** 1 **Explanation:** We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then, we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then, we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then, we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone. **Example 2:** **Input:** stones = \[1\] **Output:** 1 **Constraints:** * `1 <= stones.length <= 30` * `1 <= stones[i] <= 1000`
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
Array,Binary Search,Sliding Window,Prefix Sum
Medium
340,424,485,487,2134
977
hey everybody this is Larry this is day two of the Fe February man I'm losing months I'm losing years with years this uh March day two of the March Leo daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's prom I click here because sometimes there is a button that's to I don't know the left side of the screen if you click it you get 10 points and you see this message here that's kind of nice anyway today's PR is 977 squares of assorted away so we'll do an extra Prim after this so definitely check that out um but yeah uh yeah I mean that's pretty much it uh hit the Subscribe button if you wanted to check that out all right so given an integer right now I'm sort of non decreasing order we turn in a way of the squares of each number sort in not in decreasing order okay I mean yeah I mean I think like they said if they square and sorting is very trivial can I find an over end I mean it's just like a merge sword right like um yeah I mean I think the idea is just like a merge sword you have you square the negative numbers you square the positive numbers and then you kind of just merge together in one away in a merge sword kind of way not a merge sword but like a the merging step of the merge sword right like a the concrete step of the right conquer that's basically the idea and I think that should be good enough so let's play around with that but I mean technically I guess we uh I'm trying to think where I could do one pass I me because the way that I'm going to do it I'm going to be very lazy to be honest uh because correctness matters more for me than doing a one pass initially anyway but I'm trying to think if there's a very obvious one pass solution and I don't know that there was a easy one so I don't know but uh but yeah so maybe you have something like um negatives positives and zero or non- negatives positives and zero or non- negatives positives and zero or non- negatives maybe I guess non- negatives is maybe I guess non- negatives is maybe I guess non- negatives is technically more accurate though now it feels a little bit awkward but yeah for x and nums and this is sorted so basically I mean you can kind of do a divide you could probably binary search for this and then just kind of like but then it doesn't matter because it's still linear right that's why I'm just going to write it in a funky way like this right negatives aen uh right so same thing right so now basically the idea here is that non- basically the idea here is that non- basically the idea here is that non- negative it's going to be in increasing order or non decreasing order I suppose if it's not unique um and the negatives will be in decreasing order right so then now um the idea is just okay so then like we said there's a merge sort thing and it's a little bit annoying but it's not a big issue right um basically W I guess if I'm going to do it this way I'll just make it a q so that I can WR things a little bit easier uh I mean without using a q you can also just use like an and like a an index tracker like for I is less than n or something like this but I find that like as I've gotten older I make a lot of mistakes with that so now I think this is a little bit cener but I don't know let me know what you think in the comments what I am too silly um right uh so basically well they're both zeros right so for the negatives we want to look at the back right so if this is less than non negatives and for non- negatives we to negatives and for non- negatives we to negatives and for non- negatives we to look at the front then we just append uh non negatives. pop left right and then else append negatives. pop uh and then now that means that what uh we can do something like I want to say okay fine right so basically it's something like this and this is just like right out of the merch um textbook I mean you could also write this in one line and I was debating doing it in Pine but I feel like this is a little bit cleaner um least like a little bit um yeah and of course the reason why these things don't matter is because both of these cannot be true only one of them could be true otherwise you know it will still be here so yeah anyway and that's pretty much it uh apparently it's where us to make mistakes though what is going on oh why did I do it this way I meant I had the science one whoops cuz H okay and they cannot be equal because they would be in the same Loop thing right let's give it some it and yeah and this is going to be linear time linear space um pretty clean I think oh and I did that similar last oh I guess last time I did do the python one liner thing but uh but yeah um that's all I have for this one let me know what you think it is a easy problem or like you know it's the know as easy I think the key thing is just trying to find a property around this thing that is in variant right and for this you know it's just about separating the negatives and the non- separating the negatives and the non- separating the negatives and the non- negatives because then now there's some property change right anyway that's all I have for that this one let me know what you think stay good stay healthy to mental health I'll see you all later and take care bye-bye
Squares of a Sorted Array
distinct-subsequences-ii
Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. **Example 1:** **Input:** nums = \[-4,-1,0,3,10\] **Output:** \[0,1,9,16,100\] **Explanation:** After squaring, the array becomes \[16,1,0,9,100\]. After sorting, it becomes \[0,1,9,16,100\]. **Example 2:** **Input:** nums = \[-7,-3,2,3,11\] **Output:** \[4,9,9,49,121\] **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order. **Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach?
null
String,Dynamic Programming
Hard
2115
1,079
so today we would be solving lead code question number 1079 and that is letter tile possibilities so uh what is the question is that we need to print all the possible arrangements for the given string and we need to print uh the count of those arrangements so okay so for this example we have a b so what is the total number of Arrangements distinct Arrangements that we can make out of it so it's a single b double A a b A B A and B Double A so these were all the possible Arrangements that we could have made out of this a b okay so moving ahead uh firstly I think we should make um character array character counts whose size will be 26. and that would be an array okay an array that would be an array okay and what we are going to do is that we need we will be uh appending the count of letters we are having in our string tiles okay so for Auto it in tiles that is for each and every character uh you just go on to counts and I T minus a plus okay that is it after this we would be having counts of all the characters in our tiles and after this we will be creating and result is equals to zero rest is equal to zero or that would be storing the count and after that um when I will be calling my function answer so I'll be passing counts and I'll be passing res that is it and after that I will be returning my arrest whatever count it stores the basic functionality would be uh in this order but as and when we get as and when we encounter any other base case we would be treating it so let us get a void answer okay and uh that takes in our count function our counts array so counts um sorry care counts that's an array and after that um we can give end Ampersand result so that makes it a void function a for Loop for iterating over each and every character length in my accounts array so for end I is equals to zero up till I is less than 26 and I plus static is that so yeah that is it after doing all this uh we need to just say if at that ith position if I add that ith character that character is there if that is present okay so if counts at I is present then please do use that character to use that character in making all the arrangements possible and if you are using that character and making all the arrangements possible then it requires to be counted in my result so RS plus if you are using that character then counts at I minus after using that character if you are making all the possible arrangements with that character then I will be calling my function that please do call rest of the characters because this character will be used in creating all other Arrangements uh in my using my other characters so just pass in counts and pass in address okay after you have used this character and you have uh appended rest resultance value please do give back this character so counts at I plus and yeah that's it and we need to do one more thing after before all this we need to just sort this tiles dot begin um no that does not requires to be sorted that is fine yeah uh because we are taking each and every character uh we are then asking uh then that uh is that character present yeah that is present so using that character uh construct all the possible Arrangements Single Character double character or triple letter construct all the possible Arrangements in carbon by S value for that character okay and uh after using that editor please do increment its value and please do return it back and that is it um count character counts for we incremented its value also rest and return rest let us see let us hope that this gets submitted um so that should be counts because each and every place you have done counts so okay that's it yeah that is accepted that took four milliseconds and that should be submitted also yeah that is submitted so that is it we can reduce the time complexity also if we uh it took around it took nine milliseconds you can reduce it so uh we can just say const Ampersand dot or Auto on constant Auto Ampersand sorry uh constant Auto i t and then counts at I T minus a and uh if that's a constant iterator but that is taking five milliseconds I think that depends upon the internet four milliseconds but the constant Auto ID is there some is this something meaningful also let us see yeah that is Meaningful that took around five milliseconds but that's same so I think that's it there is no further optimizations yeah nine milliseconds again so that is it guys if there would be some optimizations I would be commenting or I would pin the comment in this video if there would be some optimizations in this question but till now that is it and I hope the discussions was pretty in depth and I think that yeah that is it for this video and we'll be meeting in the next video till then bye if you have any doubts please do comment it down in the comment section and till then bye
Letter Tile Possibilities
sum-of-root-to-leaf-binary-numbers
You have `n` `tiles`, where each tile has one letter `tiles[i]` printed on it. Return _the number of possible non-empty sequences of letters_ you can make using the letters printed on those `tiles`. **Example 1:** **Input:** tiles = "AAB " **Output:** 8 **Explanation:** The possible sequences are "A ", "B ", "AA ", "AB ", "BA ", "AAB ", "ABA ", "BAA ". **Example 2:** **Input:** tiles = "AAABBC " **Output:** 188 **Example 3:** **Input:** tiles = "V " **Output:** 1 **Constraints:** * `1 <= tiles.length <= 7` * `tiles` consists of uppercase English letters.
Find each path, then transform that path to an integer in base 10.
Tree,Depth-First Search,Binary Tree
Easy
null
114
hello everyone so let's talk about latin binary tree two linked lists so you are given the root of a binary tree and you have to pattern the tree into the linked list so linked list should use the century noteplus or blah a little bit easy and so you are given the tree right and you have to return a linked list tree okay so uh what you actually need to do is you have to convert every left subtree to right subtree so here's a recursion case so think about it how do you actually do so um what you actually need to do is when you're going down to your children you still need to flatten right so there are two cases you cannot avoid which is flattened root the left and flatten root are right okay these two cases are not i mean are not i definitely need it right so i'm going to starting code for the tree no left so i'm going to remember my left and right we know so what would i do for uh for right now is i have to set the left to a note since i'm taking care of the left and right every single time um on the single root right because i actually traverse every single root right because flattened root the left factor and root i write at some point i would hit on the basic one right so the base case is if root equal to no you just return so let's simple right and now at the bottom i will definitely know i have to make my left to no and my right equal to left okay super clear right so imagine you are here just imagine you are at a 302 so i said to the root of left to no and root our right to three so the four is temporarily gone right but i still have a variable so i'm going to say tree no p equal to root so initially the i mean when i add here the tree note p will become root and i would say well p dot right it's not no uh p equal to p dot right that's very wrong so what does actually mean is since 4 is not here right so 2 dot right which is 3 and 3 the right is nothing right so i'm breaking out the value but after i break out the value i have to say pita right become right why because i already saw the value store the value for 304 right so i just have to make sure so the diagram will become one two three four five six and when you go back um to the top so you're still doing the same idea three dot left it's two three dollar two three uh three note right which is five and you make your left side to normal and right set right side to uh left first and then you uh traverse yes you traverse through p dot right and just at the end just connect to the right which is five connect to the full so that will be the solution and just run it and you will see what happened and yeah easy pc right so what do you think about the timing space complexity so the time would definitely be both right traverse it is every single route once and well for the value you definitely need to like keep going probably unsquare but i you don't you just do the half of the tree so whether you'll do your loop half of a tree so i'm going to say a square uh un all right so okay un square n square okay come on and for the space complexity so trillion no tree no left should know right i actually what do i actually do i for every single note i create a left and right triangle so if there's a 3 note as 2n so uh one two three four five six there are six three notes and each crinol needs extra two trino which is two to land right so that would be all different sport space and then unscrew um all the time and that would be the solution m times a 2n so uh sorry n squared sometime uh into line right and that will be the solution and good luck
Flatten Binary Tree to Linked List
flatten-binary-tree-to-linked-list
Given the `root` of a binary tree, flatten the tree into a "linked list ": * The "linked list " should use the same `TreeNode` class where the `right` child pointer points to the next node in the list and the `left` child pointer is always `null`. * The "linked list " should be in the same order as a [**pre-order** **traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR) of the binary tree. **Example 1:** **Input:** root = \[1,2,5,3,4,null,6\] **Output:** \[1,null,2,null,3,null,4,null,5,null,6\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100` **Follow up:** Can you flatten the tree in-place (with `O(1)` extra space)?
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Linked List,Stack,Tree,Depth-First Search,Binary Tree
Medium
766,1796
52
Al so this question is UN Queen 2 so if you didn't watch un Queen's one solution video you can watch it this question is similar we're going to return a distinct you know return a number of distinct solution for the puzzle so yeah we need to return a number right so it's going to be two there are two different solution so uh I'm going to type where I'm coding because all the things are pretty much the same so I'm converting the what sorry not converting I'm creating a 2d array and I'm going to notate M by n and I'm going to initial everything to be what to be dot so erase. fill R do dot all right now I'm going to Traverse the DFS and G and zero represent starting the index zero so public so it has to be a in right DFX and then chart read and then in rule right so in this case I will also have a verific a verify function method and in this case I'm going to say the con starting from zero and I'll return the count later right but how do I return the count um I have a base case I'm going to do this and return one I was say I'll make sure I put this later so I'm going to start it from the column so column started from zero and the column has to be less than the columns for the G zero and then columns plus so why are we Traverse the column in here this is because one single rule you can only put one Queen so if we increment your index your Ro index you are definitely not going to have two queens at a same rule right so you have to increment your column and triers the column to make sure you are not colliding collide with your other screen right so if what is valid I'm going to put the grid I'm going to put the rule and put a column if this is true so how do I know it's true is valid draw to the array three in row in column so we only need to check what so I'm going to just yeah I need to draw so I'm going to put Queen right here right and then so I increment my index my r index to here so I starting always starting colum zero and I'm going to make sure uh for my colum they don't have what they don't have the quins for my what so if you at here right for the column they don't have the same Queen right if you have then you are colliding and then you want to Traverse top left and top right diagonal right this will be it like these are the three Direction you are going to check because you are traversing you know you are placing Queen rule by rule and then when you place the queen rule by rule and you want to check the diagonal of vertical and the other diagonal uh Direction so this is how this should be so for in IAL z i l g uh g. lens and in this one this is meaning what I column if this is equal to Queen I will make sure I assign a q for this cell you want to return F so look at this is the fixed value we pass in I is the one we Traverse right from IAL Z to the length right so in this one the column doesn't change the rule index is changing so we're checking the what vertical right and then we need to check what uh top left diagonal and top right diagonal right so for in I = to rule minus one and then so for in I = to rule minus one and then so for in I = to rule minus one and then J equal to C minus one right which is column cus one and it should be okay so I greater equal z and j greater equal than Zer and then i- than Zer and then i- than Zer and then i- Jus if you can tell this is what going top left right so if read a i j is equal to Green you return CL all right so again this is top left and I'm going to check the top right so in R = to rule check the top right so in R = to rule check the top right so in R = to rule minus one and then what else uh J equal to col plus one and then I will still have the same I equal Zer and J has to be less than three length so it should be zero length where's my and iusus and j++ right it's going my and iusus and j++ right it's going my and iusus and j++ right it's going to top right diagonal right so if three I is equal to Queen you return false and you return true at the end right so I'm make sure I do this correctly call Okay cool so yeah if this is valid so what this is doing is I'm going to assume I place a queen at L location row column location in the GRE if this is valid I'm going to say oh I'm going to put this uh row column equal to Queen and I'm going to terse the next one three R plus one right next the next Rule and I'm going to check do I have the valet Queen for the solution right and then if I don't because it doesn't matter you place a queen and it's valid right you if I don't I need to backtrack I'm going to just assign a queen back to the dot and at the end like if you want to know which one is valid you want to check this guy because this guy is from what 0er to grid. length right if this guy is equal three. L you are out of bound and which is you want to keep traversing for what the next one but you already out of bound and it's already valid right it's already valid want to return one this is count as valid board solution right is definitely distinct because the next one you have is going to be different Queen right because there's a backrack all backtracking all um I'm going to run it I don't care okay good cool all right space let's look at space is unsquare right how about time this all of n right and this one is going to be what uh this one is going to be okay so you are going to try Traverse rule by rule so it's going to be all of them for sure but once you finish all right your next possible value so if you hold if you I'm going to create new board so imagine this is the board right all right you place this value the next possible value are these three right so you form four possible you know location you check and to three and once you pull this there are definitely two possible okay it's not correct because it's colliding right here right so next possible is going to be here or here right and it's going be two but what they are ciding right so it has to be different value so you actually you know reducing a possibility to place a queen right so it's going to be factorial for the time so if you don't believe it let's do the this guy the solution is going to be the same if you want to go over by yourself but un factorial for the time all of un this is not correct un unscare come on uh they using the hash set right so it's going to be different solution but for m is going to be n Square for him is going to be all of this is going to be represent R diagonal okay and it's called oh they have three different set I mean which is okay but I don't like it so um yeah if you have question leave a comment and I will talk to you next time bye
N-Queens II
n-queens-ii
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other. Given an integer `n`, return _the number of distinct solutions to the **n-queens puzzle**_. **Example 1:** **Input:** n = 4 **Output:** 2 **Explanation:** There are two distinct solutions to the 4-queens puzzle as shown. **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 9`
null
Backtracking
Hard
51
283
hi everyone welcome today we're going to be doing leap code problem number 283 move zeros so the problem states given an integer array nums move all zeros to the end of it while maintaining the relative order of the non-zero elements of the non-zero elements of the non-zero elements now we have to do this in place without making a copy of the array we could envision a scenario where we iterate through add all of the non-zero elements to a add all of the non-zero elements to a add all of the non-zero elements to a separate array a new array and then while we're doing that we're counting the number of zeros that's in this array and then we add that number of zeros to the end of the new array however we can't do that we can't create a new array so what we're going to do is we're going to use pointers okay we're going to use a left pointer that's going to be keeping track of the leftmost zero that we've encountered and then the right pointer is going to be looking for a non-zero number that we can then swap non-zero number that we can then swap non-zero number that we can then swap with that leftmost zero okay so if you envision a an array with two pointers the right pointer is going to be the fast pointer that is incremented every single time and the left pointer is only going to be incremented after we do a swap okay so let's go ahead and get into the code we're going to set a left pointer to zero and we're also going to set the right pointer to zero but it's going to be part of our for loop okay so we'll say pour right in range length of nums we're going to check to see if that right pointer is pointing to a non-zero number so if nums pointing to a non-zero number so if nums pointing to a non-zero number so if nums of right does not equal zero then we're going to do a swap okay so i'm going to say temp equals nums of right then nums of right we're going to set it equal to nums of the left and then nums of left we're gonna set equal to temp and then now that we've done the swap we can go ahead and we can increment num uh the left pointer okay so just to show you kind of an example here um so let's say we have this is our given array and we have both of our pointers starting out at zero okay so we encounter zero uh nums of right is pointing to zero that's not a non-zero number so we keep going not a non-zero number so we keep going not a non-zero number so we keep going through the loop we continue okay so numbs of right is now pointing to zero num uh sorry right pointer is now pointing to one and the left pointer is still pointing to zero so since the right pointer is pointing to a non-zero number now we can go ahead to a non-zero number now we can go ahead to a non-zero number now we can go ahead and do a swap okay so this after the swap the first swap we're gonna have one zero okay so the right pointer remember was pointing here and the left pointer was pointing here but now that we've done a swap they're both going to be incremented okay now the right pointer is pointing to a zero we don't do anything we just increment it again okay so now the right pointer is pointing to a non-zero number pointer is pointing to a non-zero number pointer is pointing to a non-zero number now we do a swap so now we swap the three with wherever the left pointer was which was it was still over here now that we have swapped three and that left most zero we can increment both so now the left pointer is pointing here and the right pointer is pointing here then we swap the 12 with the zero and we have the numbers the non-zero numbers in order numbers the non-zero numbers in order numbers the non-zero numbers in order and all of the zeros at the very end okay so let's go ahead and run that just to make sure that works oh num is not right it is nums okay and let's go ahead and submit that to see if it works with all test cases and it does so there you go that is how you solve leak code problem number 283 move zeros
Move Zeroes
move-zeroes
Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. **Note** that you must do this in-place without making a copy of the array. **Example 1:** **Input:** nums = \[0,1,0,3,12\] **Output:** \[1,3,12,0,0\] **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 104` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you minimize the total number of operations done?
In-place means we should not be allocating any space for extra array. But we are allowed to modify the existing array. However, as a first step, try coming up with a solution that makes use of additional space. For this problem as well, first apply the idea discussed using an additional array and the in-place solution will pop up eventually. A two-pointer approach could be helpful here. The idea would be to have one pointer for iterating the array and another pointer that just works on the non-zero elements of the array.
Array,Two Pointers
Easy
27
88
hello everyone elite code a day today our problem is leaked o88 merge sorted array is a very important algorithm it can be used in merge sort and finding the medium of two sorted arrays so let's get started the problem is given two sorted arrays num1 and num2 and merge them into names one has one sorted array so basically the input of our function is nums one and the lens of num1 num2 and the lens of nums - and the tricky part here is we of nums - and the tricky part here is we of nums - and the tricky part here is we don't need to return anything but modify names one in place instead which means we just put all the elements into names one let's look at this example so nums one equals one two three zero announce two is two five six as we can see we already got places for names - in terms one actually so names - in terms one actually so names - in terms one actually so basically we just need to put all elements in place in terms one okay so one solution we can think of is just to add those two lists in Python and then more and then store them right that's a very simple intuition and let's look at the code so basically if n is zero which means Nam's 2 is empty we don't need to do anything because nums 1 is already the result then we just return otherwise we will put the last n elements in lamps 1 as in as nums 2 and then sold them so this is very simple but the time complexity for this solution is M + n log n + n because we solution is M + n log n + n because we solution is M + n log n + n because we use a sword here so can we do better the answer is of course yes so let's think try to think about a Big O M plus n tie which is a linear time complexity algorithm like we talked about the tricky part is do to modify names 1 in place so how do we do that because let's talk about let's think about this example when we somehow change names one by the number from Lambs - we don't want to want our from Lambs - we don't want to want our from Lambs - we don't want to want our Lambs one to disappear you know so that's why for this algorithm we need to first save names 1 we don't want to our lambs one element to disappear and also let's think about the algorithm how to merge the two story array actually it's quite simple right the murder the story means from small to large so since num1 and num2 are already sorted which we didn't using use this information in our previous solution we can think about every time we need to compare the current element from num1 and num2 if the current and we put the smaller element into the current situation right so the idea is to use two index 1 and index 2 to record the current position or index from the two arrays like I said if one of the array if nums 1 is smaller than m2 then we put nums 1 into the final result and we move index 1 in terms 1 - right otherwise lambs to index - is - right otherwise lambs to index - is - right otherwise lambs to index - is larger than 9 1 index 1 then we put the Lambs - to be the current smaller Lambs - to be the current smaller Lambs - to be the current smaller element and we move index 2 this is the main part for this algorithm but we still need to think about some edge cases let's say what if after this while loop there are still remaining there are still some remaining elements from Nam's 1 same or Nam's - so elements from Nam's 1 same or Nam's - so elements from Nam's 1 same or Nam's - so here we talk about if index 1 is already m which means we have used up all the elements from arms 1 but there might be still some elements from nums - right still some elements from nums - right still some elements from nums - right so we directly add those names to remaining parts into nums 1 it's the same case for it's the same for when index 2 is n which means we used up all the elements from Lambs 2 then we just append all other all the remaining elements from Nimes 1 behind that's it for this algorithm if you think this video helps please subscribe my channel thanks for watching
Merge Sorted Array
merge-sorted-array
You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively. **Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**. The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`. **Example 1:** **Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3 **Output:** \[1,2,2,3,5,6\] **Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\]. The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1. **Example 2:** **Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0 **Output:** \[1\] **Explanation:** The arrays we are merging are \[1\] and \[\]. The result of the merge is \[1\]. **Example 3:** **Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1 **Output:** \[1\] **Explanation:** The arrays we are merging are \[\] and \[1\]. The result of the merge is \[1\]. Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1. **Constraints:** * `nums1.length == m + n` * `nums2.length == n` * `0 <= m, n <= 200` * `1 <= m + n <= 200` * `-109 <= nums1[i], nums2[j] <= 109` **Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time?
You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution.
Array,Two Pointers,Sorting
Easy
21,1019,1028
435
hey guys it's off51 here and today we're going to be solving non-overlapping going to be solving non-overlapping going to be solving non-overlapping intervals in this problem we're given an array of intervals where each interval represents a start time and an end time and they want us to return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping so what does this mean non-overlapping so what does this mean non-overlapping so what does this mean exactly well first I start by defining what an overlapping interval is in this problem an overlapping interval is only if we have let's say we have an interval here going from one to three and we have another interval going from two to four this would be considered an overlapping interval because this 2 interferes with this interval here in previous interval problems if you had an interval that went from 1 to 2 and another one that went from two to three then it will be considered overlapping because they overlapped here but for this problem this scenario here is not considered overlapping so that's just something important to take note of so now that we understand what an overlapping interval looks like let's try and come up with a solution so first things first we're gonna have to sort this intervals array here because if you remember the last problem there was is no faster way to compare intervals without them being sorted so our algorithm is already going to be n log n time so now we have our intervals list sorted and we can start comparing them and we're going to have a previous pointer pointing here and a current pointer pointing to the second interval and we check are these intervals overlapping well let's take a look this first interval here ends here and the second interval starts here so that means there is overlap and as you can see in the problem they want us to return the minimum number of intervals you need to remove to make the rest of the intervals not overlapping so we have a choice here do we remove this interval or do we remove this interval well as you can see there's one in three interval overlaps with two intervals so if we were to remove just this one here there would be no overlap between the rest of the intervals but if we remove this interval here instead we'll get another overlap over here and we would have to remove two intervals in the end to make them non-overlapping so in the to make them non-overlapping so in the to make them non-overlapping so in the end we want to remove this interval because this way we would only need to remove one interval so the rest of the intervals are not overlapping if we remove this one then we would have to remove two at the minimum for example we would have to remove these two so that they're not overlapping so how can we Define that in the code well as you can see this interval has a later end time than this one so we can just say we want to keep the interval with the lower end time and delete the one with the bigger end time this way we have a lower chance of having more overlapping intervals so for this example here let's say we actually deleted this interval here well now we don't want to move the previous pointer to this one we just want to move the current pointer to the next interval and now we would check if these two intervals overlap and clearly they don't so we would just move our current pointer again and then we also want to move our previous pointer to the one we're just currently looking at since there was no overlap there and that would be our latest interval so now for our last iteration we check if these two intervals overlap and as you can see they don't overlap so in the end we will just return that we deleted one interval and that is correct here as you can see and that's basically the whole algorithm our time complexity for this is going to be o of n log n because we have to sort array and we're also going through it once and that would just simplify to obn login and our space is going to be constant because we're only using a variable to keep track of how many intervals we've deleted and now that we have that let's get into the code to start we want to sort our intervals array by start time so we can just do intervals.sort in Python and that should intervals.sort in Python and that should intervals.sort in Python and that should sorted by start time next we want to initialize our count variable and this is going to keep track of how many intervals we deleted we don't actually have to delete them we just have to keep track of how many we should have deleted next we're going to initialize our PDS pointer but we actually only need the endpoint because that's what we're comparing so to start is going to be the interval at the start and we're going to take the end point of that and just store it there next we just want to iterate through the rest of the intervals so we're going to do for I in range starting from 1 all the way to the end of the intervals list and now we're going to check if there's overlap and the way to check that is do if the previous end is greater than the current interval start time then that means there's an overlap so as soon as we have an overlap we're going to increase our count by one and next we're going to update our previous n to be equal to the minimum between our current previous end and our current intervals end so this way we're guaranteed to have the smaller interval which means we're going to have less overlaps so there's no overlap all we want to do is update our previous end to be our current intervals end and then at the end we can just return our account and that should work so as you can see this code is pretty efficient and now I'll go through the code manually so here I've just been drawn the example from the problem that we've been doing and it's already in stored in order so we're good here and I've also initialized these two variables to what they should be so our count is zero and our first interval's endpoint is two so this is also done and now we just iterate through our intervals array starting from this index here so let's see do these intervals overlap well our previous end is 2 and a start time for our current interval is going to be one so that means there is overlap so we're going to increase our account by one so now we have one interval deleted and our previous end is going to be updated to the Min between our current value or our current intervals and time our current interval's end time is 3 and the previous end is still 2 so that would be the minimum so we keep it as two so now we go to our next interval which is going to be 2 and 3. so let's see is there any overlap our previous end is 2 and that is not greater than the start time of our current interval which is also two so instead we just update our previous end to be the end of our current interval so that's going to be updated to 3. and now we take a look at our last interval which is three and four and we check if there's overlap our previous end is 3 and that is not greater than the start time of our current interval which is also three so we're going to update our previous end to be the endpoint of our current interval which is four and now we're done going through our intervals list so in the end we just return our count which is one and that is correct we only deleted this one interval up here which was one and three and that is the minimum amount of intervals we can delete so that the other intervals are not overlapping if this video helped me in any way please leave a like And subscribe thanks for watching and I'll see you in the next video
Non-overlapping Intervals
non-overlapping-intervals
Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_. **Example 1:** **Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\] **Output:** 1 **Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping. **Example 2:** **Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\] **Output:** 2 **Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping. **Example 3:** **Input:** intervals = \[\[1,2\],\[2,3\]\] **Output:** 0 **Explanation:** You don't need to remove any of the intervals since they're already non-overlapping. **Constraints:** * `1 <= intervals.length <= 105` * `intervals[i].length == 2` * `-5 * 104 <= starti < endi <= 5 * 104`
null
Array,Dynamic Programming,Greedy,Sorting
Medium
452
4
hello hi guys today special 10 medium to sorted rs.100 s the name suggests in vitro sorted rs.100 s the name suggests in vitro sorted rs.100 s the name suggests in vitro fertilization of different media not for example with spirit is giving this 232 mere 30 two years to come into one single are not a result there will also be sorted towards intermediate There is no divide rule in mid-day meal in school Subscribe &amp; Tools and Subscribe &amp; Tools and Subscribe &amp; Tools and your recent Airtel Two Venus broke in this Meena beach 15 Subscribe &amp; Finally Bigg Boss stopped being the host subscribe comment and subscribe to learn how to 5282 323 325 subscribe for you liked The Video then subscribe to The Amazing Festival Subscribe Now to Receive New Updates Reviews and News Quote Mirch Se Mile Mainten Voucher Mein To Kaam To Pehle Match On Which Channel To Cash Withdrawal Number Film Is Film On Annual Plans And 2.23 Limit Phir Bhi Answer And Plans And 2.23 Limit Phir Bhi Answer And Plans And 2.23 Limit Phir Bhi Answer And Similarly For Even numbers pen friends name posted 11th and 12th in the eyes of whose numbers have slept for watching this noida employees painter wedding dresses pages pay account student elements of meeting in the middle of keeping you very difficult to withdraw from mode of do to go THROUGH IT CAN BE REDUCED TO A VERY COMMON INTERVIEW'S DEFINITELY DUBED CREATION'S ALTERNATIVE ARRANGEMENT, Example Number Two, of The Five Elements of Obscuritism Subscribe Button Two Three 686 8080 More Subscribe A Direct No Valid Notes Some Time Ago Will come up with solution all the super model of solar light on the subscribe our skin care number of elements of wealth plus 2 and in this will be coming from which are the total number of difference of the total number of subscribe this Video give maximum After this to hard work minimum wages to ms wire set pin code fog maximum from the meaning of this subscribe 09:30 m coming from what is the 09:30 m coming from what is the meaning of this subscribe 909 difficult maximum do Volume Minimum On Decided To Give Darshan To Give Me Your Comment For The First Subscribe To Comments With 12322 - 1 - Comments With 12322 - 1 - Comments With 12322 - 1 - Number Of This Number Subscribe Alarm Set Point Is Not Very About That * Weeks Consider It Only The About That * Weeks Consider It Only The About That * Weeks Consider It Only The First Tasty Five Elements In Order To Benefit From This Features You Will Come To Know From All Way Need For Speed ​​No Limits For Speed ​​No Limits For Speed ​​No Limits For The First Time Vinod Must Subscribe This Channel Quote 10 Number 330 At Midwicket 120 12th Part Number Se Right This Will Give Me The Number Of Lemon Subscribe Your Flash Light Condition Is To-Do List Are You All Old Is Condition Is To-Do List Are You All Old Is Condition Is To-Do List Are You All Old Is Gold Election 2014 34 Premise Already Spotlight Strong Condition Solid Entertainment Analysis Army He Does Not But Not To Partition And Correct Position To Find Me To Citric Acid Left From Subscribe and subscribe the Channel White Will Not Work in This Truth Can See All the Partitions in Partitions Sexual subscribe The Video then subscribe to the two Dungra First Messenger First of Soul Witch Head Office Late Every Second of Lots of 500 Total Number of Elements in First House And Sacrifice To Always 500 Hair Oil And Gas Index Of Partition State With Good Haft Tak Petition For Watching This Is Not Followed By All The Subscribe My Channel Subscribe Partition Of Its Ok Album 2018 Egg Subscribe 263 Not Following Said Subscribe This is Not Transferred From This 252 98100 subscribe and subscribe the 1999 Liquid Liner Only and Only Waxing - Minutes and Share subscribe The Waxing - Minutes and Share subscribe The Waxing - Minutes and Share subscribe The Channel Two Is Not Less Than Rs Subscribe In As A Girl Where Is Not Less Than Two Subscribe Not Be Satisfied And Answers And No One But Will Need A Two And Three To Go With It Is Question And Subscribe Jhaal Suhavani Kalimal Number 13 Sex Romance Life In Ok Please Contact Us Partition Middle Of Partition 353 Automatic 9 News Room Report Subscribe Now We Are Not work correctly and not at all subscribe nuvve subscribe now to the first in the that checking from here from the movie the partition on a maiya hum mirch a 1500 sirf pm me remind element to the right side this photo I limited the left side subscribe The Channel These to back to calculate pregnancy figure usually a limit to left side how to make pressing elements together side and listen or check novels and similarly say by chance partition no duty will be similarly the partition like this is not right The Short Period You Will Not Move To The Side Of Superintendent Anil Sehgal Take Place At Some Point This Favorite Song Partition Will Not With subscribe Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Reduce Time Complexity Difficulty And Partition In clt20 One Third Poor Harlow Will Be Equal To Zero Pomegranate Hybrid Equal To What Is The Foundation For Pyun This Loop Is Requested subscribe this Video subscribe to Way To The Number 21 Number - Number 12192 Calculate 182 Minimum Volume Bluetooth - Infinitive Number Other Way To Bluetooth - Infinitive Number Other Way To Bluetooth - Infinitive Number Other Way To Take everyone aa the cutter man - wats partitioning over take one cutter man - wats partitioning over take one cutter man - wats partitioning over take one element product ok cement limited differential khattu sweater shrink 2012 take and minimum otherwise 12322 ki kattu minus one ok notification light it calculate defeat 1283 right side saugandh noida par katwar and lemon into thin but inserted After one is equal to take devices off do that similarly just write this kept on these to ne lord will be n Sharma likes this is otherwise it will be a great you after cut ka naam yeh jsna ledush wali hoon saaf L1 L2 always notification for The conservation of water in the condition of selecting over 100 redmi 5a reference battles alone were too short bodhi garlic r1 r2 selvan villages in hardoi to shri krishna vadh diye subscribe features album will be blessed with a baby how to check airtel mein balance * * * Partition Will Know From Apne Ruthe Yaar Tu Bhai Sahab Thanks For Partition We Left Side Sunna Institute For Eve Thursday Morning No Data Partition Side Value Festival Not Understood And Tried To Partition Over And Subscribe To Make - To Consider The Left Side Give Twitter and 150 System Case Diagram Look Like Album 2018 and 19 This Channel Subscribe Now Subscribe A Message Creator Saver Mode UP Wave Right Morning Automobile Partition Summit In This Will Not Go To Partition To Right Side Subscribe Now To Partition Will Be Decided Only for example subscribe to you are you to will lose answer weir values ​​and you are you to will lose answer weir values ​​and you are you to will lose answer weir values ​​and returning will check weather its elements and number to 20 its one number famous festival number of elements for doing with doing maths of heaven and to plus minimum of R1 r2 rights will of Meaning of this true values ​​with will of Meaning of this true values ​​with will of Meaning of this true values ​​with answers but its and number five elements with this condition is not true will come on this number will return from all evil returns from minimum of 91030 condition subscribe and subscribe the Channel And subscribe The Amazing 2009 High value is equal Two One Two Three 500 Nov 14 2012 Salo Plus Hi 520 Classification Ka 12511 Stranded 2.2 Is What 5 Minutes 10225 - 302 Stranded 2.2 Is What 5 Minutes 10225 - 302 Stranded 2.2 Is What 5 Minutes 10225 - 302 Suthri Over and Over Sunao Family Values of Silver 1251 Novel Work Is Cotton Study - 1929 2012 Basically Three Two - 1929 2012 Basically Three Two - 1929 2012 Basically Three Two To Bookmyshow Again Pressed Dishes Our Viewers Partition In Singh Album 2018 Wali Sunawai Of Which Will Agree To Welcome To Come Into This Not Know How To Move Was Left Right Now What Is This Ka Rate But Others They Not Discussed And Decided That Correct Cut Food Bill This Software Way * Moonga Hath Question To Software Way * Moonga Hath Question To Software Way * Moonga Hath Question To Here No Data Partition Can Either Right That Partition Of Way 623 Doobie Most High For Over To Hours Recent Posts By Others On Left Side Sunn Dhan - 151 - Vikram Left Side Sunn Dhan - 151 - Vikram Left Side Sunn Dhan - 151 - Vikram To - - - 90 Switch Off - - - 90 Switch Off - - - 90 Switch Off Nuskhe Reforms That Supreme Sacrifice At Hue That Was Eliminated From Everyone Influence From Where To Happen Something Like This Drive What You Will Always Love You Want To Know What Is The Formula of 102 2012 this Video not support to is equal to 4 ko nomenclature principle satisfied with his condition has no right to this album Greater Noida to no right one should not be the first president to greater than normal Aircel this great alarm Subah Arvind second hand SWIFT TO * WIREMAILS TO THE RIGHT SIDE KNOW WHAT HAPPENED SWIFT TO * WIREMAILS TO THE RIGHT SIDE KNOW WHAT HAPPENED SWIFT TO * WIREMAILS TO THE RIGHT SIDE KNOW WHAT HAPPENED THIS CUT YEARS WAN ODIS WHILE THEY REFLECT IN PICTURES AND PARTITION HIS DEMONS OF HAIR TO THE RIGHT SIDE POSITION 2025 THE FESTIVAL OF KNOWLEDGE IN THE BLUETOOTH OFF NOVEMBER CHILDREN'S TO HIGH VALUE CERTIFICATE WAY Want Ashok 152 Plus Two By Two Main Stud Sir Sunao Ya Going To Cut To Values ​​From Everyone Cut To Values ​​From Everyone Cut To Values ​​From Everyone That And Free Passes From Are To Cell Total Number Of Elements Shift Cutting 243 15th Of This Month Will Get From Ka 225 - 15th Of This Month Will Get From Ka 225 - 15th Of This Month Will Get From Ka 225 - To Which Soil 182 R1 r2 values ​​to heaven where to To Which Soil 182 R1 r2 values ​​to heaven where to To Which Soil 182 R1 r2 values ​​to heaven where to be of immense 64 182 will be battery saver 9680 se much so everyone of difficult this for its correct subscribe this album greater noida to celebrate pomegranate finally reached this situation is lesson to invent for so they will get from make of This True Values ​​From This True Values ​​From This True Values ​​From This Research Sudheesh Tourist Recent Minimum Of This 272 Behavior Media Ventures 6800 Solution Who Win The Basically Mid-19th Monday Solution Who Win The Basically Mid-19th Monday Solution Who Win The Basically Mid-19th Monday Subscribe Point Is This Point Subscribe Now To Receive New Updates Time To 9th Minimum Of Small Issues There Are Two The - Research Shows That Way Are Now You Two The - Research Shows That Way Are Now You Two The - Research Shows That Way Are Now You Must Be Thinking Of Two Different Quotes For Invitation To All Main And Beaten And Notifications Video then subscribe to the Page if you subscribe 12322 orders to get and keep to minimum that now you Might we solutions people have done in one place and two plus one by two in that case instead of taking money from one or two you can take off maths of Elva Edison developed tools and give one extra element in the life instead of them he gives the Answer included after minimum of and not poetry singing the latest number to previous 181 number 90 plus two If you having this video for boy like share and subscribe
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
969
hey what's up guys chung here um so this time let's take a look at another uh lead called problem number 969 uh pancake sorting so you're given like an array of a you can perform a pancake flip with a number integer k what you can do with the k here is you can just reverse all the elements before k right and you can do it as many times uh you can do many times of this kind of k values reversing and then it's in the end you need to like basically sort this array right the any valid answer that sorts at the rate within 10 times the length of a will be a charge that's correct right so let's think about this problem here right so for example let's see if we have this uh example here three two four one right so the most intuitive way to my opinion would be like this kind of similar like a selection of sorts what does it mean so basically every time right every time we find the most uh the biggest number why we can do that because as you can see here a i is the permutation of the uh of one to a length of a right so what that does mean it means that if we as long as we uh we loop from the end right we can always find the current maximum number right so because so that's what it means is every time we select the current maximum number right in this case it's going to be a four let's say for the step one right step one we choose four which was four and then what we need to do is we want to move this four to the end of this uh of this array right so how can we move the four to the end of array uh remember all we can do is the uh is to re do some reverse right so in order to move this 4 to the end of this array here we need to somehow move this 4 to the beginning of this array so in that case then we can just do a another reverse from with the last one then this four will become the last one right and then let's do it uh again uh for each of the number right so what does it do what does it mean it means that in this case let's say the first step we want to we choose four and then we want to move four to the end of this array right so what do we do a reverse of four right we do a reverse of uh the index of four which is will be uh the k will be three right k will be three and after we do this reverse of k to three what do we have four two three one right and then now the four is at the beginning now we can simply do another reverse with the last one right and then we do a k equals to four right and now the uh will be like uh one three two four right so now the four is that is the end basically we're done picking up we're done like uh processing the four right now with step two we have to uh we need to choose three here right we can use the i here right to keep track of the uh we should we choose three right and now we find the three index right so what's the index of three it's gonna it's one right then we do a k equals to two right because we now we are processing three right first we find the index of the current numbers we're processing and then we just do a reverse from this index right since the case one base will do a plus one the index is one so we do a k equals two indeed so now after this step three will be at the beginning right and then we will do what we'll reverse remember at this moment we already finished done we're already done processing the four so now we can only reverse with this element right because we don't want to touch this before anymore right so we're going to have like so this is going to be the m minus one so we can when we do the reverse of the second step we'll do a reverse at the n minus one which in this case will be uh one two three right will be three so after this is done it's going to be uh two one three four right so now the three and four is done are we all we are is left is two and one we just do it recursively until we process all the numbers right yeah cool i think that's pretty much it is okay let's then try to code this thing right so we're gonna have an answer here uh let's do what um n right what is the n the length of a right and so we first basically we will process all the numbers here right all numbers in range uh 1 to n plus 1. uh let's see um now we don't have to do m plus one let's do a n here uh yeah you know what actually let me do this for number in range in and plus one because i want to do it like to one yeah minus one because if there's only one left we don't need to uh we don't need to continue doing this thing right so since this is like the permutations right it's a permutation of n so every time the i means it will basically means the number here right so the i will be the number itself for the for our current biggest number right and what we need to so now the first thing we need to do is we will find the index of this number right in the a here right so the index will be what would be the a of this i right uh you know what let's call it number here right that'll be better i think and the last one will be one yeah actually the last one will be two here yeah uh will be one here because uh if there's only one left we don't need to do anything so we only need to do the sorting until there are until they're like two until there are like more than one element in this array so we can just stop at add two here i add one here sorry at one here and then we find the index of that current of the current biggest number right and then we do what we do uh we do a uh we are we reverse the uh until case right so that's gonna be the index plus one right so we reverse this one equals to the reverse right reversed a index plus one right oh sorry this thing is here this we are reverse this we reverse this uh do the first re reverse and then let's do an answer here uh i'm gonna create the answer here dot append right append what's the index plus one right that's the first reverse and then we do we reverse the rest of this uh we do another the second reverse right which will be the uh from zero to uh in this case it's going to be the in miners uh n minus i so the first one is n yeah to the end itself right because we are the end is decreasing right now so we can just use this end to do the reversing in this case and then reversed right a dot n right and then we just do another answer dot append pen n right then we can just return this thing let's see yeah i think here is uh let's uh i think the naming convention naming is a little bit confused here so that's the current maximum number right the maximum number let's do a current maximum number here that's the uh and we'll be finding the index of that of this number right so we'll be using like the index of current number right and then we do the index we are we append but here and here uh the maximum number itself will be the position we do the second reverse because it's a permutation and if we loop through from the beginning to the end of here sorry to be the end and then that's the final number right let's see yeah so like i said so since we're doing since we know it's a is a permutation of everything so at so the if we loop this n the length of n uh from the biggest to the smallest then we're getting basically we're getting the mixed number free every time right and then once we have the max number of the current step we'll basically get the index from it right and then we just re a reverse do a reverse of the of starting from that index the reason we do a minor plus one here is because k is one base and the index zero base right so that's why we do uh in order to do a case uh reverse we do we start we do a starting from index plus one we do a reverse and then we assign this one to the a and then now we have the big current max number at the beginning of the a right now we just need to do a the second reverse which will be from the beginning to the end will be based on the current max number right because every time when we are finished uh the fit processing of the previous max number the end the ending point will be decreased by one which happens to be the same as the max number here right and seems so we can just simply use the max number to record the second a reverse so that's how we do it so three four that's the first that's when we process uh four and this is when we plot two and three is for when process three and one h2 is when we process one i'm sorry it's when we process two here we stop at one because if there are like only one right only one element in the array we can just simply stop because there's no need to uh to sort it again since there's only one left right that's why we stopped from one not zero it could be starting to start from stop from zero but doesn't make it doesn't do anything right yeah so that's how we do uh the reverse basically just uh similar like uh select uh selection sorting instead we'll be utilizing the uh these two reverse to move the current the next uh biggest number from this array to the end of this array yeah cool i think that's that should be pretty all i can think of this problem yeah okay again thank you so much for watching the video and um yeah i'll be seeing you guys soon bye
Pancake Sorting
number-of-recent-calls
Given an array of integers `arr`, sort the array by performing a series of **pancake flips**. In one pancake flip we do the following steps: * Choose an integer `k` where `1 <= k <= arr.length`. * Reverse the sub-array `arr[0...k-1]` (**0-indexed**). For example, if `arr = [3,2,1,4]` and we performed a pancake flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`. Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct. **Example 1:** **Input:** arr = \[3,2,4,1\] **Output:** \[4,2,4,3\] **Explanation:** We perform 4 pancake flips, with k values 4, 2, 4, and 3. Starting state: arr = \[3, 2, 4, 1\] After 1st flip (k = 4): arr = \[1, 4, 2, 3\] After 2nd flip (k = 2): arr = \[4, 1, 2, 3\] After 3rd flip (k = 4): arr = \[3, 2, 1, 4\] After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted. **Example 2:** **Input:** arr = \[1,2,3\] **Output:** \[\] **Explanation:** The input is already sorted, so there is no need to flip anything. Note that other answers, such as \[3, 3\], would also be accepted. **Constraints:** * `1 <= arr.length <= 100` * `1 <= arr[i] <= arr.length` * All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`).
null
Design,Queue,Data Stream
Easy
null
1,854
hello everyone so in this video let us talk about an easy problem from lead code the problem name is maximum population here so you are given a 2d integer array logs where each log is a starting like the birth and end of a particular person like you can say the eighth person so you can assume there's a tongue and you have some logs like whether like when a particular person is born and when that person is like dead so the population of some year x so at any year x the population is the number of people alive in that area okay and you can check it from the logs so you just have to tell that what is the area like the first area like not area the first year in which there are maximum people living that's the whole problem now you are you might be saying that how you can check it out so let's say that this person is like alive from 2013 to nine not 213 1993 to 1999 as well as this person is alive from 2000 to 2010. so you will just check that like at which time maximum people are alive okay that's the whole problem okay so how you can check it out in multiple ways the very brute force way i can think of is because uh they are at most hundred logs at and at most also year is also in a very uh finite amount so what you can directly do in a very brute force way is that i want to give some answer as an ear okay so the year will go from 1950 to 2015. so check every year okay take every year let's say my first is okay how many people are alive in 1950 now you can check it out for every year iterate over this logs array and check that whether this person is alive between nine like whether this person is alive at 1950 now you can check it out the logs is given that it like this person is alive from 1952 and 61. so if this person like 1950 lies between the like the birth and death of this person then that person will be live at 10 50. so for every year you can check out for this person that whether that person is alive for every year like this year so 1950 how many persons are live 951 how many persons are like so you have to do an o of n over this array for every year from 1952 to 2015 okay and just check it out at which is the very first year at which most of the people are alive that's overall but can we do something better yes we can because the whole problem revolves around that i have some range okay that person is alive from this to this so why not create some sort of ranges and just like combine them out and find out uh like for what range it is maximize so what i'm trying to say is that we will be using uh cumulative sums here so what we're trying to do is let's say that just make an array a very large array from let's say 1950 to return 2015 okay so every block will denote one of the years like this every block will do that one of the years like now let's say one of the persons is alive from this year i'm not renting every year let's say because it will be very large array but let's say this person is live at 1952 and it goes till this that is 1999. so this is the segment this person is alive maybe some other person is alive from this part to this part so another person is like from this part to this part and so on so they're different segments okay every person will be alive on this number line of ears now what you can do is like whenever this person is alive from this part of this part you can update every year by one so you can initialize everything to zero like every year this like there is no person alive at this particular point now this person will be right from this to this year so for every year you understand that there will be one incremented because that person will be alive from this to this segment so instead of incremented one every time it will be again making it of n you can just do that i will do in a very later stage but i will mark that this person will be alive from this part so mark this block as one and this person will die at this point let's say so it mark it at minus one it is a very standard type of approach and what we do is that we will start the marking at which the like the segment starts to be one and if you want to like fill all the values between this segment okay with a single value i'll just mark the very start with the plus value and the very end with the minus value of the same number so it is one so minus one if it is two then two n minus two so what we are trying to do is that i want to update this whole segment with one but i will not be doing it currently because if i do currently every for every range it will be o of n into often so of n square but i will not be doing that what i'll do is i'll just update this o of one like one at the very beginning and one at the very end now i will do this for every person like this person will be uh like alive from this area to this area the other person will lie from this area to this area so minus one or maybe some this one to this minus one so i will be now filling out the whole array with ones and minus ones if two ones land on the same point i will just add them so that two persons like uh what you can say born at this particular point so start their journey at this so two and minus one and so on so now my array is consisting of some numbers now what i'll do is i will iterate over this whole area from left to right and keep on adding these numbers out because what i actually just mean is that keep on adding one and minus one means that now this person will be ending like any person will be ending so now don't add money like one so now make it zero hope you get the point so if there are two do not add two like two people are here two people here and then one people died so now one only is left now one people also right so now zero so this defines out how many pills are live and it will only do one o of n operation from left to right in which i will be updating out how many people are alive at that particular point in that segment and the end we just maximize that so it will be done in o of n only by just iterating over this whole like years array instead of like join get for every year and just checking out of n so it becomes very uh easy for now so let's so we will be doing o of n for iterating over the logs array to update this one and minus one and then again it read over this whole of n to find out the maximum value in the initial case it was nested of n into o of n now it is only o of n so it is a very uh very great time complexity optimization so what we're trying to do is in this code is that we have created out a population pop population array okay of 3000 because the array goes from let's say 1950 to 2050 so i will created a very large area of till 3000 okay just taking some buffer values as well now iterate over this logs array and wherever the first value whenever that person bonds out that is i of zero increment that value by one and whenever that person dies decrement that value level so we have this now like for every person those logs i have like any like uh set those values in this population edit okay now i want to maximize it so this is maximum and the year at which they find out the maximum so that i will store this in here that is set from 1950s total fifty i will just so what we'll try to do is we are trying to do a prefix sum we are going to try to form a cumulative sum you can say okay so pop of i the current i is the i minus one value because we are like whatever is the previous person we just take this and add it to the current value so what we're trying to do is here is that we are trying to find out what is the current person living in this particular area okay and just maximizing this value if you find out one more maximum value we'll just update the year and maximize the population and that is how we can just get it out and then uh like return right here so it is uh now becomes very simple it is now becoming o of n approach only instead of just doing on o of n square approach that's the over and the space complexity also so this is like the space throwing out a constant amount of vector for that so if you're just assuming it for like varying length of vector for different sizes so it's it will be o of n but i have created it a constant so it will be o of n as well but i can say it of one also because we have created a constant size vector so whatever you can say so it will be an o of n you can so that's the overall uh logic and the code part that i'm going to test based on recipe as well for this problem thank you for watching this video till the end i will see you in the next one i keep quoting and bye
Maximum Population Year
maximum-population-year
You are given a 2D integer array `logs` where each `logs[i] = [birthi, deathi]` indicates the birth and death years of the `ith` person. The **population** of some year `x` is the number of people alive during that year. The `ith` person is counted in year `x`'s population if `x` is in the **inclusive** range `[birthi, deathi - 1]`. Note that the person is **not** counted in the year that they die. Return _the **earliest** year with the **maximum population**_. **Example 1:** **Input:** logs = \[\[1993,1999\],\[2000,2010\]\] **Output:** 1993 **Explanation:** The maximum population is 1, and 1993 is the earliest year with this population. **Example 2:** **Input:** logs = \[\[1950,1961\],\[1960,1971\],\[1970,1981\]\] **Output:** 1960 **Explanation:** The maximum population is 2, and it had happened in years 1960 and 1970. The earlier year between them is 1960. **Constraints:** * `1 <= logs.length <= 100` * `1950 <= birthi < deathi <= 2050`
null
null
Easy
null
1,046
hey everybody this is larry this is day seven of the leeco daily april challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's problem last stone rate i have a 736 days street going you can't i need to figure out how to change my camera because that's where my face is where the streak kind of is appearing apparently but um yeah oh well anyway hope everyone's having a great wednesday and all that stuff uh yeah let's get started so okay so you're given an awareness stones where strong sub i is the weight of the ive stone okay on each turn choose the two every stone and smash them together okay so then now we okay and then the stone has the rate of either they both destroyed or the leftover okay and then put it back okay uh given that n is equal to 3 the same first thing wow only do it that's interesting the first thing i would do is just keep doing it um just simulation i mean the first thing i would think about is like what you know they tell you what you want to do right so what would it take it resimulated right so a very naive way of doing it is just looking for a for loop you know that every time so there's n elements right every time you run uh with one simulation you have either n minus one element left or n minus two element left so that means that if you do a simulation then this is gonna be n squared and given that n is equal to dirty this is gonna be pretty you know fast enough i don't know why n is so small but um uh is that right and that's if you do it very naively right of keeping track of uh two heaviest stone in a loop or something of course you can optimize it with using a heap or something like that because as you can see you're getting the two heaviest uh stone every time so yeah so let's kind of do that and given that even if we do the naive one it's gonna be n squared and if we do it with uh a heap or something like or a priority q um it's gonna be n log n as a result um given that n is equal to three that should be way fast enough yeah i wonder if there's some like funky math that you can do to do it in linear time um i would guess maybe not only because you would have to sort anyway maybe i think you have to sort anyway but i could be wrong about that one let me know if there's any like yeah funky obself type thing i mean maybe there's some like weird math parody things but i don't know i'm not gonna lie i don't know this one with respect to that so yeah so let's do it with heap and let's get started uh the um remember that uh the python q library is kind of a little bit weird to use i like a lot i wish that it passes um like a keyframe let me see if i can learn you know just let me look at heap q and python to see if i can um uh pass a q oh so there is a key type thing okay so actually okay that's uh wait let me make sure that i'm right um have he pushed no that doesn't help oh so there's the enlarges and smallest that takes a and merge but uh i think i've been looking at this not that long ago but i thought that there's a way to deal with a key function but it seems like now you have to write like um okay you have to write a an ordering class or a data class for that so yeah i mean and of course if you have infinite time uh or maybe not infinite time just a little bit more time uh that's what you would do but um yeah that's but yeah i'm just going to do it that way so yeah so now for excellence stones uh and of course you can actually use heap of five for this but that's fine i like do it this way so then we put everything in a heap um but of course in python the heap is a min heap and we want a max heap to get the two heaviest stone right so let's um yeah let's actually uh have a helper here uh let's say x then now uh q that push a sheep of negative x and the logic we have here is that you know to get them to convert a maxi or sorry a min heap to a max heap you just take the negative of the number um because you know the smallest is the max and so forth uh once you add once you multiply by negative one but it's a little bit awkward but if you haven't seen it before maybe you have seen it before um or you know you just get used to it um that said uh still not great though if you ask me but it is what it is for now um because it is definitely not as clean as defining and ordering uh onto something okay so now while length of heat is greater than one yeah because there should be at most one song left i mean they tell you that but you can also prove that yourself so then now we just take two stones right strong is equal to uh pop of pop let's say and we can define that as well as a helper uh remember that this is the negative of that so that's why and now uh we just want to push uh absolute of x minus y um this is the same i was gonna say this is the same as this which is true but not if this not if um not in both this case thing so okay or if x is not you're gonna y we pop it um okay and then now at the way n we just have to make sure if we have no items left we return zero otherwise we return the last item left maybe we turn the pop version of that so we can kind of keep it clean a little bit let's give it a spin okay so that looks good i think we can probably just like put in random numbers or something but okay i mean this code is simple enough that it should be good so let's give it a submit hopefully this is good apparently i've done it twice before i mean this is just straight up simulation so i can really um i mean other than missing some like edge cases like n is equal to zero or something like that i'm not to say that this is wrong on that case but it could be um this should be yeah so again this loop will happen over n times iterations and each of these iterations will take over log n cos so this actually gets smaller as it gets whatever um so yeah so this is gonna be n log n time and linear space for the heap uh that's pretty much all i have for this one yeah let me know what you think stay good stay healthy to good mental health hope you all have a great rest of the week it's coming up to be a little bit rainy here in new york hopefully it's it stays okay and oh it's on your haircut now that i see a little bit but uh anyway i'll see you later take care bye
Last Stone Weight
max-consecutive-ones-iii
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone. We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is: * If `x == y`, both stones are destroyed, and * If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`. At the end of the game, there is **at most one** stone left. Return _the weight of the last remaining stone_. If there are no stones left, return `0`. **Example 1:** **Input:** stones = \[2,7,4,1,8,1\] **Output:** 1 **Explanation:** We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then, we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then, we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then, we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone. **Example 2:** **Input:** stones = \[1\] **Output:** 1 **Constraints:** * `1 <= stones.length <= 30` * `1 <= stones[i] <= 1000`
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
Array,Binary Search,Sliding Window,Prefix Sum
Medium
340,424,485,487,2134
1,828
Hello guys welcome to the video me series sub heading thode bhi hamid se problem nach kudiye phone number of points inside sarkar se yagya na points ko subscribe channel ko subscribe and subscribe the Channel and subscribe the two and subscribe ka sauda first Sarkar is the green circle so let's meet on a green color you will run this particular sarpanch this marking name and others sarkar have tripped points inside and points the return subscribe if you liked The Video then subscribe to The Amazing spider-man subscribe Quickly 1.5 Inch Point Vijay Singh Size Quickly 1.5 Inch Point Vijay Singh Size Quickly 1.5 Inch Point Vijay Singh Size Reducer Difficult For A Visit To Come Into Its Inside You Circle Swift Returns The Amazing One More Point On The Bounty Middling 134 This Point To Point And Subscribe Returns subscribe to subscribe our YouTube Channel and tap On The Amazing First service center for example the distance between the center and all the distance between the given to Delhi distance for calculate distance to the distance queen points and the center of the circle ok and distances loosening guddu radius of the Shravan basically vinod that point slice Here inside and them Buddha circle and you can return you can entertain oo can finally add blur this period solar power this 2012 Farukh the point to that is this point to point on the okay sir you will you viplayer unlocker look for in jQuery to Dhiru Ajun appoints dots plus point to make a simple subscribe and subscribe the distance between the center and points subscribe and subscribe the center of the subscribe quid just bracelet minute sudhi d'souza point opposite the center of the richest of a person subscribe to subscribe and subscribe the Video then subscribe to the Page Ki Lakshmi And Check If I Have Uddhav Practice Properties I Will Just Give Back Its Gas Pricing Spinal subscribe to the Page if you liked The Video then subscribe to the Page 210 Will Visit And Dom A Foreign Soil To Give Back It's Condition Score Day Yogendra Singh Criminal Congress Will Have Two Quora Account Variables And Counted 120 And Finally Bigg Boss Drown Pushp Will Be An Observer River Near Sector Saeed And Pushp A Lesson Types of your written and disseminate vector in BBA BCom final year in 3D is like cleavage pregnancy is fit and fine so its final but when you sleep on the table sanctification time
Queries on Number of Points Inside a Circle
count-ways-to-distribute-candies
You are given an array `points` where `points[i] = [xi, yi]` is the coordinates of the `ith` point on a 2D plane. Multiple points can have the **same** coordinates. You are also given an array `queries` where `queries[j] = [xj, yj, rj]` describes a circle centered at `(xj, yj)` with a radius of `rj`. For each query `queries[j]`, compute the number of points **inside** the `jth` circle. Points **on the border** of the circle are considered **inside**. Return _an array_ `answer`_, where_ `answer[j]` _is the answer to the_ `jth` _query_. **Example 1:** **Input:** points = \[\[1,3\],\[3,3\],\[5,3\],\[2,2\]\], queries = \[\[2,3,1\],\[4,3,1\],\[1,1,2\]\] **Output:** \[3,2,2\] **Explanation:** The points and circles are shown above. queries\[0\] is the green circle, queries\[1\] is the red circle, and queries\[2\] is the blue circle. **Example 2:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\],\[4,4\],\[5,5\]\], queries = \[\[1,2,2\],\[2,2,2\],\[4,3,2\],\[4,3,3\]\] **Output:** \[2,3,2,4\] **Explanation:** The points and circles are shown above. queries\[0\] is green, queries\[1\] is red, queries\[2\] is blue, and queries\[3\] is purple. **Constraints:** * `1 <= points.length <= 500` * `points[i].length == 2` * `0 <= x​​​​​​i, y​​​​​​i <= 500` * `1 <= queries.length <= 500` * `queries[j].length == 3` * `0 <= xj, yj <= 500` * `1 <= rj <= 500` * All coordinates are integers. **Follow up:** Could you find the answer for each query in better complexity than `O(n)`?
Try to define a recursive approach. For the ith candies, there will be one of the two following cases: If the i - 1 previous candies are already distributed into k bags for the ith candy, you can have k * dp[n - 1][k] ways to distribute the ith candy. We need then to solve the state of (n - 1, k). If the i - 1 previous candies are already distributed into k - 1 bags for the ith candy, you can have dp[n - 1][k - 1] ways to distribute the ith candy. We need then to solve the state of (n - 1, k - 1). This approach will be too slow and will traverse some states more than once. We should use memoization to make the algorithm efficient.
Dynamic Programming
Hard
null
1,560
we have a circular track which consists of n sectors labeled from 1 to n a marathon will be held on this track and the marathon consists of M rounds so I the round starts from Stars sector rounds of I minus 1 till the sector rounds of I so for example if the round one starts at sector rounds of zero then it ends at the sector 1. sorted in the ascending order notice that you circulate the track in ascending order of the sector numbers in the counter clockwise Direction so the question is let's take this example explain example problem with this example here we start at the sector one okay we are acceptable to move to sector three how do we if it in circular track we have to pass sector 2 then sector 3 so from three four you go and then you reach one from again then one to two how do you directly from one you go to two because already at one directly you go to two so this will be count will be written for one how many times have you visited two times two is also raised to two times three is three and four are these three ones so you could see here three four straight ones and one and two are missed it twice so the highest number of times uh which stack has been listed there is one and two which has been visited twice we have to return that in the ascending card this is the question we have given in so let's Implement logic with a given example here we have n equal to how much it's four okay so what we'll do is as I said uh like the round you sector how much you travel it's nothing but you started this index at that ended this index I limited this you start that first term you end it third track how do you move one two three then if you want to start your third row and move to first track uh not track first sector then how do you move from three you would Travis to four then one similar for one to two directly from one to two you go here one two three so what we'll do is we'll keep pointers okay we'll keep pointers let this P start and end now initially right so initially you want to move from the sector 1 to sector three and okay we need to store the answer so we'll have a resultant Vector the stored answer and also one more thing which we need to have is um we'll have an array of size n okay y n as this is the n tracks that's why we'll have a array of size n or you can have RF says n plus one also because if I take array of size n then 0 1 2 3 4 indexes indices will be giving getting and if we use an RF says n plus 1 then 0 1 2 3 4 so 1 2 3 4 you can use zero you can just leave as such one two three so this is in the index and elements corresponding to this index are nothing but one two three four these are the number of sectors that provide sector two sectors 3 sector 4 and let's have how many times we had visited this um every sector so we should initialize everything to zero initially okay so this is array index these are the elements corresponding to each index you could see element minus one represents the index and number of times we still each sector is initialized to zero in the array this is done so once you are done with this now you have your battery low will uh last element minus one because start in start and start end the last one we will see that how do we handle it later okay start in this is start this is n then again this is star this is n so this is what I said now and if we start this is what is where there is no end so we shall look into that later now just imagine we are having started it okay um second one so increment the value at the sector one that is index 0 to 1. okay that's fine increment the value to one because we have visited once now so once you are at uh start equal to 1. you will state that next which is the one we have to S plus what is that s equal to 2. so s equal to is it equal to n no this is not the ending sector so you have to Traverse this also even this value will get incremented to one it's a sector 2 which is index as sector 2 minus one that is okay then again increment s plus how much you get this will get incremented to three you are a sector 3 so start is equal to n now because ND is important to three status was according to three at this point stop this while loop okay now you have instead to move from one to three you have to visit you have to basic one two then three you might ask why it into increment that will increment in the next row when we go from three to one okay for now start so once you find start is equal to N Stop the Loop now which should be the start next start will point to okay so next start will be this and next end will be this so again same thing until start not equal to n is it equal to a start is equal to n no so now initialize s equal to 3 you have okay in this pointing to First Position from 3 Etc is next you have to Traverse 4. so okay first you have to basic three so increment evaluate the position three now we have a state three next Once you have step 3 increment the value to 4 now 4 is equal to n no again we Miss next again if you increment it to five is there any sector number five we have only four sectors there is no fifth sector then how do you prevent the value now because you have to move to one so for this reason what you do is whatever start you have you do modulus n plus one okay so you have four modulus four plus one if you do how much you get it one foreign it will give you so now here instead of 5 you have to get one as the answer so this is why we do this operation start model is the given number of set plus one so that will not go out of range of the number of circles so now what s equal to 1 again so S is initialized to one so now is start is equal to n status one end is also one yes okay now run the next Loop okay so with this foreign so stop this now as I said next actually it should be now you have not visited the sector two you didn't think now it should be actually start and end should be some other sector here but we do not have so last one part of which you have left just increment that value after all the loops are done till here start and end you have increment the last value whatever sector you have here recommend that value to also visit so is it correct actually what we have got here let's check that so we have one three one two so we are at one if you want to move to three or two Traverse to two then three from three you have to again move to one so you go four then after that one you reached one so one you have to go to two so how many times one is basically twice how many can two is visited twice how many times three and four are basically once yes three four visited ones one and twelve is that twice so it's we have absolutely nothing we are doing Simple so we have a start and pointer from here to here how many in between sectors you get just keep on visiting those values till this and why do we do this modulus operation if it gets out of range that's why once you are at three you have to go to one means three four one it shouldn't be three four five now this should not have to avoid this we are using this modulus operation yeah so this is the logic we shall implement the logic now so as I said what we should have let's create a array first okay so let's create an array of size n foreign and visualize two sides of the given area so we'll iterate elements less than M minus 1 why M minus 1 because last element will not be traversing because in that case will not be having the end point that we have the start pointing but there is no important in the last element so not be taking that so we will give the condition less than M minus one so let's start be equal to rounds of I can be pointing to rounds of I Plus 1. start this one and this trip like that so while start not equal to n so first what we need to do uh okay so we need to increment the sector account value now so sector count of start equals to plus equals to 1. but this should be actually start minus 1 why 0 plus equals to 1 I'll give this plus why start minus 1 is given here because as I said the element corresponding to index 0 is 1 index 1 is 2 next 2 is 3 index 3 is 4 so the element is 1 then that is at the index 0 that's why you have to start this one it should be at index then it should be start only so next uh we have to increment start so start equals to start plus 1 but how do we calculate start modulus n because it should not go out of range of the sectors plus one so once you are done with this um at the end after the loop we have to let the 2 will be remaining for this there is no end part no so for this whatever without increment the value of this sector how do you increment again uh sector on the wherever we start M minus 1 the last element start of M minus 1. so set the count of rounds of n minus 1 so rounds last element so rounds of M minus 1 plus again same as we'll do start here is its rounds of M minus 1 will 2 because as R is zero indexed so yeah this will give us the array now we have to take the array with a maximum element from the array so how do you get the maximum element so let's say end Max count equal to as we have the input function we'll use stats Max element of the array which are in not begin comma sector count Dot N so this will get the maximum element the maximum frequency is more specific visited sector now run again iterate over the sector um all right so for I equal to 0 I less than sector concise we got around size only so let that be m I plus will have a resultant array so vector result will use so if sector count of I is equal to Max count then that is the most positive visited signal we have to add that to the resultant so Vector so result Dot pushback off 8. plus one again y plus 1 is the zero index plus 1 will get the first characteristic index 0 so 0 plus 1 so that will be the first sector yes at last uh you written the resultant okay here this should be discourse one more error runtime a small mistake we had did it should be sector arrival sector counter of size and not M so that is the mistake which we did I hope it works now yes and for Java we'll see the same logic applies nothing change um how do you find the maximum with your title she'll submit this also yeah successfully submitted if you understood the concept please do like the video and subscribe to the channel we'll come up with another video in the next session keep learning thank you
Most Visited Sector in a Circular Track
number-of-students-doing-homework-at-a-given-time
Given an integer `n` and an integer array `rounds`. We have a circular track which consists of `n` sectors labeled from `1` to `n`. A marathon will be held on this track, the marathon consists of `m` rounds. The `ith` round starts at sector `rounds[i - 1]` and ends at sector `rounds[i]`. For example, round 1 starts at sector `rounds[0]` and ends at sector `rounds[1]` Return _an array of the most visited sectors_ sorted in **ascending** order. Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example). **Example 1:** **Input:** n = 4, rounds = \[1,3,1,2\] **Output:** \[1,2\] **Explanation:** The marathon starts at sector 1. The order of the visited sectors is as follows: 1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon) We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once. **Example 2:** **Input:** n = 2, rounds = \[2,1,2,1,2,1,2,1,2\] **Output:** \[2\] **Example 3:** **Input:** n = 7, rounds = \[1,3,5,7\] **Output:** \[1,2,3,4,5,6,7\] **Constraints:** * `2 <= n <= 100` * `1 <= m <= 100` * `rounds.length == m + 1` * `1 <= rounds[i] <= n` * `rounds[i] != rounds[i + 1]` for `0 <= i < m`
Imagine that startTime[i] and endTime[i] form an interval (i.e. [startTime[i], endTime[i]]). The answer is how many times the queryTime laid in those mentioned intervals.
Array
Easy
null