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 |
---|---|---|---|---|---|---|---|---|
815 |
hey what's up guys chung here again so tonight let's take a look at this uh lead code problem here which is number 815 bus routes okay heart i like this problem so if we have a list of both roots and each roots uh roots i the bus route that's basically the route is a kind of list for example if the route 0 is a 1 5 7 it means that uh you can travel right you can basically you can travel to any of the stops right you can go to one from one to five from five to seven and from seven to one basically it means that at any of the stops here right you can go to any other stops right within this uh roots here okay and basically so the first input is the it's a list of the roots basically it's a list of list and then it you have a start and stop okay basically you start from this uh stop one and you have a target basically and you have a target t here you want us you want to go to the target stop six and it asks you to find the least number of buses right we must take to reach our destination okay and return -1 if it's not possible okay and return -1 if it's not possible okay and return -1 if it's not possible okay so for example right so for this one uh we start from one okay and then from one to basically we from one to two we go to seven right and from seven we can go to uh the other bus right we can take on get on the other bus and from the seven to go to six and so the answer is two right i mean this one i think it's not hard to think to i mean to realize that this is like a bfs search problem right basically from at each of the uh the stop you can go to you can have like different options right and you just need to find the basically that the minimum uh hop right the minimum hop to get from the start to the target stop okay and that part is not that hard but the difficulty for this problem is how can we build the graph right the word we'll do the bfs search so that from seven we can go to six okay right because so i mean i think a nice way is that i mean basically for each of the stock right for each of the stop we want to see uh the brutal force weight will be basically we're creating a graph right the graph and the key will be it will be the stop and the value will be uh will be from the current stop from the value will be a list or a set of all the stops from the current uh from the current stop to get to without taking to another bus so which means in this case right from one we can go to what two and seven okay from two we can go to one seven okay and then from seven okay from seven sorry some from seven we can go to uh what we can go to one and two and also three and six okay so same thing for the difference three here can go to uh six and seven okay from six go to three and seven yeah seven is done okay right so i mean the brutal fourth way will be uh basically we just loop through all the routes here right and for each of the routes for each of the stop we're trying to like uh build a list build at least on the on this stop which means the list of stops means that from this stop we can go right without taking any of the without moving to any of the bus okay so every time now we have a graph here every time we have a stop here we simply loop through we just need to do a bfs search based on this graph okay i mean it will work but unfortunately it was tle because of this as you guys can see the length of the maximum length of the roots is 10 to the power of 5. and to be able to build this uh to build this like graph the time complexity we need will be n square right as you guys can see basically we are for each of the roots here and we're looking through all the stops here and for all the stop we're adding everything else right all the other stops for this stop for the current stop that's going to be the n square time complexity which will be uh tle okay so then this so okay so since this one doesn't work um how can we do it right i mean then we notice that right the root itself only has like 500 okay it don't have only has 500 so it means that instead of building like uh like a stop to stop right this is like stop to stop relationships we can build like stop uh stop to what to the roots right so basically i mean for each of the to stop here right let's say for example to stop one and stop one belongs to what belongs to root zero i'm assuming i'm giving each root like i'm using the index as the root id here so basically one belongs to root 0 and 2 belongs to root 0 right 3 sorry 7 okay belongs to root 0 okay now 3 belongs to root 1 and uh like six belongs to root one and seven now it's seven again belongs to root zero and root one okay cool so this thing's here right so now we have a stop to root then we just uh we just do the breadth first search from one here okay and the way we're using this graph is every time when we have like one here right when we have a stop here we just look for okay how many roots this one belongs to okay and from for those roots here we just look through all the stops within those roots and we add those stops into the queue that's how we do the bfs search okay of course we're gonna be using like some visited or scene set to record uh the stops we have visited and also the routes we have been used before yeah i think that's pretty much it is basically we just move from this on square to this like to be basically to build this kind of the second graph here the time complexity will be like this one n times what 500 right cool so let's try to code this up here okay so first like i said we need to create a graph here okay the graph will be a default dictionary set okay so for roots for i and roots enumerate roots here okay first stop in roots right and the graph is this stop belongs to this root basically like i said i'm using the index to represent the id of the roots okay so now basically we're building like a graph here the key is the stop and the value is a list of the roots this stop belongs to okay and then we have uh answer equal to zero and then we have a queue here right then we have a queue uh collections right dot dq collections um the starting point is s okay yeah s and then uh so scene stop okay basically i'm going to create two sets here and the second one the scene are roots okay it's also a set and scene stop dot at uh s right because that's a starting point now let's do a bfs here okay uh for in range length after q stop okay goes to uh pop left okay if stop equals to t right and then we simply return the answer right that's the uh the stop the base case right when we have like a stop we will see the t here we know okay we have find the minimum bus we need because we have already uh add everything right to this stop here for the for basically for all the routes all the rules this stop can go okay so now uh we have the stop and the graph we have is the from the stop to the roots okay which means uh from the stop we can know what are the routes this stop from this stop that can it can go right uh so it means that from the roots okay in the graph stop okay and we check okay you know actually let's not use this scene root first let's only use the scene stop to make it easy right and then we can uh try it using this like scene roots to optimize our solution time complexity here so from the root here right so from the root uh we can get everything we can get all the stops within this route okay basically it means that's all the uh that's all the stops from the current stop it we i mean we can go freely right without uh without changing to any of the bus okay so for a new stop okay if a new stop in roots in well actually this is the root id here sorry it's not the root itself the root id and to get the uh the roots itself we have to do a roots dot a root id right that's the that's a stop we can go and now let's do a simple check if the stop not in scene stop okay then we just add uh append this new stop to the queue and we also need to add uh add these things to the scene okay yeah and that's that and yeah and i think that's that answer plus one okay here we simply return minus one you know this should just work right basically from the current stop since we have built the web build the builds the relations from the stop to all its roots now basically what we're doing here is we're adding all the possible other possible stops from this stop we can go without changing to end without uh changing to without taking to another bus okay right because if the stop is like the seven right so from seven we basically we can either go to one two or we can go to three six okay yeah and let's try to run the code okay this one works submit yeah as you can you guys can see it's accepted right so even though it's only faster than that less than 10 percent okay but it still works basically that's the idea here right so we're using like this uh stop to roots graph here and for each of the stop we tried we're trying to get all the possible stops from this stop can and get to and then we add that to the graph okay and then we just do a bfs search so what kind of improvements we can make here right so the improvement we can make is the uh we can also record uh which route we have been we have processed before why is that because you know every time when we have a route here basically we're adding all other stops within that route to the to our queue okay so it means that i mean next time when we see a new roots uh another route that which we have already uh seen before we can simply skip that because we know we have already uh add those stops right for uh to the qp to the qb4 so we can just simply do our earliest termination and so that's what i'm trying to say here basically if um if the root id not in scene root okay then we do this and in the end here we just do a what scene root dot at root id okay yeah cool see it's much faster it's only uh we're basically getting a huge improvement here just because you know because of this otherwise you know otherwise we have to be basically looping through all the elements right all the elements in this rules one more time even though for most of the even though for those new stops we will be a stop we'll be skipping from here if we process the rules we have already been seen before right but as you guys can see we will be looping through all the other stops in that old route again so but if we do a if check here we can simply save the nested for loops right cool yeah i think basically that's pretty much it is oh and the space and time can space complexity so uh let's see this is n here and this is m okay so for this one right for this one it's uh and the roots is uh we have m roots and then for each one we have a and stop right so we have m times n here and how about the bfs right so the bfs we will be looping through basically we're looping through all the uh odd elements okay yeah basically we're basically since we're using like those scenes those like two scenes set here we're basically looping through all the notes right for the uh for the entire yeah and here i'm always thinking it's also like m times n right basically that's the total notes or total stops right we'll be having that's the worst case scenario the total stops among m roots and each roots have like n stops okay yeah so the space time complexity will be o of m times n and the space complexity is also like uh since this one is stopped right basically we have this many stops and the total stop is also like o of m times n yeah i think that should be correct cool guys i think yeah i think that's pretty much it is you know this one i think it's a good problem you know actually it's uh you know at the first glance you guys may be thinking okay it's pretty easy just a bfs search right yes you're right the bfs search but the hard part is the uh how can you convert the bfs how can you construct the bfs search tree right basically how can you add how can you construct a graph so that every time when you have a stop you can add all the possible stops the possible new stops right this uh this stop i mean you can go from this current stop okay yeah cool i think that's pretty much it is okay thank you so much uh for watching the videos guys and stay tuned see you guys soon bye
|
Bus Routes
|
champagne-tower
|
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever.
* For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever.
You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only.
Return _the least number of buses you must take to travel from_ `source` _to_ `target`. Return `-1` if it is not possible.
**Example 1:**
**Input:** routes = \[\[1,2,7\],\[3,6,7\]\], source = 1, target = 6
**Output:** 2
**Explanation:** The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
**Example 2:**
**Input:** routes = \[\[7,12\],\[4,5,15\],\[6\],\[15,19\],\[9,12,13\]\], source = 15, target = 12
**Output:** -1
**Constraints:**
* `1 <= routes.length <= 500`.
* `1 <= routes[i].length <= 105`
* All the values of `routes[i]` are **unique**.
* `sum(routes[i].length) <= 105`
* `0 <= routes[i][j] < 106`
* `0 <= source, target < 106`
| null |
Dynamic Programming
|
Medium
|
1385
|
144 |
Where there is in order travels sale, this is question number 94 and one is question number 145 which is post order, so we will see these three questions here, how will these three questions be here, okay, so you see an easy level here. The question is difficult, the upward is very high, okay, the question is quite good, this is the first question of our pay tree here, before this we have taken the link, we have done the questions here, given here is the type of data structure, the rest of the data we have is There is a structure in it, we have ars, ok, we have aris, we have here, please, what is the difference, which one you have. What kind of data is there and what kind of data structure do you want to have in order to score it? If the data you have is sequence, okay Meli, we have two types of data, one is you have frequent one here. You have here, okay, your frequent data is stored in these data structures, which is your stock, it is a linked list. If you have sequential data, then you will use these data structures for that, but if The data you have is the article of last night. How is the data? If you are in a corporate, if you are in a college, then in a college, if you see, there is a teacher, there is a competition over the teacher, the principal is your boss, then the manager of that factor. Whatever day you have, it is divided into a whole, like this, if you go to a corporate, then at the top of the corporate, you have a CEO here, then you have an ATO here, cough, that happens, okay, then if you are here. You will come here, the Vice Presidents are there, right inside them, then you have your managers here, right here you have all the managers, inside you are the team leads. And inside the team lead, you have developers here, so you see here, Puri is a heer's bundle, so if you have a data which is yesterday, then you will store it inside the tri, so that is why we are here please. Here we do the data structure, now there are some terms here, if you take a cream, then we have a tree here, this thing is called a root and if you look here, this root has two children. This is the left node here, this is the right node here and these two are its children here, so this becomes its parent and these two will be its children here if you this one from this entire cream. you if you this one from this entire cream. Take one sub for free, okay so in this is the root here and this here is its children, meaning these are the children here and this is the parent of this here, what is the relation between these two? This here is its grand parent. Well, if you do n't have that much family relation, then keep in mind that this here is the root and this here is only the children. For all the tricks of this one, this is the root here. This is its root here. Children, okay, this is a simple one here, okay, here they said brother's binary tree, what is this thing here, if you look here, we have a lot of notes in one cream, okay, this is what we have here. In which all the parent's atoms can have two children. There can be only two notes. If there is a tree in which it has only two children, the number of atmos can be less than two, but mostly the atoms should be two. Then there should be only two notes. We will call it a binary tree, like here it is a putative parent, okay, this is the parent here, how many children does it have, here it has three children, which is more than yours, is this a binary tree at all, because here But it has three children, the second one and this one are the third, like if it is a parent, then it will have only two children, it can be one, so how is it all, so here they have given binary. Here the simple meaning of binary is that Atoms can have only two children, there will be no extra than two and what they are saying here is that you have to do traversal here, that you have to go through each one of the tree here. You have to visit the note here, now you are told that you have to travel for something, meaning you have to visit each note, after visiting, you have to read the data, update it, do anything but you have to travel. So it means that you have to visit each mode here, so what they are saying is that you have to travel the binary tree here, by which method, by the fairy order method, now when you travel the binary tree here, you Suppose you have binani here, okay after a very big one, primary is free here and you have to read its data here, okay, to read its data you will have to make a note one by one, so we have two. Whenever you travel, there are two types of travels, first is breakfast or you have breakfast here, second is depth first, okay, these are two types of travels, we have breakfast here. It means that you are breathing, it means you are doing it horizontally, you are doing it in reverse, first you did this normal travel, then you did tables for these three, then you did driver for these three, then tables for these five, this is the breath first, in this we use towel. Let's do that's our level order, it's called depth first, you have three types of travels, you have one in the pay order here, if you make it horizontal, you have it here. What you are doing is that here, let's do it, you are traversing the level note here, after that, you will come here and these notes here, meaning you are traversing the vertical notes here, not towards the horizon. If so, then it is depth first, okay, there are three types of first order, there is angel order, there is inverter, we have been asked to pay pre order here, in the remaining two questions, there is inorder and post order also, here they have asked here. I am taking all three questions together. Free order in order post order. What happens if you take a binary here, okay by C, if from this I take out a subcluster here that I take a sub tree here. If I am removing it, then if I write it here, then you have this here, even in the software, we have many ways as to how you can visit a note, so these are the three ways how you can visit the note. Yes, okay, you want to take the left first and travel the route. Now what's in it is that first you want to travel the left, first you want to drive the route, first you want to travel the right. Simple, this is the method here. If you have to travel left first then do the route then do the right then that is a different method. If you have to first travel the route then do the left then do the right then that is a different method like if I suppose. Look at the order, see the P order. If you are here, look at the Pari order. In the Pari order, there is Singh kasi many times. In the Pari order, the root comes first, then we come to the root, after that how is your right answer. In this order, we are the first on the left. We travel to the left, then we travel to the right, then we traverse the route, so this thing is first in our Also, on the basis of which note you are visiting first, we will categorize it and how to remember it. Pari means first, then root first, understand the meaning of these, if root is in between, then post means later. If it happens, then the root is yours later and first you have to do the left towards, after that you have to double the right, like first here is the root, then here is the left, at the end there is the right, so there is the root in the middle but later on the right. And here is the post, then first is on the left, right and last is yours here This is here, how do I write the code, after that how is the code doing, I will show you here by running it in a perfect way. How are you doing? So I hope you have understood this much. This was a theory for those who are watching the piece for the first time. If anyone has read it before then they would already know it. You have been given a function here which is returning a list of waiting and you have been given the root element of the tree note, meaning you have been given the first element which is the topmost which is its root. First of all, I have to return a list here. You have to return a list of integers here, so I have to create this. What am I doing here, I am creating a list of integers and output and bank it with an errorless Let me make it okay, there should be written type and there should be a list here and the type should be integer. Now in this priority order travels, what I told you is that first comes your route, then your laptop, then your right answer. Okay, first of all I will tell you the route. Kota bus tax While doing this, if I want to print it, then to print it, I am directly adding it to the output here. In my simple, what I have added to the output and if you look at the note here in the right corner, then there should be maximum only two notes in the note. If you can, then it is given to you straight here, one is given to you here and one to you is right here, okay, there can be maximum only two notes, either left or right, then both are given to you and the value is yours. That value is needed inside the bell After the root, it is on your left here, now here it is the left element and here it has to travel to the right, I have written simple here, root and right has to be returned which is on your here √ 2 elements, this is which is on your here √ 2 elements, this is which is on your here √ 2 elements, this is so little code, once I run it here, then I explain it, then I made the diagram and how it is doing it here. Okay, so now let's see how the code is doing it here, which Here I am given 123 and you are given 123 here. The meaning of null here is simple that there is no child of one, okay, the left child of one is null here, on the right side here you are. Which is what you have to return from here, which is here one two three, this is a small example, it is okay, let's take one example and a slightly bigger example has been taken. Friends, you make this suggested 12 notes and I have given them to you. Let's also do it Is the Is the Is the root your tap? If it is not there at all, then it will come down here and will add it to the output. Root dot Well, so the value of root in my output is one, it will be added to me here, okay. What happened after that? What will be the priority? I sent the left element of the root here again and this function was given to you here again yesterday, so now I am writing a simple free order here because order one I The prior one written here is not yet completed because this function has not yet returned from here and this function here is reversible again tomorrow or what is root dot left, root and left me here you are lying, so which Aap ka pari order wala function hai with vo yeh dobara kal hoga kya root aap ka name exactly in output.ed root and aap ka name exactly in output.ed root and aap ka name exactly in output.ed root and value here tu ko yahan par dal dega to root ka left here pe four hain pari order travels ke It will happen again tomorrow, okay, you have not returned yet and here the four has already happened, okay and here it will happen tomorrow, will the route here be null, it is not there at all, in the output dot, you here, then add four and dog. Now in fairy order, from the left of the root, you did it again yesterday by going up to the left because here on how in nails, here, if this function will happen again tomorrow, then here on √ on √ on √ how in that function, it will turn from here because your root element. There is null here, there is nothing on the left of four, this is your return from here, so this line has been executed, so it will come on the next line, there is something on the right of priority table root dot and right, there is nothing. Okay, so here the root is null again, this line of yours has also been executed and from here, your function here will return off, will return and will come back here he turned left, after this We went to the right, now this will come on the next line, fairy order came to the right and from fairy order here, your five pen is fine, file is here, yours happened yesterday, so this function happened again yesterday, root is not null here, output and here. Pay Four and Five A will go here, after coming Pay Five from Poddar, whatever is left of Route Dot Left 5, will do it tomorrow, then with angel order, your 8 will be here tomorrow, as soon as tomorrow comes, your Pay √ is not there, output dot well. It will be your Pay √ is not there, output dot well. It will be your Pay √ is not there, output dot well. It will be added here from the prior table, root dot left, there is nothing, root is equal to you, it will be added here, so this will be added to this how, this function has already been done, is there anything on the right, something on the right. If not, then this function will be returned from this line, we will come back here and both these functions are yours, okay, it will return the output, the function on the left of five was running near Prevent, you will come on the right one of five, dot. There is something on the right or right, there is nothing on the right here because the root is your null here, this is where the function with five will return, if your return is from here, then it will return from here, near 2, okay pop. Pari order was going on in the forest that we will go from here Pari order route dot left, we came here on left, now this function will be coded here, right, so now we will go here on T, okay so Pari Now in the order here, your three will be there tomorrow. Three here is your tomorrow. So first of all, the root here is not null because here is three. In the output, we will add three here. We have added three to this here. After adding priority table root dot left here pe kal hua which is here pe six so in fairy order we have here pe fix yesterday hua six here root is not null because here the output from pe six is dot well. is not null because here the output from pe six is dot well. is not null because here the output from pe six is dot well. Here we will add six. After adding six, there is something to the left of √6, there is nothing, there is something to the left of √6, there is nothing, there is something to the left of √6, there is nothing to the right of six, this will be returned from here and the fairy has come here now from here. With this function, the root's right will be tomorrow, which is the right of three here, which is seven here, so in the starting order, now your seven will be here, after coming 7a, the root here is 7, you dot well, so here we are. We will add 7 by adding 7, after that the fairy order will go to the left of √7 from the driver, after that the fairy order will go to the left of √7 from the driver, after that the fairy order will go to the left of √7 from the driver, which is here your fairy order is 9, there is no null here on the board, it is okay, there is nine here in the output and wire. Someone will print the priority, left is your tap, right is also your tap here, nine will be returned from here, will go back to seven and left of seven is here, we did it yesterday, right of 7 will follow here which is the order. Your N is fine, by the way, the left of the root is null here, the root is also null here, the left right of 10 will be here, both will be done here, Papa will go to the intake, both left and right have been run in the intake, it will return the output to the intake from here to Britain. It will be okay. A will go back to three because here your method in three pack is also your left and right both have been played. So from the return output your pay here will be 300. This will go back to one because one is still with you. Paan is in stock. Earlier your left had gone. We had already done this left for the tables. Now what did you do here? You also traveled to the right and returned. You paid one here. This one became Britain from here and that one here. At the time of one, the one who will be here in Britain, that is you, this is the final outdoor, so this is the one created at your place, okay, this is the one in order, this is the fairy order of this, what was in the table cell, first was your route, then was your left, then was your right. It does something like this, it is not even below, it is okay, let's take 123 from this, which they have given here, from this, I will explain it once, this is your pay here one, this is your pay here. Root one is yours here, it will be added inside it from this line, so one yours here is added to the left of the root, if you do n't take the root here, then go to the left here, then this is here from this same line of fabric, then to the right of the root. You will come √hi So, here on the right side of the root, your √hi So, here on the right side of the root, your √hi So, here on the right side of the root, your 2 is here, your here, this function will come to the root dot well, you have added tu here, after adding tu, you are here √k, on the left, in total, here. Pay three √k, on the left, in total, here. Pay three √k, on the left, in total, here. Pay three is three, it will come here because the research is yesterday, there is no root here, there is no tap, it will be yours in 12, since it was added on 3, root and left, root dot left and right both have been run, it will return yes, 123. You see, it is going absolutely fine, so we can do it this way and in this way we can do the rest of the questions. If I copy some parts from here for a second, because it is from here, I have to show it to you first of all. So after submitting this, I will show it to you because I had a meeting with you, I had just run it, so you see here, I got zero seconds and bits, 100%, so everyone has been beaten here, let's come bits, 100%, so everyone has been beaten here, let's come bits, 100%, so everyone has been beaten here, let's come back, okay and here I come. Now the order here is that in innovative, your root should be in the middle. Okay, what was here is that we have already printed the ghost here, but here you do not print the root first left. You have to travel, then the route will come, this thing will come, you have to adopt the fund from here, this is the output of yours, you are printing your route, it is very little, okay, you just have to put the route in the middle, if you look here, This will work for you, the explanation here is complete, okay, the diagram I had made, you can try it once by making the diagram, now look here, this also has zero percent here, it is 100% percent here, it is 100% percent here, it is 100% okay, make the diagram once and try it to see how. -How is it going, as I see how. -How is it going, as I see how. -How is it going, as I showed you further, similarly we have a post order here, what has to be done in the post order, whatever is your route, it will go here at the end, okay, here we have written the route in the middle. In the post order of inverter, but in the post order, how is your route and will go in because in the post of ortho, first your left is left, then yours is left, after that your food is traversing, we have to make the route go straight and you Look here, it is going absolutely perfect, so in this way you are here in this question description.
|
Binary Tree Preorder Traversal
|
binary-tree-preorder-traversal
|
Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[1,2,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
94,255,775
|
1,047 |
how's it going guys so today i'm going to solve the question which is remove all adjacent duplicates in string so this question is quite simple like if you understand this question like you understand how the stack is working so we use the help of stack for this question all right so let's just read the first question what is saying so it's saying like we have given a string as considering of all lowercase english letter a duplicate removal consists of choosing two adjacent and equal address okay and removing them all right so we have to remove two equal adjacent net like the two words coming together okay so we repeatedly make a duplicate removals on s until we no longer can okay so we will remove until like we cannot find uh any similar one in the final string after all such duplicates removal have been made it can be prove that it's a unique one all right so let's just look at over here what is saying so we just simply take this test case we have this test is a b a c a okay guys so what we have to do we have to remove the similar objects from over here okay so we are like we have to remove this b okay after removing the b the a will come together the a is similar because a space nothing is over here the a will remove and if you look at our c and a they both are different so this will be our answer so how we're going to do it we just use the simply helpful stack to solve this question all right so let me just give you and like overview like how we're going to solve this so let's say we have stack we have this element abb aca okay what i will do i will create one my stack okay let me call it st okay now what i will do i will uh put the element in the stack which is like i will put the element which are not similar okay or if the stack is empty and it's coming first time only if that's the condition then i will put it so like my stack is empty one condition and the is it's like it's not similar to anyone so it will come so a will come in my stack okay now what i will happen i will go in the next one i will check is b similar to the previous one it will check no b is not similar to the previous one so we will go in the stack okay now this b will come it will say is b similar to the previous one yes it is similar to the previous one so what i will do i will simply remove this from the stack and these two will be removed all right guys okay so now what we have left like empty over here now a so what i will do i will check again like is a similar to the previous one in the stack yes it is similar to the a in the previous in this text what i will do i will simply remove these both as well from the stack okay so what now what will happen we will see our stack is empty now our stack is empty so what i will do i will just simply put c in the stack and like it's going it's taking my two both of the condition the stack is empty and it's not similar to the previous one okay now what i will do i will go for the another one is a similar to the previous no it's not similar to the previous one so now a my anc is coming on the stack so what i will do i will finally print my stack but my stack will come like in the form of ac so i will reverse it to get my ca in the form of string okay guys uh like as they are in the form of factory so i will convert first of all i will reverse it and i will convert it into the string so i hope this question is clearly like how we're going to approach this question so let me just erase everything from over here okay so let just solve this approach so what i will do first of all i will create my step first of all and this is my character so because we are dealing with character over here okay i will call it a st all right guys now what i will do i will run a for loop from end i to zero to the uh length of s the last okay i plus all right guys now i will run an if condition i will say if my stack is empty okay i will say like if my stack is not empty over here i will say if my stack is not empty all right guys and my the peak element on this stack what did i mean by doing this the element is on the top of the stack the uh last element we just put in our stack is at the peak i will check is it similar to that we are looking at now is this similar to the current element we are looking at if that's the condition if the stack is known empty is similar to the previous one okay then what i will do is similar to the element within the stack then i will simply pop it up okay and it means it is removed from the stack else if the stack is empty or my element is not similar to the previous one then what i will do i will simply push into my stack add it into my stack s2.bush as a dog stack s2.bush as a dog stack s2.bush as a dog yeah right i alright guys okay now if you look at over here what is i told you like if you if we just look at this test case we have c a so like what we have see uh no we have ac in our stack if we just remove that then you know like how it's removed it's removing le li f4 last in first out so the first element presented in the stack will be removed first so it will come like a after that what will happen the c will come that c will come from the stack so c will come over here okay now my stack is empty but it's in the reverse order okay so i like is in the raw motor is in the reversal so we have to reverse it first so for that what i will do i will use the help of string builder in this one all right so i will say string builder sb new string builder okay guys so i will run a loop to remove it and put it into my string builder so what i will do i will say while my stack is not empty so this proof will until the stack is not empty okay so otherwise my stack is not empty then what you have to do sb dot append add in my string builder and remove from the stack all right guys i hope this thing is clear and finally we have to return it so once i am returning my string builder i have to reverse it first okay and i have to convert into the string so like you know we are just receiving the character so i have to convert the character into the string so we'll use two string okay and we just finish our chord let me just give a quick run to this one i have the code is very simple i just whatever i explain similar to that one only so yeah it's accepting let me just submit it and here we go so like in this question we are dealing with the time complexity of off and because we are uh running for like or n characters okay and the space complexity is again o of n okay because we are using this space of stack all right guys i hope this question is clear to you guys if you still have any doubt then just do watch the video again if you have any doubts still you have any doubts then just do let me know in the comment section i will definitely use to you guys all right guys thank you very much guys for watching this video i will see you in the next one till then take care bye love you guys
|
Remove All Adjacent Duplicates In String
|
maximize-sum-of-array-after-k-negations
|
You are given a string `s` consisting of lowercase English letters. A **duplicate removal** consists of choosing two **adjacent** and **equal** letters and removing them.
We repeatedly make **duplicate removals** on `s` until we no longer can.
Return _the final string after all such duplicate removals have been made_. It can be proven that the answer is **unique**.
**Example 1:**
**Input:** s = "abbaca "
**Output:** "ca "
**Explanation:**
For example, in "abbaca " we could remove "bb " since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca ", of which only "aa " is possible, so the final string is "ca ".
**Example 2:**
**Input:** s = "azxxzy "
**Output:** "ay "
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of lowercase English letters.
| null |
Array,Greedy,Sorting
|
Easy
|
2204
|
670 |
hey what's up guys john here again so today i want to talk about another lead called problem here number 670 maximum swap so the problem description is fairly straightforward basically you're given like an integer and you can only swap two digits at once at most once and then you need to return the possible maximum number afters after swapping right for example this one here 273 6 so the maximum member after 1 swapping will be 7 2 3 6 basically swap 7 with 2 right and in the in case of this one in case all the numbers are so they're like from the mid sorted from biggest to the lowest in this case is already the biggest number possible so there's no point of swapping it in that case you simply just return the number itself right so how should we approach this kind of this problem right I think one basically we need to do some observations here and also write some of the take samples here so I'm gonna just so crazy like some random samples here for 3 let's say 5 3 8 2 3 8 so oh actually it's too big for me because it says the number is like 10 to the 8th power of 8 so anyway I'm just assuming this is still a valid number here I'm just using this kind of long numbers to better explain this approach here so if you watch closely right so basically what we want to do here right we want to swap this number in this case so what's the best optimal solution here all right it's if you watch it closely so we have 9 here the beginning right and then we have eight it is to eight right there's no but later on there's no there's eight here then it's this six right so when we meet six here will be swapping so when we add six so what should we swap when you swap with this de sade no right that eight basically we need to swap these two numbers to get the de madame maximum number right after swapping then okay so I think the first observation will be so for free number right let's say for a number regardless of the values we need to a store I will acknowledge its index right but in our case let's say for eight there like direct how many eight one two three right so which index is the one we care the last index right four in this case right we have two indexes of eight after six but we what we need is the last index right so that's the first observation we keep with that in mind basically we'll be creating like a dictionary or a hash map or whatever you wanna call it and that dictionary will be like the key will be the number itself right how about the value will be the last index of this number right last index okay so first we're gonna have this one hash map here to store each number and its last index right and then with this hash map created how can we use this right then we're gonna loop through the we're gonna loop through all the numbers are the each number here and we're gonna use like a greedy algorithm here or greedy idea here whatever you want to call it so the greedy idea here is that for each numbers we always try it from the biggest number stated which is nine right until this number itself until the number itself plot plus one until six plus one in this case basically for each of the for each hopped and for each of the two try here right basically we try all the numbers bigger than the then the carton bigger than the current index a current bigger than the current number from maximum to the lowest that's why we try to greedy we are hoping to find the maximum as the biggest one as early as possible right and then the reason we stopped at the car number plus one is because if his car is the same as the car numbers we there's no point of swapping it right and if he's smaller of course there's no point of swapping so that's why the range will be from the biggest to the current one and plot plus one right and then what do we track we tell each number within this range what's the index of that number right so if that index is after the last ending if that last index is after the this the current index right if this index is after this current index then we know okay we find out we'll find a way of swapping it right if this one if the this index is before this we know okay it's before that so we cannot swap it for example this it's nine and six and for example we are processing six here right we start from nine here and we see okay nine in the dictionary but the index is it's a likely so it's too right oh sorry is one the last index of nice one is smaller than three so we cannot swap with that so we have to find and then we finish nine here and then we will check eight and then we see eight okay we see eight isn't it is in the harsh map right and the last index of eight is this one somewhere like ten it's I think it's 12 or 13 yeah 12 is greater than then 3 and then we know ok this is the number one so I swap and you need when we find that we can simply stop there because it only allows one swap right cool I think that's proud that's basically the idea of this solution here it's a greedy method a grittier idea here of always try to find the maximum number after this the current number is as early as possible okay so now for coding with first like I said we need to have a dictionary to store all the numbers last index right we can look at last index I will just call it last index what was gonna be that so simply just like the number right the number of index right four which is to enumerate okay so that we can get post the numbers and index right so that's how we to find the last index because if we find this number later on same numbers since this is like integer so this key will be updated with the later index and since we are looking from left to right we are making sure once we finished looping for each number this index will always be the last one right for this number okay so that's that and then okay another thing is in order to swap these numbers right we need to convert this number two to a string to a list off string right otherwise we cannot just still swap right swap in to convert it you know we can either do a like a mathematical way which is like that we divide it we divide this number it's like we do it that they've mod right with this number which is 10 right and every time we cut through the remainder and we add it with a today so string to the list until the this number becomes a zero right but there but we have a simpler way of doing this it's just the tool conversion right basically I'll just use that so we can have a numbers list we do what we simply do a first we convert this number into a string which use a strange function here and then we convert this string to a list right pretty soon pretty simple yeah I think that's ah yeah and then like I said we just simply loop the current loops to loop the integer I'll loop the number here I and right for not in enumerate them right and okay then for each numbers here we loop through nine to the current number plus one right so in order to do that so here right we have to 4i for 4k who did it in range we have to do a knife - - this number - - this number - - this number but this number like it's yeah that's then oh no sorry it should be the list here right so we look through the list here and but since we're trying to do a range from this night to the seat in here to remember current right now this n is a strain right because we convert its integer to a string but what we want is we want this one to be a to be integer so then we have to do a little bit of conversion here I know it's a bit annoying here but let's do it so for each of the numbers here which do I convert it into an integer for right something like this which is for each of the integer character in this string here which is convert into it in integer and then we convert it to a list so now this number will be an integer here right and then we're looking through nine to here right since that the end point is exclusive that happens to just satisfy our requirements here right so we didn't want to include this edge we want to stop it before which means all the numbers it's greater than n right so then for that right so for each of the teachers here we want to check if the this digit index is greater than the current index right so we do what we do our last index right last index since this like this numbers didn't cook up as possible could be not exist in this index here right so we can simply to do this like 50 we can either use a cat right to do that or we can simply do a simple check here if the is in right in the last index right we'll do a simple check and last index dot d right now then we know the DS there is greater than the current index right if that's the case we know okay we find our the numbers we need to swap which you simply swap these two numbers the first number is the int number is index I and the second one will be the num nums list of the last index d here right and then we just simply do a swap it's this short cut short the shorter version line of in Python without using our temporary variables and then we simply return right which simply just I mean we come if we break here you know in Python if you break in the nested loop it will only break for the loop where you're in right now it won't break the outer loop here that's the basically that's how the break works in Python so we can simply return here right we can simply return the so in order to stop this thing we wouldn't we need to do a return here because we cannot break the whole loop and return what we return here okay so we already have it so all we need to do now is just to convert this string a lace back to the integer right so we do int right and then we do what we do up join right we join all this number back to remember here right since the join here joins is expecting a string type so and now we have all the in type in this array so we have to convert them back to the string again I know it's a it's not very intuitive way but I'll just finish what I'm doing here data it's right for it in nom list okay so once again with we convert all the digits all the integer in this num list back to the string and then we join them back and then in the end we return we convert them into integer alright and how about now don't forget about example two here right so if none of those happens which means we never find like a bigger numbers that has like later index we simply return the number itself right okay I think that's that should do it let's run it oh sorry yeah sorry I need to create this list first then I need to use this list to do the in enumerate here alright accept it let's try submit it cool yeah so yeah it works basically the idea here is just to keep the last index of the of this array here not array of this list of numbers for each numbers and then we'll do a greedy search here a greedy search we search all the odd numbers greater than its current digits if there's a index for that number which has which comes which is later they bigger than the current index and then we know we find our results which is sir we just swap them cool I think that's it for this problem you know I'll treat I want to maybe talk up a few I feel a bit more about this problem because at the beginning I didn't come up with these solutions what I did was the I figured out so I figured out I need to swap the we need to swap the other current the ones you know the this number which the current the biggest number right with the later lady's index right so what i did what i end up ended up doing was the i created like a dictionary of course for the to store all the indexes and then I use a priority queue to stores the current biggest numbers right and then every time when I see it when I see that numbers here I Chuck okay so if this number is not same as the first one in the priority queue because that priority queue always gave me the current biggest number right and then if we see our like index here I'm sorry if I see season number here and if it's the same as the current priority queues first element I just remove the index for that number right that's how I keep this like this index this is like priority queue I basically I have a one priority queue and one dictionary for the Congress the not counters the dictionary stores all the numbered each numbers are the indexes in that dictionary I didn't thought about I mean already there was the last index that's why I store all the indexes for these numbers for the current number into that dictionary and every time when I see this like a number there I compared with the priority queue it's the same I just remove the first index from that priority queue from that dictionary because yeah when I add the index I added from lab to writes right so now when I see this number it's safe to remove the first index are in that a dictionary and then when we and when I see a and then if that dictionary the list is empty I just removed the I just pop basically I just do a hip pop from the priority queue then we know okay we have seen all that all the clearances for that numbers and then when I see until we see a number that still halves it's not same as a priority queue the first element then we know okay we need to swap these numbers in there with the last index in that dictionary it's kind of a long implementations but it worked it's not as like I system wise neat as this one but it's a it's anyway it's just my some salt and okay cool guys I think that's it for this problem I think so much for watching the way and I hope see you guys soon bye-bye
|
Maximum Swap
|
maximum-swap
|
You are given an integer `num`. You can swap two digits at most once to get the maximum valued number.
Return _the maximum valued number you can get_.
**Example 1:**
**Input:** num = 2736
**Output:** 7236
**Explanation:** Swap the number 2 and the number 7.
**Example 2:**
**Input:** num = 9973
**Output:** 9973
**Explanation:** No swap.
**Constraints:**
* `0 <= num <= 108`
| null |
Math,Greedy
|
Medium
|
321
|
309 |
hello everyone welcome to my YouTube channel today I'm sorry little question 309 best time to buy and sell stock with cooldown you are given a great prices where prices I is the price of a given stock on the ice day find the maximum profit you can achieve you may complete as many transactions as you like that is buy one and sell one share of the stock multiple times with the following restrictions after you sell your stuff you cannot buy stock on the next day that is you have a cool down one day you may not engage in multiple transactions simultaneously that is you must sell the stock before you buy it again example one the input prices is one two three zero two the output is three the transaction the optimal transaction is you buy on the first day when the price is one and so on the next day to gain profit of one and then you have a cool down for one day when the stock price is the highest and then you buy it on the fourth day and then sell it on the last day to get a profit of two so in total you get profit of one plus two equals three the second example prices equals one the output is zero so how to solve this problem so basically let's think about the overall idea is let's say what is the current state and what is the next state so basically some of the idea is current state you have the current state and then you determine the next state why is that because let's say if you just sell your stock and then the next day you will have a cooldown so basically like overall idea is from the current state to determine the next state so then how to solve it so the first idea is actually to solve it using recursive solution so have a recursive function it may not be the optimal solution or it may run out of time but it's kind of a very yeah basic and easy idea to start with and then we can work on optimizing the solution so first let's go over the idea to solve it using recursion so for the recursion we must know what is the base case and then from the current state to the next state then what is the current state and what is the next state let's say you are checking the uh the prices you are given the prices on each day so basically we uh for our recursive function we have a function we call this recursive function let's say uh recursive function for the day on day only I stay on the I Stay let's assume you have a function I and then from there you go to the next function So currently going to the next state so what can be the current state so you can have a no transaction day basically you perform nothing you do not sell you do not buy so this is uh this state is better or not you have a stock or not let's see whether or not you have a stock you hold a stock you have no transaction day and then what other character States so you can purchase a stock so in our case if you do not hold a stock right now and then and that you are not in cooldown Period in that case you can purchase a stock you can also sell a stock you can sell a stock if you hold the stock basically if you personally have a stock then you can choose to sell that stock so those are the three current states and then what are the next States so basically before we are discussing the next state you can tell from those conditions knowing whether or not you hold the stock is super important because it determines whether or not you can sell a stock so in that case we need to add that status into our function into our recursive function let's say the input for each recursive function is the I indicates on the I stay and then hold is the Boolean variable in the case okay true or false whether or not you hold a stock so that's kind of the input for this recursive function in that case let's determine the next state given the current state if you have a no transaction day so the next day is you just move to the next day that's the next state and then you carry this hold indicator so that's the next state and then if you purchase a stock basically if you purchase a stock today and then you can go to the next day and then in that case your whole indicator is true you can directly go to the next day because you can perform the transactions or have no transactions the next day if you have a stock if you sell a stock then the next day is a cool off period so in that case the next state is actually I plus 2 and then whether or not you hold the stock is false because for I plus 1 you know that immediately after you sell a stock you have a cool down period of one day so in that case from the current state the next state we are actually calling the function for I Plus 2. so in that case we start so our start point fast starting point is the function we start with the I stay and then hold equals false and we do not have a stock so that's our starting point so basically we call this function to enter the recursive function so in that case so what is the base case so the base case is let's say if your eye is out of the index so basically if your I is greater than or equal to the lines of prices so in that case you just return zero okay so we kind of go over the idea of this recursive solution so let's call this solution so we Define a recursive function called I uh and then hold we call this recursive function and then first let's deal with the base case if I is greater than or equal to the amounts of prices you know I guess you'll just return zero and then you cause consider the first uh condition the first state is like no transaction so in that case you just call the function for I plus one hold up and then scenario one that's our scenario one and then scenario two is a purchase or so if you are hold is true if you hold the stuff in that case you can sell a stock in that case your profit is your function pi plus two and then false so in our case we've hold then you sell a stock and then when you sell a stock you gain the prices so you think the prices I after you sign you sell a stock so you add this one to the profit else if not hold in that case you purchase a stock if you purchase stock then you use this prices I so you did you minus this price I've been in that case is equals the next state is I plus one and then that is true so when you enter the next you can enter the next day and then your whole status is true because you just purchase a stock so in our case so what is our answer for uh what is our output for this function that is the maximum from both answer one and answer two so return the maximum of answer one and answer two so basically uh there are two different scenarios there are ones you do not do any transaction in that case your total profit equals the profit uh you get from the next day and then the different scenario one whether or not you hold the stock you can choose to perform notes to do no transaction so it's independent of your whole status you just carry this hold uh value to the next state the second scenario is you can do a transaction so in that case you can purchase or sell whether you purchase or sell depending you on your hold status if you hold or stop then you can sell the stock and then after you sell the stock because you need to have a cool down or for one day after you sell a stock so in that case the total profit is the price I the what you will gain after you sell this stock basically the prices you are selling this stock and then plus uh what the profit you're earning from I plus today if you do not hold the stock then you can do the transaction to purchase a stock and then when you purchase a dog you use this about prices of eye so in that case you reduce that from your total profits and then for the profits of the ice day you just return the maximum of the two so that's the recursive function so let's run the solution oh so we forgot to call this a recursive function so basically return function so our starting point so how we call this function we call it from you're on the Zero step you are actually on the first day that is when the index is zero in the prices uh in the prices already so in that case you are holding holds false you do not have any stock at the starting point so let's run the solution okay we passed the two simple test cases which are submitted you are most likely to run into the time limit to exceed Arrow okay yeah his ass is factored we're trying to submit the solution the time limit to exceed so why is that so you know because let's enter uh analyze the time complexity and then also our space complexity so the time capacity is actually all 2 to the power of n and the outer space complexity is Owen so how to optimize this recur save solution so or common techniques to optimize the recursive solution is to use memorization so in that case we try to reduce the time complexity 201 how to achieve that so basically if I remember the value which the value we encountered before so in our case you keep track of the values you encountered before so in that case let's try to take the solution and then modify on top of that so in our case we want to keep track of the we have a dictionary or we can call it to memory so that is our dictionary we want to use this dictionary to keep track of the values we already calculated so we keep base case the same and then after the base case so basically let's check if I hold in the memory we just directly return memory by hold so that is if it's Harris has already been calculated before which means we're already stored in this memory dictionary then we just return it instead of like entering the recursive uh calling the recursive function and then uh if it's not in the memory if it's not calculated before we just start our calculation so in our case our memory I hold decodes the maximum of those two and then we just return memory by hold so basically after calculation we put the calculator value in our memory and then we just return it now let's run this uh improve the solution okay we pass the basic test cases and let's try submitted okay so this solution actually passed so compare with our original recursive solution we use the memorization basically we add a memory dictionary to keep track of the values we have already calculated before and in our best case to remain the same you just we add one step we first check if it has already calculated before if it's calculate before then we retrieve that from the memory dictionary and return the value directly if it's not calculated before then we just calculate as how we did in the recursive solution and then after calculation we just store this value in our memory and then we return the value so that's kind of how we improved on top of the recursive solution and then now I'm going to cover how to solve it using dynamic programming so to start with using that on my programming so we want to have a dynamic programming uh array to actually keep track of the State House for each day so in our case what we are trying to have is actually a array with or to represent each day and then also the whole the status so we neutralize that to zero so the profit is zero as we're beginning so zero four so effectively we want to have something DP I am done hold the status so basically similar idea to how we uh how we did that in my modification solution so in that case we have a function with input I and hold here we want to keep on array to have the status uh to keep track of I and hold so and then I'm going to initialize that so this one represents the hold so in that case we choose from zero one and then this one we are actually extended beyond the original length of n we add two more elements why is that because let's think about that if we are on the DPN minus one on the last day and then in our case uh the God is actually need to determine if you let's say for currently when I equals n minus one and then we are calling the next is actually n minus one plus two where n minus one plus one so in that case that's why we need to add two more two to this one so to make sure we are not going out of uh we are not going out of index so that is our array for our dynamic programming approach and then let's try call this and then filling in the value so in our case for I hear range and minus one for hold in actually hold have two options it's either a zero or other is one so in our case covered DP I hold so similarly answer one equal uh answer one so equals DPI plus one hold and then if you are hold basically you are uh you are having one stop in that case your answer to equals DP uh I plus two and then false which is uh zero and then here we are considering so selling a stock it's our stock and then previously there is no transaction that is price is I that is what you gain by selling one stock and then after you sell a stock you enter a cooldown period else if you do not hold the stock you just purchase and then after I purchase a stroke your whole status become zero becomes one and then in the end you just return deep dp0 and zero so before you return the final solution you actually have to assign that basically uh inside this Loop you are trying to calculate DPI code that is the maximum from answer one and answer two is not defined so n equals the line of prices so this solution also will pass all the test cases it and it is also accepted so my dynamic programming approach actually looked very similar to the mammalization approach here I'm just using a ray to actually store I call this DP to actually store the status and then while trying to Loop it through I start from the very end why that is because on for I for DPI hold that is actually determined by DPI plus 2 0 DPI plus 1 and then also DPI plus one hold so that's determined by the later days so in that case that's why we are trying to Loop it through we go uh we're calling the I for the range n minus one and up until I reach 0. so that's our dynamic programming approach so in that case the time complexity similar to the memorization approach the time complexity is 2 o n and then space complexity is also Owen so next I'm going to talk about how to optimize the space capacity on top of this dynamic programming approach so basically optimize the space so let's take another look at our dynamic programming approach so in the dynamic programming approach we are trying to calculate the DPI holder that's what we are trying to calculate and then in order to calculate this one what we need so we need to know DPI plus one hold we also need to know DPI plus 2 0 we also need to know the DPI plus 1. so we need so that's what we need in order to calculate the DPI hold so in our case you can tell from here so basically DPI is not determined by BPI plus three it's only determined by DPI plus 1 DPI plus two so in our case we can optimize this dynamic programming approach so to optimize that so we want to say more space so we want to have a smaller array to actually store the DP value so in that case we offer on for each I stay we only need I plus one day and I plus Tuesday so in our case we only need to know I A plus one and I2 so we need to keep track of those three states by three days so in our case we can just reduce this one from n plus two to actually to three and then in our case we are still trying to Loop through uh we keep the same uh four loops and then it just when we keep track of the state let's say you start keeping tracking of the original eye where I is from a minus one up into zero we just mod 3. so basically compared to the original dynamic programming approach we modify the array so that's in our case our DP the dimension of our DP is 2 times 3 instead of two times uh m plus two that's the first modification and then the second modification application seems where for the day for I we only keep track of the three different states so we just like uh divided by three and calculate the remainder so that's kind of the modification we are making and then let's run the solution so you can tell for this one uh this space is actually optimized so for the solution the time capacity is still online that's something you have easily tell from those two lines the for Loop and then the space complexity is actually optimized 201 because you only need array of Dimension uh three times two as opposed to M plus 2 times 2. so in this case you off you optimize the space for this dynamic programming solution so for this problem I went over how we actually start with how we start with the recursive solution that exceeds the time limit and how we optimize that using memorization basically we have a dictionary to store the values we already calculated so that we do now to repeatedly calculate the same thing and then we also talk about the dynamic programming approach it has the same time and space complexity that is Owen and o n and then we also talk about how we optimize the space complexity on top of the dynamic programming solution
|
Best Time to Buy and Sell Stock with Cooldown
|
best-time-to-buy-and-sell-stock-with-cooldown
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:
* After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).
**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
**Example 1:**
**Input:** prices = \[1,2,3,0,2\]
**Output:** 3
**Explanation:** transactions = \[buy, sell, cooldown, buy, sell\]
**Example 2:**
**Input:** prices = \[1\]
**Output:** 0
**Constraints:**
* `1 <= prices.length <= 5000`
* `0 <= prices[i] <= 1000`
| null |
Array,Dynamic Programming
|
Medium
|
121,122
|
14 |
Hello Gas Myself Amrita Welcome Back To Our Channel Techno Sage So In Today's Video We Are Going To Discuss Lead Code Problem Number 14 Date Is Longest Common Prefix So Let's Get Started Let's First Understand The Problem Write Un Function To Find The Longest Common Prefix String Amongst And Are Of Strings If There Is No Common Prefix Then Write And Empty String So Basically C Will Be Given When Are Of Strings And Are You Need To Find D Longest Common Prefix String For Example Here You Can See Have Are Of Strings Having Strings Aaj Flower flow and flat and see you need to find This area of strings so see This area of strings so see This area of strings so see you have returned null correct so nine let's understand you are going to solve this problem so let's take D from input string are having flower flow it will come a flight flow and flower same C are sorting D are because it bikams easy tu find d common prefix ho when d are set so see can directly check d first string and d last string if there is any other common prefix in these strings give definitely date common prefix is going to be there for this prefix is going to be there for this prefix is going to be there for this particular string so see need tu check only for d first van and last van so date mains c are going tu take tu strings van is level of zero and andar van is level of str.len -1 date mains d level of str.len -1 date mains d level of str.len -1 date mains d last string in d area of strings last string in d area of strings last string in d area of strings so when Are you going to check for these and this case will have flight and flat so are you going to check character by character firstly are you going to check first character f matches are you are going to move to next character characters it is not matching So since most of the common prefixes are full you don't need to check for all the other strings because they are sorted. So definitely this common prefix is going to be found for all the other this common prefix is going to be found for all the other this common prefix is going to be found for all the other strings if it exists for the first one and the last one if let's say d first character it self decent match than date mains date is no common prefix see can directly return footage empty string so nine let's try d solution for it so this is r class date is longest common prefix nine let's drive d method date would be Public Static Strings Give It Is Going To Retain D String Longest Common Prefix Right End It Is Going To Expect D Input Test String Are Nine What Was D First Step First See Need You Sort The Are Directly Use Class You Sort Arraysot String Are Date It T R s end give C r going tu take first string and last string so date main string level 1 wood b d first string date is level s of zero end else string date wood b st r tu which wood b last string stores dot length -1 end last string stores dot length -1 end last string stores dot length -1 end give science c are going to compare both d strings character best character c can take one variable next zero because c are going to start from d zero then next end will date index is less give length of d string c can check h character date mains first string dot caret if date is equal tu str.i index service d first character message let c have tu move on to d next character date mains c can increment the index so date in d next iteration it bikams van end let th end Give three up you go on until the character matches l If it doesn't match let c can directly break d look nine come d and c need you check if index is zero From d zero the next till d index so see can say return index zero date mains if index is zero let see you have return nothing else vice return d substring of first string from zero till the index and then let's come back again function and take D to string are having values a flower flow and pod nine let's write values a flower flow and pod nine let's write values a flower flow and pod nine let's write print statement and call the function to C the output so it would be longest and prefix end string nine let's on D programming C the output C can C hair D output is flower science D common prefix in the strings is flower nine let's test it with same negative input let's dress government flow and dog so you can see clearly date there is no common prefix so it should be written and empty string so you can see every in D output date Nothing is returned because in question it self it status date if there is no common prefix return nothing so this is how you need to solve this problem if you have other questions other doubts please let me know in comment section please don't forget to like Share and Subscribe Channel Thank You for Watching
|
Longest Common Prefix
|
longest-common-prefix
|
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string `" "`.
**Example 1:**
**Input:** strs = \[ "flower ", "flow ", "flight "\]
**Output:** "fl "
**Example 2:**
**Input:** strs = \[ "dog ", "racecar ", "car "\]
**Output:** " "
**Explanation:** There is no common prefix among the input strings.
**Constraints:**
* `1 <= strs.length <= 200`
* `0 <= strs[i].length <= 200`
* `strs[i]` consists of only lowercase English letters.
| null |
String
|
Easy
| null |
134 |
hello and welcome to my YouTube channel today's video will be solving the gas station problem from its code before we get started make sure to hit that subscribe button if you haven't already that's why you won't miss out on any of the great content we have planned for this channel thanks for watching and let's get started so the problem is that you are given a list of stations each with a certain amount of gas and a certain cost to travel to the next station and they ask us to find the starting gas station index that allow us to travel around the circuit once in the clockwise Direction otherwise we return -1 for example let's say we have this -1 for example let's say we have this -1 for example let's say we have this input list in this example it is possible to complete the circuit starting at Station 3 means the index 3. this is because we have enough gas to visit station five one and two and three and complete the circle in this case the function should return three on the other hand let's say we have this impost list this server at the station 2 and fill up with four units of gas your tank gonna be four you cannot travel back to Station 2 as it's required four units of gas because you only have tree then it's not possible to complete the circuit starting at any of the station in this case the function should return -1 so to case the function should return -1 so to case the function should return -1 so to solve this problem we're going to use the greedy algorithm and the greedy algorithm is an approach for solving problems by selecting the best option available at the moment so we're going to start iterating over the gas stations first we calculate the remaining gas after visiting each station if the last or the remaining gas become negative that means we cannot complete the circuit starting at this index so what we do is to set the start index to be the next station and reset the remaining gas station to be zero and then we continue repeating the same process so here at index 3 we have a positive remaining gas station means we can travel to the next station so we keep the start index at index 3 and we move to the next we have 5 minus two which is 3 added to remaining gas station from the previous calculation so the remaining gas station is six at the end we return the starting index which is 3 in this example so if the remaining gas is always non-negative it means that is always non-negative it means that is always non-negative it means that is possible to complete the circuit and the starting index is the one we found otherwise it will return -1 or we can otherwise it will return -1 or we can otherwise it will return -1 or we can say that if the sum of gas station is less than the sum of costs will return -1 because it's not possible to complete -1 because it's not possible to complete -1 because it's not possible to complete the circuit that's it guys so let's jump at code in the solution first we check if the sum of gas station is less than the cost will return minus one because it's not possible to complete the circuit we initialize the starting index to zero and the last gas to zero then we start iterating throughout the gas station we calculate the last gas after visiting the station if the last gas is less than zero we update the starting index to be the next station and we change the last gas to be zero finally after the loop finishes and we have a non-negative last gaze means the have a non-negative last gaze means the have a non-negative last gaze means the remaining gaze station will return the start index so this solution has a Time complexity of often because we are accelerating throughout the gas station and for the space complexities of one because we are not using any extra space memory thanks for watching see you on the next video
|
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
|
436 |
hey everybody this is larry this is day 27 of the august eco daily challenge uh hit the like button hit the subscribe button join me in discord and let's get started on find right interval uh okay give him a set of check if there exists an integral j equals storm point is bigger or equal to n point of integral i which can be called j is on the right of i um for any interval i you need to store the minimum index oh so that okay let's take a look at some examples so okay what is the weight into again reading is kind of hard for me uh okay okay minimum right starting point i'm still not quite sure what the definitions are so there no seven one four hundred two three four one you can check if your starting point is bigger than or equal to the endpoint okay so okay i think they just didn't define that uh okay so the this is the starting point this is the end point i think that's the part that i they skipped over and wasn't precise about and i was just reading it um right minimum starting point to build the ring okay so basically because three is closer to two and one okay um okay do we only care about eyes that are less than j or something okay no that's not true because 2 3 goes to 3 4. okay uh okay yeah so i uh so it took a long time to kind of read this form correct uh and definitely during a contest i sometimes have issues with that uh because you just want to be as fast as possible but you know misreading will cost you even more time as you um as you solve the one problem which i've done from time to time and hope you know you don't but um okay i mean so basically there are a couple of ways to do this uh i think i just have a couple of oh okay so wait what does this mean meaning that the starting points are unique um okay um i think i'm still in that understanding the problem stage um now let's put these in there but i think the one question i have was whether it has to be exactly the bigger or you cooked too so that means that in theory if you have uh one two and then i don't know ten eleven then this should still point to negative one or something like that right i have to you are kidding me how do we move all these things oh i didn't that's my vibe that was me being silly okay so yeah one negative one as i expected okay so then that's this becomes a problem of for each interval find the number that's bigger than um or the smallest number that's bigger than the n interval that should be okay i mean you could definitely do it with a tree um or some sort of uh i think this is actually what she's in c plus uh but maybe this actually gives me an opportunity to learn something new um because in and you can do stuff with binary search so you can actually manually implement a binary search and they'll probably be okay one thing to note is that this is a little bit weird but one thing to note is that because all the starting points are unique um an interval cannot find itself so you don't have to worry about that weird edge case if that makes sense uh depending on how you because in some similar problems you may have run into something like that um but for me um i do want to fi so one thing that i've been meaning to learn is this think course sorted containers uh and i'm i am going to try to figure out how to use it i'm reading api now uh so if you want to read with me this is the link um but basically um yeah uh you know for these for any problems really on lead code or wherever you're studying um you know try to focus on what you want to learn uh even if you know the algorithm you know maybe try to learn something new and for me sort of containers have been on my list to learn for a long time so this is a perfect time for me to kind of uh jump into it um yeah but generally okay just to explain the algorithm a little bit you can do it with a tree you can do it with binary search you can do it a number of ways but it's just a number of queries where okay here's a four get the smallest uh left starting point that is bigger than or equal to four right and if you put everything in the list and then you sort it and then you could binary search so that's pretty straightforward i think um yeah implementation may be a little tricky with binary search as usual but you could do it uh but it was but for me right now i'm taking the opportunity to observe if you will learning sorted containers which is something that i've been seeing more and more uh and it's and the three types of sorted containers uh as i'll put it here uh there's sorted lists sort of dictionary and sorted set i'm trying to figure out which one makes sense the most um probably not this probably the uh the dictionary one if it has the interface that i think it does um because then now we can maybe i'm just playing around so this might actually be really bad really terrible but you know we're on this journey together i hope you uh you know find something useful while you're here uh but for interval in sd oh and i guess i have to enumerate it to get the index okay so how do i do this oh no this is intervals oops uh so sd type uh so we want the this is an integral which is actually start and n right so we want to keep track of start is equal to uh do we even care about the n i guess not actually no i guess we don't so we could actually just do this uh and the n doesn't matter except for when we process the answer right so okay and then now we can do it again for um let's do this and then now we can just do i think bisect i always forget which one is bisect left and right and five seconds but i think bisect left is the correct one where it can be equal to so we wanna bisect on the n um i don't think this is quite right to syntax but let's run it just to see what it gives us uh maybe in general also if i had a id i would put this in a debugger or something like that but uh this is not defined i thought someone told me that sorted containers is already automatically uh defined but maybe i'm wrong on that one only code i hope this is on it otherwise it's a little sad okay so the fourth type finds did i do this right i don't know what these numbers about percent that's probably my problem uh yeah okay let's print out uh like i don't literally don't know it just gives me the index or the key i guess the three is just representing that um it is out of the thing but and put an end here as well so we could just have better debugging and you know um for me even if i had gotten it right i would do some printing just so that i could learn more about how the api works as opposed to me guessing how it works um so now we're looking for four we find in the three does that make sense and maybe i'm not sure also uh how sordid dick works with um with uh bisect don't have an idea of it comprise two keys yeah that's what i would guessed oh so just gives the return to index to insert the value in a sorted list yeah did i look at the wrong one i want the one for dictionary right sort of dictionary yeah okay it applies to keys yeah exactly okay but then it gives me the index which is not super useful maybe hmm i mean okay this is kind of where we want but not really hmm so maybe we don't need a dictionary on this even though it's a little bit easier to use maybe but hmm all right it's a key maybe this one returns the index as well why is it similar to okay um apparently the way to do it and i don't know about the complex of this one to be honest so uh so we might have to you know see how that goes but so that's the index and you have to do something like sd.k if index is uh less than keys so something like that so you're learning me learning you're watching me learning in real time uh okay let's run the code real quick so that's the way that it seems like you would do it but it still feels a little bit off um also this is just wrong right uh this i returned the key but we actually want the value so we actually want the sd of this okay because we store the uh we saw the index here right okay so this looks i mean this looks good here uh let's submit it i don't so again i don't know i have to maybe do a little read up on the complexity of uh dot keys uh maybe something that internally um you know like if it iterates for every item to generate this then that's a little bit sad if it's just uh an interface to a pointer that's an assorted list that's in internal representation which i have to kind of look up uh then it could then it's not so bad um yeah let's pretend that it does this in the reasonable way uh then in theory um you know this does everything in uh so this n items and integrals and each of these will take all log n time roughly so this is n log n uh in the same way uh this is all over n items uh and then each of these will take over log n times um and yeah i would say in theory this is our one uh so this is gonna be an o of n log n algorithm um yeah so this is how i and space is going to be all of n because you just keep one item per interval item uh but yeah that's all i have for this problem uh thanks for watching me um uh you know thanks for watching me he's learning this from uh this is going to be a interesting prom i really will have to take a look at the performance uh to make sure that this is the case but otherwise this is pretty cool uh and i hope that you learned something as well uh hit the like button hit the subscribe button and i will see y'all tomorrow bye
|
Find Right Interval
|
find-right-interval
|
You are given an array of `intervals`, where `intervals[i] = [starti, endi]` and each `starti` is **unique**.
The **right interval** for an interval `i` is an interval `j` such that `startj >= endi` and `startj` is **minimized**. Note that `i` may equal `j`.
Return _an array of **right interval** indices for each interval `i`_. If no **right interval** exists for interval `i`, then put `-1` at index `i`.
**Example 1:**
**Input:** intervals = \[\[1,2\]\]
**Output:** \[-1\]
**Explanation:** There is only one interval in the collection, so it outputs -1.
**Example 2:**
**Input:** intervals = \[\[3,4\],\[2,3\],\[1,2\]\]
**Output:** \[-1,0,1\]
**Explanation:** There is no right interval for \[3,4\].
The right interval for \[2,3\] is \[3,4\] since start0 = 3 is the smallest start that is >= end1 = 3.
The right interval for \[1,2\] is \[2,3\] since start1 = 2 is the smallest start that is >= end2 = 2.
**Example 3:**
**Input:** intervals = \[\[1,4\],\[2,3\],\[3,4\]\]
**Output:** \[-1,2,-1\]
**Explanation:** There is no right interval for \[1,4\] and \[3,4\].
The right interval for \[2,3\] is \[3,4\] since start2 = 3 is the smallest start that is >= end1 = 3.
**Constraints:**
* `1 <= intervals.length <= 2 * 104`
* `intervals[i].length == 2`
* `-106 <= starti <= endi <= 106`
* The start point of each interval is **unique**.
| null |
Array,Binary Search,Sorting
|
Medium
|
352
|
35 |
hey everyone welcome back and let's write some more neat code today so today let's look at leak code 35 search insert position so we're given an array of distinct integers just like this one down here and a target value in this example the target value is 5 and we want to know does this 5 exist in this input array if it does if we found the target then we return the index in this case the index was 2 right 0 1 2. but there's going to be some cases where we do not find the value in that case we're going to return the index if we were to insert the value in order conveniently for us the input is sorted so in this example 2 now 2 is not in this array but we know that in order it would go over here between the one and the three so in that case we would have a output array or a new array of 1 2 3 5 6. now the index the indices of this are going to be 0 1 2 3 4. so we're going to return 1 because that's the index that we inserted our 2 at and that's what they tell us in the example now your first thought might be well since the input is sorted and we're given a target value then can't we just go left to right and just you know search the array starting at index one uh is this equal to five nope is this equal to five it is so we return value 2 because that's the index so this is actually easier than you'd expect right this is the easiest solution it's not even a bad solution it's o of n we didn't need any extra memory this is a pretty good solution but my question is can we do even better than this is it even possible to do better than linear time o of n is that possible well the hint that they gave us is that this input is sorted can we use that to our advantage can we maybe do better can we get a solution that's login and the answer is yes how are we going to do it well there's a standard algorithm that's called binary search that you may have heard of and i'm going to show you how to code that up to get the most optimal solution for this problem now the reason we're doing binary searches we don't want to have to go through every single value and potentially check it so we're going to do a slight shortcut we're going to use the fact that this is sorted to our advantage now binary search works like this we get a left pointer and an initialize it over here so at index 0 we get a right pointer and initialize it over here and that index is 3 and now we need to compute the middle because we don't want to have to start from the left and then check every value and we don't want to have to start from the right and check every value so maybe we can start in the middle and then kind of expand outwardly and use some shortcuts to our advantage so when we're computing the middle we're just going gonna take zero plus three and divide it by two and we're gonna get a one so we can put our middle over here and now let's check is this middle value the target 3 is not equal to 5 so we don't this is not the value we're looking for so we're done so we have to update our pointers but we know that 5 is greater than 3 so where are we going to search now we need to move our middle pointer are we going to move it over there or are we going to move it over there since we want to start searching to the right we're going to update our pointers and shift them to the right so we can leave our right pointer where it is because we're looking for greater values but this left pointer is going to have to change we're going to have to shift it to the right so now our left pointer is going to be over here at index two so now let's recompute our middle pointer which is going to be two plus three divided by two so we're taking the averages of our left and right pointers and that's going to give us a two so now our middle pointer is also going to be at this position at index two and so we check is this value now our target value that we're looking for it turns out it is so we found our solution we can return index two but so what happens if our target value doesn't actually exist in our input array what if our target value is actually two let's see what happens in that case notice how we're still initializing our left pointer here we're still initializing our right pointer here and we're still going to compute the middle the exact same way so 0 plus three over two is going to be one so we can put our middle pointer over here once again now let's check is three equal to our target three is not equal to two our target two is actually less than three so we didn't find our target but now the only question we have but so now since we know this is not our target the only question we have is which way do we shift are we going to start looking for our target over here well these numbers are even bigger than 3 so they're obviously going to be even bigger than 2. so we can instead start looking to the left so since we're looking to the left we don't have to update our left pointer all we have to do is take our right pointer and then shift it towards the left and since we don't have to check these values i'm just going to cross them out because we know they're too big and now we can have our right pointer over here at the same index as our left pointer so now let's check one is this our target it is not so we didn't find our target one is not the target either and we crossed out every value so two does not even exist in our input array so what do we do now well we don't actually need to find the value we just need to know what index we would insert it at so since 2 is greater than 1 that means we have to start searching to the right but we know that we already searched every value to the right and we like we also have this arrow going to the left so where's the result from the picture it's pretty easy to see that this is where we would insert our two and we would want to shift our left pointer because we want to update our left boundary so we would say left plus one is going to be our return value so this is kind of a high level general overview of binary search and i'm going to code this up and remember that this algorithm is efficient at least more efficient than o of n it's login and the reason is because remember when we crossed these two values out we crossed them out without even checking them we didn't have to check every value to know that these couldn't possibly be the result value that's why this is much better than big o of n if we had a really large input array log n would be more efficient than o of n and we're going to initialize our left and right pointers just like we did in the visual explanation to 0 which is the leftmost and length of our input array nums minus 1 which is the rightmost value and now we're going to start doing our binary search so we're going and while left is less than right so while our left pointer hasn't crossed our right pointer which makes sense right left should be towards the left and right should be towards the right and now we're going to compute the middle pointer do some fractions so left plus right divided by two in python you need the double slash and now the first thing we can check is did we instantly find our target did we get really lucky and maybe the first value that we checked was equal to our target is nums of middle index equal to the target if it is we know that we can return that middle index because that's what we're trying to do is just return the index if that's not the case though there's only two possibilities one possibility is that our target is too big it's much it's greater than the middle value in that case we want to start searching to the right so we can update our left pointer and shift it towards the right the last case is if target was less than nums of middle or in other words the else case in that case we would want to start searching towards the left because our target is small so we want to go to the left where the small numbers exist now the last thing is what if we never find our target what are we going to return in that case i'm going to return the left pointer just like we did in our visual explanation now why is it the left why not right or why not even middle right why are we returning the left first i'm going to run the code to prove to you that it works and then i'm going to explain a couple of the edge cases to show you why so you can see this time it was better than 97 that's why we want to do log n because it's the most efficient but why are we returning the left pointer let me explain so what if we had a target of one and an array with just one value two then we would have our left pointer here and we would have our right pointer here but we would see that one is less than two so we're going to start searching to the left meaning we're gonna take our right boundary and put it over here but clearly now our pointers don't make sense right left should not be to the right of right so in this case we're gonna stop our uh our code is gonna stop right our loop is gonna stop we're gonna return left just like we wrote in our code and left is equal to zero right that's the index that it's at and that's exactly what we want to do because once we take this one and insert it our new output array is going to be one two but what if our target was different what if our target was three then once again our left pointer is going to start here our right pointer is going to start here but 3 is greater than 2. so now we're going to start searching to the right meaning we're going to take our left boundary and then move it over here but now once again this doesn't make sense the left is out of bounds and left is to the right of our right pointer that doesn't make sense our loop is going to stop executing and what value are we going to return we're going to return left just like we wrote in our code and what is left is equal to 1 and that makes sense doesn't it because 3 if we're going to insert it over here and the output array then is going to be 2 3 our 3 is at index 1 which is exactly the value that we returned i hope this at least explains kind of the main ideas of it let me know if you have any questions thank you so much for watching and i hope to see you soon
|
Search Insert Position
|
search-insert-position
|
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[1,3,5,6\], target = 5
**Output:** 2
**Example 2:**
**Input:** nums = \[1,3,5,6\], target = 2
**Output:** 1
**Example 3:**
**Input:** nums = \[1,3,5,6\], target = 7
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` contains **distinct** values sorted in **ascending** order.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Easy
|
278
|
1,695 |
hey there everyone welcome back to lead coding in this video we'll be solving the second question of lead code weekly contest 220 name of the problem is maximum erratio value so this is the solution that i came up during the contest is still going on and in case you have some better approach that currently i am not able to think of please comment down below now let's read the problem statement and start solving the problem you are given an area of positive integers numbers and you want to erase a sub array containing unique elements the score you get by erasing the sub array is equal to sum of its element run the maximum score you can get by erasing exactly one sub array and array b is called a sub array of a if it is forms a contiguous subsequence of a that we already know so basically in this case what we can do is we can erase the element two four five and six because there's a sub array and it contains really unique elements so the summation is 17 and this is the optimal answer next in this we can either erase 5 to 1 that is this sub array or we can erase one two five that is this sub array and if we try to go beyond this like if we extend this to the right then we will not have unique elements because two is appearing twice similarly if we try to expand this to the left the same will happen here as well so the maximum summation that we can get in a sub array which have only unique element is this much 8 1 2 and 5. all right now let us see how we can solve this problem let us go to the whiteboard for that so let me quickly pick up the example it is four two four five six four two four five and six so these are the elements now what we can do is we can start reversing from the beginning we can start traversing from here then we know that this is only unique element as there is no four behind this then we can come to this element and we will see that this is also unique because there is no occurrence of 2 behind this so we can include this as well in the answer now our answer is 6 2 plus 4 now as soon as we come to this 4 we know that there's already one for behind this how we can know this for that we can use a map or we can use a vector as well to store the elements and their index is corresponding to the elements the way we do in maps so here the constraints are given as 10 raised to the power 4. we can either use a map or we can use a vector to store the elements and then their indexes corresponding to the element here we know that four occurred at the index zero two occurred at the index one again when we are at the index two four is occurring and we will know from our lookup table or from our map that 4 has already occurred and it occurred at the index 0. so what we can do is we can sim try finding the summation from the index 1 till the index 2 because 4 already occurred at the index 0 so now we will have to find the summation from the index 1 till the index 2 next we go to 5 and we know that there's no occurrence of 5 when we look into our lookup table or our map and that is why now we will have to find the summation from the index one till the index three as we have already shifted our starting point to the index one just because of this four next we come to six again we will have to find the summation from the index 1 till the index 4 let us see the other example i think that will make things more clear so this is the next example let me first index them all right so now our lookup table is empty there is no element and our starting index from where we have to find the summation is also 0. so this is our starting index and it is 0. so from here we have to find the summation when we come to 5 we will have to find the summation from 0 till 0 and the summation will be 5. so this will be our answer next when we go to 2 also we will have to store the index 0 corresponding to index 5. next when we come to index 2 we will see into our lookup table there is no occurrence of 2 so that is why our starting point will remain zero so as there's no occurrence of two we will have to find the summation from zero till the index one because the starting point is still zero so the summation will be seven and the answer will be 7 as it is the maximum and corresponding to 2 now i will store 1 because 2 is occurring at the next one next we are going to 1 and there is no occurrence of 1 behind this so again the starting point will remain same and we will have to find the summation from 0 till the index 2 and the summation will be 8. now corresponding to 1 i will add the index 2 this is our lookup table actually this is our lookup table and this is our starting point now when we go to 2 we will find innova lookup table that 2 already occurred at the index 1. so now our starting index will become just after 1 that is 2. because we will have to ignore all the elements still one so we have to ignore all the elements from the starting of the array till one so now our starting point will become two that is the index at which uh two occurred plus one so a starting point will now become two and the summation we will have to find on the index two till the index three and that three is equal to three so three and it will not change the global answer because it is still the maximum next one we go to five also we will have to update the position of two now the position of two in our lookup table will now become three we have to update the recent position the most recent position next is five in the lookup table we will see that five is occurring at the index zero but our starting point is already two so we won't change the starting point because we cannot go behind actually so our starting point is not going to change but corresponding to 5 we will be inserting the index 4 in our lookup table also we can find the summation from the index 2 till the index 4 the summation will be 8 the global answer will still remain eight then we come to two so for two if we look into the lookup table the index is three so two is occurring at three and our starting point was two so now our starting point will change now it will become 4 3 plus 1 4 this will be our latest starting point and we will have to find the summation from the index 4 till the index 5 the summation will be 7 corresponding to 2 we will update 5 and we will carry on this process till the end so i hope you got this another thing is each time when we are computing the summation from a certain index starting point till the current index then it is going to take big o of n and the entire process is again going to take big o of n so the overall complexity will become big o of n square but as the constraints are high the constraints are given as 10 raised to the power 5 we won't be able to solve this in one second so for that what we'll have to do is we can maintain a prefix summary in order to find the summation from a certain starting point in the current index we can maintain a prefix summary and using the prefix sum array finding the summation from given l to r would be computed in big o of 1 that is in constant time so for those who don't know about prefix sum it is simply the summation from the index 0 till the current index so if i draw the prefix sum for this array it will become 5 then the next index will be 5 plus 2 7 then next will be 5 plus 2 plus 1 8 then 5 plus 2 plus 1 plus 2 10 then plus 5 that is 15 then 17 and so on and if i want to find the summation from the index let's say 1 till 3 so from here till here what i will have to do is i will have to look at the element present at the index 3 and subtract the element which is present at the index 1 that is 2 minus 1 so just behind this and that will be equal to 5 10 minus 5 and we can see the summation is 5 from the index 1 till the index 3 all right now let us go on and try to implement this so let us first create the prefix summary n is the size of the array nums the prefix summary which i am creating will be one based indexing so at the index 0 i will place 0 and it will help me in the further implementation basically writing less lines of code so p of i plus 1 will be equal to p of i this is just one base indexing you can pause and just think about it once now we are done with the prefix summary and we are keeping s is equal to 0 this is our starting point now we will run a loop from in i is equal to 0 is more than and i plus we are going to each of the element in the nums and also we will have to keep a map that i was talking about instead of map i am keeping a vector i think this is the range for the elements so i think this will be enough now in this m i am going to keep the index corresponding to each of the element but as of now there is no element that i have seen so i am keeping minus 1 all right now first of all s will be equal to maximum of s comma m of nums of i plus 1 now we will have to find the summation starting from s till the current index i and that will be answer so answer will be equal to maximum of answer comma p of i plus 1 because it is one based indexing minus p of s and then i will have to update our lookup table numbers of i is equal to i and finally i can return the answer let me create the answer as well let us run this code 1798 and it got accepted so talking about this space complexity we are using a prefix sum array and that is big o of n again this lookup table is big o of n where n is actually the range of the numbers so it is big o of n in terms of space in terms of time it is going to be big o of n as well because here uh the loop is big o of n to compute the prefix sum and here also the loop is big o of n now let us move on to the next question and if you like the video please subscribe to the channel and press the bell icon so that you can get notifications to our videos thank you
|
Maximum Erasure Value
|
maximum-sum-obtained-of-any-permutation
|
You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements.
Return _the **maximum score** you can get by erasing **exactly one** subarray._
An array `b` is called to be a subarray of `a` if it forms a contiguous subsequence of `a`, that is, if it is equal to `a[l],a[l+1],...,a[r]` for some `(l,r)`.
**Example 1:**
**Input:** nums = \[4,2,4,5,6\]
**Output:** 17
**Explanation:** The optimal subarray here is \[2,4,5,6\].
**Example 2:**
**Input:** nums = \[5,2,1,2,5,2,1,2,5\]
**Output:** 8
**Explanation:** The optimal subarray here is \[5,2,1\] or \[1,2,5\].
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 104`
|
Indexes with higher frequencies should be bound with larger values
|
Array,Greedy,Sorting,Prefix Sum
|
Medium
| null |
42 |
in this video we're going to take a look at um a lethal problem called trapping rain water so given a negative integers representing a elevation map where the width of each bar is one compute how much water it can trap after raining so here you can see we have an array and the above elevation map uh the black section is represented by array this one right here and each in this case six water units is represented by blue section are being trapped so here you can see we have zero that means they're at this position there's zero elevation point and if there's one that means there's one elevation point there's not going to be a water trap here because there's no elevation point on the left so we need to have elevation point on the left and on the right to get the um to have water being trapped right so if there's no elevation point in this case there's no water being trapped so you can see here that there are total six units because we have one two three four five six okay pretty straightforward and um to do this problem i'm going to teach you how we can do this in a brute force away i think it's very important to understand how to do this brute force in a brute force approach and then we can improve our time complexity down to a dynamic programming way where we can be able to bring time complexity down to a linear but the space complexity is going to be linear as well so we're also gonna i'm also gonna teach you how we can do this in a using two pointer technique which we're going to bring the time um the space complexity down to a constant instead of linear this will be very important to know um so let's start with the proof force approach so the brute force approach are pretty is pretty easy all we're trying to do here is we're trying to uh if we were to calculate how many water units for each position in the array right for how many water units is each position in the array um is uh is having right so in this case the current position let's say is this one right here right this could this position to define to figure out how many water units this position can um this view this position have all we're trying to do here is we're trying to find the left um maximum value right the left maximum elevation if there's no left maximum elevation then that's going to be there's no there's not going to be any water trapping right just like i talked about and then what we're going to do is we're going to find the maximum elevation point the max the maximum elevation value on the left and the maximum elevation value on the right in this case the maximum left elevation is two the maximum elevation on the right is three and what we're going to do is we're going to find the minimum value between those two value in this case the minimum is 2 right 2 is smaller than 3. once we find the minimum value what we're going to do is we're going to minus the current height and this will give us the number of water units that the current position can have right and then all we have to do is we have to increment the current um number of water units for the current position um onto the sum right we get all the water units um how many water units for each every single position in the um in the array and then we get the sum of that and then we just return the sum right in this case we have one two three four five six water units right so this is going to be the brute force approach because for each iteration we have to find the um the maximum value on the left side and the maximum value on the right side so this will give us a n square time complexity but a constant time in space so what we can do instead to make this better is we can use a dynamic programming basically we're going to solve this problem by simply memoize the um all the maximum value on the left for each and every single position and all the maximum value on the right for each and every single position in the given array so what we're trying to do here is we're trying to so here's the base case if the um if the length is less than two right if the length of the array is less than two then we can guarantee that there's no water trapped right so there's no water being trapped because we need a left elevation and a right elevation we need at least three um space right three elements in the array to work with because we need to have a left and a right elevation right now we're going to do is we're going to have a left array to memoize to basically iterate each and every single element to compare um to compare the maximum value right in this case the maximum value that we have um on the left so far at the current position and then we also have a right array to keep track of the maximum um value on the right for each and every single element in the array right so in this case the given array we want to find the maximum l um for let's say for example this one right here so for this element right here the maximum let's say this album right here right this element right here the maximum value on the left is this one right here right the maximum value on the right is this value right here so we are constantly um using a two array right we're using two arrays to keep track of the left and the right for the current position for the value for the current value in the array in the given height array then we're going to do is we're just going to find the minimum for the current position right so find the minimum on the left and the right find the minimum max value on the left and the right and then minus the current height will give us how many water units the current position in the array can have right in this case we're going to give the left uh the sorry the maximum right value for the current position and the maximum left value for left for the current position minus the current height will give us the how many water units for the current position have and then we just plus that onto our sum and then we just return some at the end right so this will give us a linear time complexity and also linear in space complexity as well so it should be s p e s p space right space so constant sorry linear in space so this will give us a linear space complexity but what we can do is we can use two pointers to optimize this solution which is what i'm about to show you basically we're trying to do is we're we know the core um core steps to solve the problem right all we need to do is we need to find if we were to find the how many water for the current position what you need to do is we need to find the maximum value on the left and then find the maximum value on the right to figure out the how many water units we can we have for the current position so all we need to do is we need to do first do a linear scan for the find to find the maximum value in this case the maximum value is here we have three elements right we sorry we have value of three in this case that's the maximum elevation point what we're going to do then is we're basically just going to start from zero in this case start from the left right work our way up to the um the right the maximum on the right in this case this is going to be our maximum on the right so we're going to start from zero and for each iteration we're just going to redefine our left max right so we're so this is going to be our current point our pointer is going to point here right we're going to say well um starting from here we're going to redefine our mac our left max right in this case there the left max in this case is going to be 0. so the minimum between 0 and 3 in this case 0 zero minus current height is also zero so the maximum uh the um the number of water units that we can have at the current position is zero right makes sense and then we just keep going and then keep going until we get to this point where we uh we know that the maximum water units we can have is zero because this is the highest elevation and if this is the highest elevation we guarantee that there's no water units right because this is the highest and there's no left and the right to support that right so in this case there's zero water units so we're gonna do is we're gonna traverse up to this current point and that's it and then we're gonna do is we're gonna swap it around we're gonna say this is our left max and we're going to go from the last element where the last element on the array towards the left max right and then we're going to do is we're just for each iteration we're gonna redefine our right max so i think it's better to show you this in code i'm just gonna um i'm just gonna walk you through how we can do this in code for using two pointers way so again our first step right remember just to do a linear scan to find our maximum value our maximum elevation point max is equal to let's say zero initially we're going to iterate each and every single element in the um let's also get a n which is equal to high dot the length okay so we're going to do is we're basically going to iterate and notice here we're trying we're not here to get the value we're trying to get the index so we're saying this if height at max is less than height at current position right we're going to do is we're going to get max is equal to i okay we're going to get max is equal to the maximum elevation point or the maximum value the maximum values index in the array then we're going to do is we're just going to once we have our maximum elevation point we're going to do is we're going to start from the left all the way working towards the right max right the max is gonna be on our right we're starting from the first element in the array so left right in this case the left max okay is equal to zero initially we're gonna do is we're gonna start i is equal to zero i is less than max okay so the maximum index so the maximum elevation point index gonna do is we're just going to um first right compare the max um the left maximum value with the uh the current value right because there could the current value could be also bigger than the max um the left max that we have already so we're going to do is left max because left max is going to be the index right so in this case if height at left max is less than height at current position then we're going to do is we're going to get left max is equal to i because we're dealing with index here we're not dealing with value right those ones here this max the left max they're all index they're not value and then we're going to do is we're just going to calculate the how many water units we have for the current position right because we now we know our left max right and we also know the right max because we traverse the array right we're going from i all the way to max okay so then we're going to do is we're going to have a variable called sum initially it's a zero right so sum is equal to sum plus the um the minimum right just like we talked about the minimum between the left max and the right max okay once we find the minimum between those two what we're going to do then is we're going to minus the current height okay once we minus the current height this will give us the new sum right and then what we're going to do is we basically get how many waters unit we can have up to this current position right up to this current position we pretty much get all the water using we already calculate all the water units we can have up to the max okay now we're going to do is we're just going to figure out the right side in this case what we're going to do is we're going to have a variable that is called right max which is equal to 0 and then what we're going to do is we're going to start at n minus 1. while i is less than the max okay i minus basically we're just going to start from the last element working towards the maximum elevation point all right so we're going to do is we're going to say height it's at right max if it's less than the current position right if it's less than the current height then we're going to do is we're just going to get right max is equal to i just like how we did here if it's less than we're just going to redefine our right max right and the sum right is equal to the minimum of between the max right and the height of the right max now we're going to minus height at i okay this will give us the new sum for the current up to um for the current position right and then what we're going to do is we're just going to at the end which is going to return some so we're basically going from starting from last element working towards the highest elevation point and we don't really have to touch the elevation point because we know that there's just like i mentioned there's no there's going to be zero water units at this point okay because we know that this is the highest elevation point there's no um elevation that are larger than um than this elevation point so therefore um there's no there's basically there's going to be zero water units so let's try to run the code um yeah it should be n right so in this case we're traversing the entire array let's try to submit we have a wrong answer okay so the reason why we're getting the wrong answer there is because we uh when we have the right max it's actually going to start from the last element so in this case it's gonna be equal to the index of n minus one okay so we're starting at the right max right so we're starting at the right max and then we're just working two words um in this case we're starting from the last element which is working towards the um the highest elevation point so now if we were to run this code okay now let's submit you can see we have our answer so this is how we bring the space complexity down to constant and then um time complexity in this case is going to be linear okay so there you have it and thank you for watching
|
Trapping Rain Water
|
trapping-rain-water
|
Given `n` non-negative integers representing an elevation map where the width of each bar is `1`, compute how much water it can trap after raining.
**Example 1:**
**Input:** height = \[0,1,0,2,1,0,1,3,2,1,2,1\]
**Output:** 6
**Explanation:** The above elevation map (black section) is represented by array \[0,1,0,2,1,0,1,3,2,1,2,1\]. In this case, 6 units of rain water (blue section) are being trapped.
**Example 2:**
**Input:** height = \[4,2,0,3,2,5\]
**Output:** 9
**Constraints:**
* `n == height.length`
* `1 <= n <= 2 * 104`
* `0 <= height[i] <= 105`
| null |
Array,Two Pointers,Dynamic Programming,Stack,Monotonic Stack
|
Hard
|
11,238,407,756
|
1,558 |
uh let's go to question 15 58 minimum numbers of function course to make target only this is medium question let's get into it okay let's check the function first our name is modify and then argument first argument is already and then second operation and this are these index okay if operation is zero at the value one in index so given index item we just add one and then if operation is one and then multiplied by two all elements so operation one we multiply twice all of item in only okay your task is from an integer already known from an initially array of zeros all right that is the same size as nums return the minimum number of function calls to make norms to array the answer is guaranteed to pit in a 32-bit is guaranteed to pit in a 32-bit is guaranteed to pit in a 32-bit side integer okay let's check the example one is one five so it starts with one row and then increase to one first and then double because double is the more fast right so double two four now is here and then now it's time to increase this one and this one so first increases one and one four and then last increase five because five cannot make the double right so that is legion so finally uh the this one operation and then one two total five how we gonna death okay uh maybe we can do our reverse diverse meanings backwards that mean also this one also same so first i will change order number to even so when is the order so i deduct yup zero five and then next zero four and then now we are able to divide the right zero two and then zero one and then finally so one two three four five we have two little five but if we do like this uh we got the tle that means we need to make the better so today i'm gonna use bit operation so okay in this case one is the bit operation is one right either like oh the one is one and then five is one two three four five so one zero one in this case okay uh if this one is the uh odd number then is that time we needed to operation right and then if we saw uh one the number over the one is the index that we need that is same as uh the two to operation zero right and then the number of uh the ranks of beat this one represented to use the operation one because if you divide the two minions we can delete one right so why uh the iteration every number of our ones i will check the uh old number one and then i also check the maximum bit because uh in this case if we needed to divide the multiply two one and then this one deleted this one left next so we need the this region why we need the maximum bit so in this case okay let's check the number of one so this is three and then maximum bit is the three right three and then we need to one more thing that is okay let's see this one actually we started the general flow we don't need to count zero but in this case the zero also start point also include so we need to deduct one so finally number is the five same as this one does this make sense okay let's implement the code first we need the counter to check the one and then we need the next bit is zero then i will get number in nums and then i need to count the correct number why n is zero if the y n is not zero i will add counter if n is gold i will add one and i will increase the pitch one and then i will shift n one so after first is the second and then which is the three right so now i save the max bit is maximum speed with the so if which is the bigger than free speech this will be updated and then finally i will return count plus max b minus itself and then there is one each case okay let's check if num is zero what is return okay in this case count zero max b zero so n is zero and then a bit is zero while this one is skip because this is zero right did that so this routine is did not execute so max width is the zero right so zero plus zero minus one is little minus one but actually we need the zero right so we will uh do h case handling okay looks good let's check complexity time complexity is this one linear this one is a number of n and then each end we need to use uh the of each number so okay let's say uh-huh mom's uh-huh mom's uh-huh mom's number or pitch of each number each item norms if that is n we can say that this one is linear time right and then space is uh but normally uh let's call the uh call and is a number of nums and then m is uh number of bit then we can say we go and then does it make sense but i think this one is still linear and the space complexity is constant because we do not use any uh data structure so linear time with constant space thank you
|
Minimum Numbers of Function Calls to Make Target Array
|
course-schedule-iv
|
You are given an integer array `nums`. You have an integer array `arr` of the same length with all values set to `0` initially. You also have the following `modify` function:
You want to use the modify function to covert `arr` to `nums` using the minimum number of calls.
Return _the minimum number of function calls to make_ `nums` _from_ `arr`.
The test cases are generated so that the answer fits in a **32-bit** signed integer.
**Example 1:**
**Input:** nums = \[1,5\]
**Output:** 5
**Explanation:** Increment by 1 (second element): \[0, 0\] to get \[0, 1\] (1 operation).
Double all the elements: \[0, 1\] -> \[0, 2\] -> \[0, 4\] (2 operations).
Increment by 1 (both elements) \[0, 4\] -> \[1, 4\] -> **\[1, 5\]** (2 operations).
Total of operations: 1 + 2 + 2 = 5.
**Example 2:**
**Input:** nums = \[2,2\]
**Output:** 3
**Explanation:** Increment by 1 (both elements) \[0, 0\] -> \[0, 1\] -> \[1, 1\] (2 operations).
Double all the elements: \[1, 1\] -> **\[2, 2\]** (1 operation).
Total of operations: 2 + 1 = 3.
**Example 3:**
**Input:** nums = \[4,2,5\]
**Output:** 6
**Explanation:** (initial)\[0,0,0\] -> \[1,0,0\] -> \[1,0,1\] -> \[2,0,2\] -> \[2,1,2\] -> \[4,2,4\] -> **\[4,2,5\]**(nums).
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
|
Imagine if the courses are nodes of a graph. We need to build an array isReachable[i][j]. Start a bfs from each course i and assign for each course j you visit isReachable[i][j] = True. Answer the queries from the isReachable array.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
| null |
1,261 |
Hello Hi Friends Welcome Back Today We Are Going To Solid Problem 12615 Elements In Contaminated Binary Tree Before Will Look Into The Details Of The Problem And Some Examples Of Just Want To Mention That My Channel Focuses On Helping People Were Preparing For Java Coding Interview And Telephonic Interview Sun My Channel Health Over 200 Solved Problems as Prime Minister in Companies Like Amazon Google Facebook Microsoft Yahoo and Lots of Other Companies and Friends Kal State of Institutes Are Different Varieties of Problems Which Is Dynamic Programming Click Problems Related Interview Questions for Binary Search Tree Is Graph Benefits Matrix Related Problems in Optimization Problems Logical 20 Problems Social Media Problems to Cover Which Were Like Important from the Perspective of Good Interview Please subscribe to the Channel So You Know You Can Watch the Practice Dost Videos Delhi Definitely Helpful in Your Job Interview Preparation for Please subscribe The Channel So Let's Go and Its Practical Look at the Description Sukoon Final Tree with Following Rules Route 1200 of Tree Not Well Being Recorded and Not Left It is Not Nalbandian Note Loot Value Request Two in Two X Plus One Entry Not Believe In This Entry Notes Right Value Is Not Done It Is Equal To * Right Value Is Not Done It Is Equal To * Right Value Is Not Done It Is Equal To * Express To Election The Final Tricks Contaminated With Means The Best All The Notes Values Have Enhanced To Minus One Notes Values Have Enhanced To Minus One Notes Values Have Enhanced To Minus One Implement Five Elements Class True That Point Elements Of Train No Truth Initial Aaj Dhobi Tweet Contaminated spinal tree and rear seat and junior fine target returns through war target follows existing recovered final tree is on So common man has given his flop example so let's take this second example and clear shot in the first understand your word problems and you will like To Go Into How They Are Going To Solve This Problem Solve The Worst Thing Is The Way They've Been Given A Contaminated By Doing Right For This Is America Contaminated By The Distinct Where All The Value Is In The Chest - Good Night So They've To Value Is In The Chest - Good Night So They've To Value Is In The Chest - Good Night So They've To First Recover This Binary Tree Way Daru 1200 And Always The Value Of The Lift Note Is Equal To Two * X2 * Ten Light Equal To Two * X2 * Ten Light Types of two index plus two so that you can see sovu use this alarm formula reddy123 quarter final trick saunf example will start with hero and will go on and sacrifice on this day will calculate to in 2051 should change its value 218 will go to right end Viewers Activities And Tried Not Exist And Will Calculate This Twenty-20 Plus To Again Will Calculate This Twenty-20 Plus To Again Will Calculate This Twenty-20 Plus To Again And Again For Beauty Recursively Using Different Sau Use Defense For This Soil Recursively Ghost There Left And Right Part Of Every Month And They Never Dare Is Not With The Template The Correct Values In this two for adulteration is given to fight for example again will go to laptop 102 into one plus one right to main stud plus one is equal to 300 year two into one plus two is just two plus two record 2008 clear if and don't have any Look right hind this case will return basically clearance hui don't have any electronic chalu india select described in the difficulties and 2016 use this on formula you will first recover the tree and after that is the trees recovered and let's you want to find out its value for RENT IN HISTORY DAY WILL GO ON AGAIN LAKE DEFICIENT LIGHT ON THIS LIKE IT WILL GO ON LEFT SIDE RIGHT SIDE AND AGAIN LEFT SIDE AND RIGHT SIDE UNTIL THEY GET THE VALUE FOR RIGHT LEFT TO FIND THE VALUE FOR WINTER'S RETURN IT'S GOOD TO RETURN - GOOD Night in that case RETURN - GOOD Night in that case RETURN - GOOD Night in that case how have hello how to prevent it's true or false on its return from say find the value will return to right som that is the problem is so common let's look into the you know implementation and also one of the example set The same time fennel worst thing is fine element method this will help to implement solution is given to solve in just create ₹1 are outside and just finished and lives through their ₹1 are outside and just finished and lives through their ₹1 are outside and just finished and lives through their plait and inventors are responsible so start please read this website and use this President 234 Have to come tight from this point because he will just make fruit drinks 120 years and will apply Davis on Road Trick 16 and definition workshop acid the best condition in routine Arvind Written test for example in this case right left and right in the left And right in third year also left parties also give its written all in this case otherwise and will check cafe appointed left side left mode one day will calculate the value of lift notification to impress plus one you for not existing for the current month will calculate The value of root means after * calculate The value of root means after * calculate The value of root means after * express to right hand side to the not right now and left note basically after going to that again applied defense right for example to clear calculated to sandwich value hit go to right assigned as well S after 30 done will again pipeline 120 to side 67100 remaining part battery basically fight for two years will pass through water left there deficit function and definition of course you have to keep doing in the left and right but also right the short way we are doing And this is the best condition for receiving function right way and rooted in the return of bus route for every attracted function is Himmat hai that selling condition is right otherwise that every to come out of the question read 100 grams of pure tips given this function After death we have to find right Sudhir values will be given to us and will have to find Sudhir values will be given to us and will have to find Sudhir values will be given to us and will have to find life for example in discuss define 143 and favorite so you can check it what is there free this time is not the types of in case of a woman Return Forms Bichha Spywares Not Arrive So You Will Serve At The 5th Return True For Them Were Written True And Five Return For Class Five Days Not Exist In Distinct Crossroads Anxious Am Going To Implement Find A Repulsive Functions Over 250 Roots Of The Tree And Target Validate where looking for and reduce ignorance our best condition for find function solid waste condition of corruption sorry for editing note the novels written for all sites for example hui us ninth loot have not found in node for example indicator for your right way Never Have Read Channel Lotus Which Means That They Did n't Find Any Are Not With Values Will Return Form Otherwise Away In First Checked The Values Will Return Form Otherwise Away In First Checked The Values Will Return Form Otherwise Away In First Checked The Roof Badkar Andher Looking And Give It Is Equal To Target Value Will Return To Otherwise You Have To Check On Left And Right Side effect for example Looked into this till 1950 120 r point use and foreign cigarette government whenever you find any true even just returned to find a specific taking so pranam created with example of whole life in notes total starting from tuesday atul ko 214 basically white and make of this is the example that to for the Unit Test's Journey From Dar Examples Pair Hui He This All of Fifteen Notes Thoughts Like This Is The Contaminated With Minor Gangraped Tea Spoon Basically Member Contaminated Tricked Thing - We Fight With All Of The Fifteen Tricked Thing - We Fight With All Of The Fifteen Tricked Thing - We Fight With All Of The Fifteen Notes And Destroys Recover Deleted This Is The Receiver Tree From zero 12345 600 software co * search for words 312 600 software co * search for words 312 600 software co * search for words 312 or district so they can see but one is the white day 320 shyamsundar right 54200 10:30 is that 1012 is dahez dare but 50 is 10:30 is that 1012 is dahez dare but 50 is 10:30 is that 1012 is dahez dare but 50 is not refrain is not a sorry waste is not also in The Case Which Platform Slide Flats Previous Castor Status The Soldiers Who Can See A True And False Request Does Not Dare In Every Country So If You Want To Just One More Like A Modified And Modified Like Share 0 Corporate In Front And Commerce Paint Maths Bigger Testis 910 You Can See Here Have Values And Till Fourteen But After Back To Values And Till Fourteen But After Back To Values And Till Fourteen But After Back To You Will Get 1528 So Let's Get And Tried This Out In A Successful 300 Cr Actually Adding To More For Information Right To Have To And Clear Concepts Of Attempts To Work On Me Aa Previous Song 12345 67 Points 12345 6 And Have Two And One More Point Par Luti 1287 Points 100 Hai To Aise U Can See Sui Get All The True Until Death Routine Are Also Learned In This Court In Its 12345 Foreign 12345 Se Zone Traffickers Drink Hot and Spirits No One and a Half Hundred Were Getting Correct Results Let's Go Ahead and Learn Overall These Test Cases and You Have Given Us and Miss You Everything Was and Will Submit Our Solution is A So That You Can See You Are Getting Correct Results for All the test cases so let's question time this 200g port God accepted by list code for a perfect so this is the way you can implement final moments in contaminated by doing so views difficult shiv function to first three cover countryside after to you recover saucer and You have implemented for information which gives no reciprocating function show will just check the current note value and it is not equal to the K din Vijay control it left and right side to you will keep checking continuing to and did not indicated in Allah and have to retail Policy Intended SMS You Have A Positive Check The Playlist On My Channel Regarding List Code And Solutions That Is The Playlist Over 200 Problem Sardar Explained With Java Code And Examples Hey Friend Problems And Taken From Last Interview Which Big Companies Like App Open That Facebook Google Microsoft Yahoo 100 Please Go Through That 2000 Like and Very Like and Write Your Problems Including Dynamic Programming Link List String Graph Binary Search Tree for Your Research Benefits Matrix Related Problems Optimization Problems Solved to Important Aa From the Interview Perspective and According Interview Perspective Oil Discovered Yaar Please Check That If You're Just A Ring For Telephonic Interviewers Initial Screening Delay Job Interview Playlist On My Channel And Cover With No Of Oil Frequently S Telephonic Interview Questions Big Companies For Three Days Will Definitely Be Helped You If You Find This Video HELPFUL AND IF YOU LIKE IT PLEASE HIT LIKE AND SUBSCRIBE TO R CHANNEL YOUR SUBSCRIPTION TO THE CHANNEL IS REALLY IMPORTANT FOR US PEOPLE THAT IS THE BEST VIDEO CAN REACH TO MORE PEOPLE WHILE PREPARING FOR FOOD IN INTERVIEWS WAREHOUSE FOR TELEPHONIC JAVA INTERVIEW OR JAB SIMPLY Learning Different Contexts New Concepts of Java Please Subscribe to my Channel and Thanks for Watching the Video on
|
Find Elements in a Contaminated Binary Tree
|
swap-for-longest-repeated-character-substring
|
Given a binary tree with the following rules:
1. `root.val == 0`
2. If `treeNode.val == x` and `treeNode.left != null`, then `treeNode.left.val == 2 * x + 1`
3. If `treeNode.val == x` and `treeNode.right != null`, then `treeNode.right.val == 2 * x + 2`
Now the binary tree is contaminated, which means all `treeNode.val` have been changed to `-1`.
Implement the `FindElements` class:
* `FindElements(TreeNode* root)` Initializes the object with a contaminated binary tree and recovers it.
* `bool find(int target)` Returns `true` if the `target` value exists in the recovered binary tree.
**Example 1:**
**Input**
\[ "FindElements ", "find ", "find "\]
\[\[\[-1,null,-1\]\],\[1\],\[2\]\]
**Output**
\[null,false,true\]
**Explanation**
FindElements findElements = new FindElements(\[-1,null,-1\]);
findElements.find(1); // return False
findElements.find(2); // return True
**Example 2:**
**Input**
\[ "FindElements ", "find ", "find ", "find "\]
\[\[\[-1,-1,-1,-1,-1\]\],\[1\],\[3\],\[5\]\]
**Output**
\[null,true,true,false\]
**Explanation**
FindElements findElements = new FindElements(\[-1,-1,-1,-1,-1\]);
findElements.find(1); // return True
findElements.find(3); // return True
findElements.find(5); // return False
**Example 3:**
**Input**
\[ "FindElements ", "find ", "find ", "find ", "find "\]
\[\[\[-1,null,-1,-1,null,-1\]\],\[2\],\[3\],\[4\],\[5\]\]
**Output**
\[null,true,false,false,true\]
**Explanation**
FindElements findElements = new FindElements(\[-1,null,-1,-1,null,-1\]);
findElements.find(2); // return True
findElements.find(3); // return False
findElements.find(4); // return False
findElements.find(5); // return True
**Constraints:**
* `TreeNode.val == -1`
* The height of the binary tree is less than or equal to `20`
* The total number of nodes is between `[1, 104]`
* Total calls of `find()` is between `[1, 104]`
* `0 <= target <= 106`
|
There are two cases: a block of characters, or two blocks of characters between one different character.
By keeping a run-length encoded version of the string, we can easily check these cases.
|
String,Sliding Window
|
Medium
| null |
1,845 |
hey everybody this is larry this week over q2 of the bi-weekly contest 51 week over q2 of the bi-weekly contest 51 week over q2 of the bi-weekly contest 51 uh seat restoration manager uh hit the like button is a subscriber and join me on discord let me know what you think about this apartment during the contest and so forth so during the contest i will do things a little bit hacky um and here i use sorted list you can actually also use the heap for this and i think heap is probably the way that i would actually do on an interview and if i slow it down or you know like go through it um you know you may take a look and i stopped in about a minute and 40 seconds give or take um so you know i was just trying to solve it as quickly as possible um but in essentia um in essence all you have to do is just have a heap and you put all of you know x from one to n into a heap and then when you reserve you just take the smallest number from the heap and when you unreserve you add the number back into the heap after you're done um that's pretty much it and if you had used heaps then this will take n log n this would take log n and this will oh yeah this will take log n and this will take log n so yeah um that's probably the recommended solution so the list does this or at least especially the way that i did it uh it does the same thing but i when i was writing the code i wasn't sure so that's why i kind of used this sorted list because i was like oh wait which way did i have to go um because for me during the contest it means a little bit less to prove but keep in mind that sort of list is going to be slower than heap even though it roughly has the same complexity which is technically not true you look at the step backs but henry via side um yeah use heap that's all i have let me know your solution and yeah uh that's all i have and yeah you can watch me solve it live during the contest next um um uh yeah thanks for watching hit the like button as a subscriber and drama and discord let me know what you think about today's farming contest and so forth and whatever uh i will see you later bye take care of yourself stay good stay healthy and to good mental health bye
|
Seat Reservation Manager
|
largest-submatrix-with-rearrangements
|
Design a system that manages the reservation state of `n` seats that are numbered from `1` to `n`.
Implement the `SeatManager` class:
* `SeatManager(int n)` Initializes a `SeatManager` object that will manage `n` seats numbered from `1` to `n`. All seats are initially available.
* `int reserve()` Fetches the **smallest-numbered** unreserved seat, reserves it, and returns its number.
* `void unreserve(int seatNumber)` Unreserves the seat with the given `seatNumber`.
**Example 1:**
**Input**
\[ "SeatManager ", "reserve ", "reserve ", "unreserve ", "reserve ", "reserve ", "reserve ", "reserve ", "unreserve "\]
\[\[5\], \[\], \[\], \[2\], \[\], \[\], \[\], \[\], \[5\]\]
**Output**
\[null, 1, 2, null, 2, 3, 4, 5, null\]
**Explanation**
SeatManager seatManager = new SeatManager(5); // Initializes a SeatManager with 5 seats.
seatManager.reserve(); // All seats are available, so return the lowest numbered seat, which is 1.
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.unreserve(2); // Unreserve seat 2, so now the available seats are \[2,3,4,5\].
seatManager.reserve(); // The available seats are \[2,3,4,5\], so return the lowest of them, which is 2.
seatManager.reserve(); // The available seats are \[3,4,5\], so return the lowest of them, which is 3.
seatManager.reserve(); // The available seats are \[4,5\], so return the lowest of them, which is 4.
seatManager.reserve(); // The only available seat is seat 5, so return 5.
seatManager.unreserve(5); // Unreserve seat 5, so now the available seats are \[5\].
**Constraints:**
* `1 <= n <= 105`
* `1 <= seatNumber <= n`
* For each call to `reserve`, it is guaranteed that there will be at least one unreserved seat.
* For each call to `unreserve`, it is guaranteed that `seatNumber` will be reserved.
* At most `105` calls **in total** will be made to `reserve` and `unreserve`.
|
For each column, find the number of consecutive ones ending at each position. For each row, sort the cumulative ones in non-increasing order and "fit" the largest submatrix.
|
Array,Greedy,Sorting,Matrix
|
Medium
|
695
|
23 |
in this video we'll be going over merge case sorted list so you're given an array of k linked lists each linked list is sorted in ascending order merge all of the linked list into one sorted like list and return it so in our first example we have 145 as a first list and then one three four second less and two and six and we're trying to merge into a single list so we get one two three four five six now let's first go over the dot process instead of starting out with k list let's first go over the case where we have to merge two lists in the two lists when we are trying to merge two lists we implemented a two pointer approach one pointer will be in list one and one pointer will be in list two then in each of the iteration we picked the smaller node out of the tool list out of the two pointers to be appended to our resulting list now if we expand this to k-less now if we expand this to k-less now if we expand this to k-less but we expand this to k-less but we expand this to k-less but we expand this to k-less we want to retrieve the node the smallest node out of k-less this means out of k-less this means out of k-less this means we can create a min heap to keep track of our nodes this will allow us to quickly retrieve the minimum node to be appended to our resulting string to our resulting list now let's go over pseudocode we'll first create a min heap which is a priority queue in java to keep track of the heads of our linked list we're going to iterate through the list so we're going to denote it as list this is the input list if list is not equal to no that means it's a valid list so i'm going to add lists to min heap now we're going to start creating our resulting list so we're going to create the following variables first is the head is the sentinel head of the resulting list and tail is the sentinel tail of the list of the result list so it's going to be initially equal to the head so while min heap is not empty we're going to pull a node from inhibit now we want to append node to our resulting list so we're going to set tail.next to node so we're going to set tail.next to node so we're going to set tail.next to node and set tail to node now if node.next it's not equal to null now if node.next it's not equal to null now if node.next it's not equal to null that means we still have elements inside the current list so i'm going to add node.next node.next node.next to the min heap then we can return head dot next which is the resulting head of the list now let's go over the time space complexity so for the time complexity is first we got to create our minimum heap min heap so it's going to be k log k because this k less and then when we operate inside the heap with k elements it's going to be log of k then plus of n log k because we want to process all of the nodes inside the heap to be appended to our resulting list so it's going to be o n log k so where n is the total number of nodes and k is the number of lists so this one is creating the min heap and of n log k is processing all nodes and heat now space complexity is go to off k where k is the number of lists and that's our min heat we do not need to account for our result list because we just modified it the input now uh now let's start writing the code we're going to create our mini first there's a priority queue tree notes or list nodes in heap let's go through we'll say create min heat we'll create a method that generates the mint heat for us and then let's first write out the method we want our nodes to be an ascending order in terms of the value then we're going to iterate the list either way to the list if list is not good to know then we can add it to our heat then we return to heat now we're going to create our two nodes to be our sentinel head and our sentinel tail while min heap is not empty that means we still have notes to process retrieve a node from the heat then we're going to append the node to our current running list then if node.next it's not no that means then if node.next it's not no that means then if node.next it's not no that means we still have nodes to process in the current in this list so we're going to add the next node to our min heap then we can return the resulting list the head of the resulting list now this is the problem you gotta set your head let me know if you have any questions in the comment section below hit like and subscribe if you would like more content that will help you pass the technical interview i upload videos every day and is there any questions or topics that you want to cover let me know in the comment section below
|
Merge k Sorted Lists
|
merge-k-sorted-lists
|
You are given an array of `k` linked-lists `lists`, each linked-list is sorted in ascending order.
_Merge all the linked-lists into one sorted linked-list and return it._
**Example 1:**
**Input:** lists = \[\[1,4,5\],\[1,3,4\],\[2,6\]\]
**Output:** \[1,1,2,3,4,4,5,6\]
**Explanation:** The linked-lists are:
\[
1->4->5,
1->3->4,
2->6
\]
merging them into one sorted list:
1->1->2->3->4->4->5->6
**Example 2:**
**Input:** lists = \[\]
**Output:** \[\]
**Example 3:**
**Input:** lists = \[\[\]\]
**Output:** \[\]
**Constraints:**
* `k == lists.length`
* `0 <= k <= 104`
* `0 <= lists[i].length <= 500`
* `-104 <= lists[i][j] <= 104`
* `lists[i]` is sorted in **ascending order**.
* The sum of `lists[i].length` will not exceed `104`.
| null |
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
|
Hard
|
21,264
|
347 |
Half a minute Spencer will be the chairman of the commission. He said that now we will solve good nutrition. Till now we have done all sparingly here comes at present president. How to delete all 10 inches right. We had asked the question in the last. I am assuming this. After all, we have to see the settings of the country, what will happen if this suddenly drips from the middle, who is behind me with the clear concept behind me because our crows will be in a bad condition, how did this happen, I will request you to please give me half an hour for a short time. Watch for a day or two. If you want to do many more dead games on the occasion of destroying the country, then it is fine and I assure you, if you have faith then watch any playlist or video in the comment section. I have understood, okay, now if you are Amazon, then like every time, whenever they see any problem, whenever they watch any video, then pause this video, read the questions, attend and without any tender, Look reduce, this one did not learn Bigg Boss, if you do powder and letters, it is very beneficial for you, if you ask, you must have tested yourself, not from you, that ticket, the question is the factor of time, the question is on the top frequent elements, the question is very simple, basically, where is the crop from? That sending the top frequent element, frequent means that I am talking about the sequence, so here I have given you the number address, given two equal to the contract, which is the most frequent element in this, what is the total laptop elements, we have printed it. Tell me, if I make a frequency counter table of this, then once is coming thrice, which is you, once, the last one is 2828 and making this is frequency countable. If I tell it, frequency countable fact, now in this, whose is the most reference? The free leg is break point, the currency value of the option is 354, then 241 will be printed, if I make it soft, then it will start, then it will be in the Doctor of Already and will be done accordingly. The party rate of this account is the highest, it will print one and then two. It has two front totals, let us play the top albums, Google, here is S2, I will request you to erase it twice, pause the video, set it to something, one thing how to do it, you get to know the content from little by little points. It does not happen that you already know everything and updates. Solve which question and you will understand it. If I am soft and table no. 21 has come, how many times two and two have come, two and three have come, one and two. Three and four has come exile ticket so total is 22 43718 and sitting here in Delhi is done if I sort it according to it if I do soft then it will come before thrill bar 2002 2851 more mode resorts recording development frequency coding and we click here It has to be said that its frequency is more, it is talking about the top element, every three is the top three elements, here this is correct, hence the answer is why two and three can now be printed in any order. In this, the question is for the illiterate people. It is written that you can print it in any wards, there is no problem, what can be its solution in real life, if you can think about possible things, then you will know one thing, making this table is very easy for us, unwanted map districts, own map and Saturn. This mapping is not understandable. Keep the playlist of Hai Singh big till now. So you can say that it is more craft. So that playlist is so good in destiny that after reading Hai Singh, I am like share comment. You should try and see that you will get pumped a lot, most of it will go, you will start getting a lot of questions from you. 288 is a very important topic, so we can create it through the unwanted app, okay, it is possible, now brother, how to do the shot according to this. Now we have to return to the office, friend, we are the only ones who are studying, so Abhishek must be hiding somewhere, what can we do, like if you have three, if this is 3241, if we basically have to shift, who is from the third topper or 241 more? Do the settings element and print it. We used to give 321 from Chittor. So we point out the top element as to what is the largest at the top. Now we put it as if 3210 was made from Pisces and Aries. Earlier Vaishnav used it. And we think that if we pop it outside then it will spread only the points. Freedom will come to right here, but this is the account, brother, okay, we need the element, so somewhere we will have to store that which is the account and those values. What happens in the next test match is that there is a value relationship, the account is there, it is the value here, okay, we are able to express the beginning and not through the value, that it is able to access, it is possible, it is not possible, so basic. Don't ask, it is going on, you will know as long as you will point through one, what is the amount of life, then one's account is drowned, contact two can point that if someone's time is inexhaustible, then its element is cut, mapping is not stored with us. Right now, this account is as it is, if this point is cleared, then the balance of this account will have to be carried forward. Besides, its color is coming, you can tweet like this about it, what else brother, Jasmine is of hip size. These people did not see the last letter. The biggest mistake is if you see the real life style tips. Message the playlist. Give it half an hour a day for two days. This is a very special thing to boost your confidence. You will come to know about it and it will always help you. That will go past and please see my method of increasing the capacity. Okay, now we have asked for the size, whereas we used to maintain the minutes as we asked all the questions, so this mini of 123 has been completed and the size is here. If there are equal two then it will pop till after doing side effect, if you top one, then whatever is left, two and three against, these two elements have been rang and the element of both of them which is there, print it, if this is an account, then tube is an account, what is this element? So we will do two fronts and trend counter one in daddy's water set and this, we will get the answer, but brother, where is the mapping, there should be mapping, only then I will be able to do something, do n't give any reaction in this, what fear of death, we will do this. For this, we will use a pair, okay, now we will grease the back and add inches to the pair inside this chip, okay, if it is logical, think of one thing and tell me, okay, it only works, it will pause itself, I am according to you, we People will declare and whatever is the minimum limit for stop, it is okay and whatever is the maximum, we will put it as top, we will create it in tower send and how is the minimum and maximum decided from the account, so whatever element we will put in the pair is okay, dress power dress is okay. If so, which element will it be the account and will it be how many people could think of it in the districts and tell by commenting that you would also like it. I felt that yes, the child understands, the child is able to understand how you eggs. Will you have any problem, I am doing it for you, okay, this is a very important question, I have served many companies, okay, so what do we do, because of the minute, I made it, brother, I find it easy to make, so if I make a mini of this, I will make it of this. Let me press it here, Ritesh, even if you don't want to do it here, it's okay, so first we will get this award in food, first this award has not been made, it's okay, if we get it first, if we become a destination, then the first input will come, three less age, this I have made it ok then the second one is in true that two commando is ok so two is Coimbatore so to-do here is ok so two is Coimbatore so to-do here is ok so two is Coimbatore so to-do here is small and three is big so two is command2 remember the first one is telling the account and then we will interlink it text 351 to 9483 on mobile 3121 There is an account here which we are in the border deciding factor which will be in interest, so it is small here, okay, and you are big here, so we are bigger than the one, so do n't let the forest of jewels which have just been made, okay. Road to Commando Nov 3 Komal, how many people understood that he was the most important star? It is most important that Bigg Boss understood those people who watched the last episode. If you guys, I have not seen the last section, then it is a little. There will be difficulty in understanding, for which it is made by the media itself. Okay, this was the minimum deciding factor. This was the deciding factor and I decide this. Have you understood how it is unmuting? That size here became 3, that size here. You will be free by doing the website, now you will do a pot, then it is typed, if it is top, then what is left, you are amazing, two and three third hour, now what we will print is now one by one, now which is equal to this second, it has become its element, now give us this. Till now, the stomach was wanted to be the largest, that they wanted to have the largest element of the cigarette top, that there should be only facial limit, here the top is asking the rate, so while maintaining the size of us and I, let's test it, we will top it, and we will add this boiled peas to it. You get it printed, pop it quickly, make it social, do this anchor source code, do it, you understand a lot, don't take tension, try the jewelery option, but before that, let us understand how to fill the skin treatment, how will we make it, how to make it? With select Friday in Twitter and Greater Noida Correspondent Update, here you will replace these with paired interest. Okay, this will also replace this and this one will replace this thing. Got it, we change the second data type with where people use an integral. Do minutes, everyone type, you earrings are different is the homework for you, this homework is this, when sure Kareena, move ahead without this age, do this homework, Khusro, then wow, on turning on the recording, the court problem is working, the code is complete. Write it down friend, if you do n't understand anything then complete it by commenting that brother, how did this thing come from where did it come from, I would rather give you a playlist, I will tell you that before this I will understand much better than you, okay now disable it or spoil it, a lot of new There is a way to code which you come to know when you see someone else then Laxman Mata ke desirous hai hua tha by hamara hum hamara border banna to un order came up with the intention that and comment it and economic review maths for all to x Let's pick each element and add it like sum map of Now this will pass everywhere such a data factor and this and greater so this is a's paste president and where painted notification we have taken the ribbon is visible a little bit start what is our job to print further that now reinforces each and every element. If it works then for all toe These maps are each element, this map is a pair of Hakimo's value, so the value which we are putting in second, will not become a side effect in it, now it is simple, now look, now we have to maintain the size, so 6 Next Raw Grater It comes to the mind that so 6 Next Raw Grater It comes to the mind that so 6 Next Raw Grater It comes to the mind that what will we do with this, we will turn off the fit hotspot, social is fine, not what to do, only this case will be saved, issue it and will top it and print the body oil usage of the juice that is sent. Also there is constipation value, we have element sajj jhale which frequency is most correct then simple swirl not speak u dot mp tri till it is not done what will we do till a pair banaye pe stuck mint type 100 school put PQ dot top ko Will put and cut it OK WhatsApp social and director create here vector minute at government door transfer to Karnataka and return here when return answer end answer dot push back half a minute gone on time don't see the second date By submitting that answer to the office, if there is a tractor skirt, then , therefore, if you tractor skirt, then , therefore, if you tractor skirt, then , therefore, if you keep the foot in the pushkar, then post it on some time, people are there, you are sorry, E M 1 and foot 9 are discounted, you have to see the loot, sorry for, it will not come here, will you get one, what. He is making mistakes and I submit and let's see if it was added now, I want it, okay, so now you can ask a question like this, I was going to tell you that this repair is written again and again, it means you can use macro, okay. So here we have cut it and here we dip the type tight [ __ ], so tell us the dip the type tight [ __ ], so tell us the dip the type tight [ __ ], so tell us the type is difficult and fair, the name API is fine, short hand is not a problem and here we will replace it with piss. Chief will now replace it with beating. Friends, you can tie anything, voluptuous, I did not want to write such a big thing, what does Micromax say that you can replace the piece, okay, this pear will only replace the piece, if you keep submitting and like this website, then this In this way the problem is put, only the problem is understood, look, I have solved the problem in the court, now its judgment is in front of you, but while doing it, the seat should know less set, you should tell the method, you should know how to code. And if you understand then the next video is really good, please tell by commenting, liking it, if it is bad, then decide, share it with your friends, maybe I am Richa but the reason has increased, okay then see you. Run Trouble Next
|
Top K Frequent Elements
|
top-k-frequent-elements
|
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[1,1,1,2,2,3\], k = 2
**Output:** \[1,2\]
**Example 2:**
**Input:** nums = \[1\], k = 1
**Output:** \[1\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
* `k` is in the range `[1, the number of unique elements in the array]`.
* It is **guaranteed** that the answer is **unique**.
**Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
| null |
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
|
Medium
|
192,215,451,659,692,1014,1919
|
1,937 |
hey guys uh in this video we can discuss decode one three one nine three seven the maximum number of points we can collect with the cost so basically for this program we're going to be given a greater points and uh we're gonna start from the first row and the correct one uh select one cell and then move to the second row select another cell to collect the points however there will be a cost when we are selecting cells so basically the cost will be the column the number of columns we move so for example let's say uh example one so let's say we want to maximize the points we collected so we for first row we collected the cell three and then for second Arrow we call cell five however there will be a cost of one because we move uh by one column when we are moving uh a row one to row two so there will be a cost of one because we moved one column and then from row two to row three we moved by another column from five to three so there will be a total cost of two columns so then uh the total points we can have is will be eleven minus two will be 9. so basically a for this problem we're gonna use a dynamic programming for that so and we're gonna we need we can move either like to the left or to the right when we are moving uh columns right so we can um uh use a dynamic programming and listen to check like both directions or moves to see uh how to maximize the cost maximizer uh points we can collect so let's um start by uh with this example so let's say the input will be the same as this one example one so either we initialize the DP grid by one two three as well because um so the first DP row will be the same as the input row because this is like the one to three points we can connect and then the DP array will be one two three all right now then let's go to the second row so for a second which cell we're gonna which first of all like how much cost we can get by selecting the different uh sales in the second row so because the cost will be um the course will be like the number of columns we move so let's say like if we move from left to right and uh like if you like we move from left to right and let's see how many uh how many new uh how many uh points we can get from the first row so give me a second so let me just say one two three right so if we move from left to right so let me see so here like the initial if we like move from this cell right we only consider direction from left to right then this cell will still have a value of one and for the second cell copy of the previous cell minus one and the maximum of the current sale like moving downwards there will be no cost plus uh under the against the previous cell minus one so the liquidity let me just write it down for the it will be the max of key a plug and the ppj minus one a minus one the previous cell and the minus one so this will be maximum of zero and two so it will be still two and this one would be the maximum of two minus one and that's three so which will be three all right so this is how we do it uh left to right and for right to left it'll be similar so initially let's set it to one two three as well so now we can start from the uh left leftmost position which will be three right so the second so this position will be the value for this position would be um it will be the same so the max of EP G against uh DP uh J plus one minus one okay plus the next column and the minus one because it will be a course of one so it would be maximum uh two and then three minus one which is still two and here it will be the same so the it will be the maximum of uh one against two minus one so it will be still one all right so now this is the values you can get right and how to redefine the DP value so DP value will be uh for this cell right it will be the value of this cell plus the maximum of this one and this one either move from left to right or left right to left so let me just also write it up here so it will be the maximum of um we could of okay that's F2 right J and the right to left okay give me more space and see how it goes all right and uh okay so now so this one will be 1 plus maximum one and one so it will be two this would be five plus uh maximum two of two so two will be seven and then this will be um on plus maximum three of three is which will be four all right so now let's do the circle so now we can calculate two seven four right four left to right and the right to left so for the first one it will be the maximum of it will still be 2 right it doesn't move and then for this one it'll be the maximum of seven against uh two minus one so two minus seven against a two minus one right which will be seven and then this one will be uh four against uh seven oh minus one so which will be six here we this one four were on change and then here will be again seven against the four minus one which will be seven and here it will be um uh sorry uh two against um seven minus one which will be six all right so now the new value here will be three Plus maximum of two and the six so which would be nine and then the value here would be one plus the maximum of seven and seven which will be eight and then here will be one plus maximum of six and the four which will be seven all right so this is the last row of lasted Row for the DP we can get and then what we need to return is just return the maximum of the last row which is nine so that's what we need to return okay so basically this is the algorithm we're going to use and then let's try to uh code it out so let me just uh minimize that so let's see how it goes okay so now we need to get to the size of the grid first rows were equal to the length of the points now we just initialize the pp array and look through the um let's see let's uh initialize the first row to the same of the same as the first row in the points of columns word two let's go let's majorize the temporary to the arrow uh for every Row in the range all right so this is a DP array it'd be great sorry and then we initialize the DP the first row in the DP grid to be the same as the points right so four value in enumerate the points that's the row of the point just initialize there sorry zero all right so we initialize the PPT grid now we just look through the uh starting from the second row to look through the um grid the points grid so 4 I mean range so the second row two number of rows so foreign left to right and then right to left uh yeah left to right and the right to left so uh left to right equal to the same yeah let's just let me go copy on that and the right to left is the same now we just need to calculate to the left to right and to left so four J in range columns so that's the first item doesn't change when we do the left to right so um left to right would be uh max out DP to this one right sorry so left to right a equals to the maximum of this one to this yep now we need to do the same for the right to left we're gonna just Loop uh the other direction um we're gonna skip the last column so it should be -2 yeah -2 yeah -2 yeah so right to left actually now we need to take to calculate the PG array uh yeah it should be the this one I made a mistake here it shouldn't look so it should be the same for J in the range uh this one should be columns because we need to take a starting calculating the first cell so the dpij row the column equals to the points i g that's the maximum of the right and then lastly we can just need to return a maximum of the BP raster Row in VP see how it goes it looks good all right so uh yeah so this is the uh basically the algorithm we cannot use so a DP approach and that the time and space would be both would be a N squared so like the size of the grid so yeah this is the end of the video and I'll see you guys in the next one
|
Maximum Number of Points with Cost
|
maximize-the-beauty-of-the-garden
|
You are given an `m x n` integer matrix `points` (**0-indexed**). Starting with `0` points, you want to **maximize** the number of points you can get from the matrix.
To gain points, you must pick one cell in **each row**. Picking the cell at coordinates `(r, c)` will **add** `points[r][c]` to your score.
However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows `r` and `r + 1` (where `0 <= r < m - 1`), picking cells at coordinates `(r, c1)` and `(r + 1, c2)` will **subtract** `abs(c1 - c2)` from your score.
Return _the **maximum** number of points you can achieve_.
`abs(x)` is defined as:
* `x` for `x >= 0`.
* `-x` for `x < 0`.
**Example 1:**
**Input:** points = \[\[1,2,3\],\[1,5,1\],\[3,1,1\]\]
**Output:** 9
**Explanation:**
The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).
You add 3 + 5 + 3 = 11 to your score.
However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.
Your final score is 11 - 2 = 9.
**Example 2:**
**Input:** points = \[\[1,5\],\[2,3\],\[4,2\]\]
**Output:** 11
**Explanation:**
The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).
You add 5 + 3 + 4 = 12 to your score.
However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.
Your final score is 12 - 1 = 11.
**Constraints:**
* `m == points.length`
* `n == points[r].length`
* `1 <= m, n <= 105`
* `1 <= m * n <= 105`
* `0 <= points[r][c] <= 105`
|
Consider every possible beauty and its first and last index in flowers. Remove all flowers with negative beauties within those indices.
|
Array,Greedy,Prefix Sum
|
Hard
| null |
332 |
hey everybody so today's question is reconstruct a denarii so in this we have given some list of tickets in those tickets we have given the two airports that have our pair of departure and arrival Airport so what we have to do is we have to find the final route that we can take starting from JFK Airport so that we can go to all the airports and there are some routes like they said if there are multiple routes then please give the route that have smaller lexical order also they have said that there will be always at least one valid attorney which means that we don't have to check if it is valid or not because it will always be valid so for example we have at input like this so this means from the airport em you see we can go to lhr from JFK we can go to em you see from SFO we can go to SJC and from lhr we can go to SFO that are starting destination should be JFK so starting from JFK we will see that vertical it is where we can go we see that there is only one possibility that we can go to em you see so we will go to a music then going to an aspherical see from there but are the possibilities then of moving forward DC that we can go to LH are only so we will go to LH r then we will see that what are the possibilities from there to move forward from LH are we can only go to SFO so we will go to SFO then from SFO we will see where we can go that we can only go to SJC so we will go to as DC and we got ad output so we got the final list as we can firstly go to JFK then mu C then alecha then SFO and then SJC so also there was written that it should win lexical orange so what does this means that if from an airport we have multiple options so we should choose the one that will come first in lexical order for example from lhr if we have to move forward and if we have these two options like a muesli and a sepal so we know in lexical order we will get em you see first so we will take em you see so talking about how can we implement this question we can pretty much implemented the way we have seen it so how so we can form a graph in which we can store the first Airport as the key and their final destinations as the value so that we can easily check from which airport but are the possible ways we can go up but at the possible ways we can move forward then iterating over all the airports like using the FS we can easily check so let's see is implementation so what our first step should be so our first step should be to form a graph in which we have starting airports as the key and the possible next destinations as at will so I have formed a function in which I have taken input list off list in which we have strings as tickets and firstly I have formed the graph then and graph this lines means that the keys are the first starting positions and I have appended the final destination in it then they are sorting all the final destinations in aircraft but in reverse order so why are we sorting it and why are we sorting in it in reverse order so we know that if we have many answers the we have to give the answer in lexical order so how can we do that so to achieve that we are sorting it but we are sorting it reverse because we know that in a list then we want to remove an element from the last it is o 1 but from the first it is an operation so that's why we're sorting it and reverse order so that we get our value with minimum number of operations so our last element will be the most preferable choice because it is sorted then I have taken a stack and given it value JFK there's a starting value because they have given that we have to start from JFK in this stack but I will take this I will keep the note of where I am at the current position so for example I am at JFK so from this tag I know that I am at JFK so I can easily check that what are the next possibilities of destination where I can go from the current value and the rest list is unreserved so as we got a fixed value we will append it in our result list so what I am doing is I am taking the last value of the stack seeing its all possibilities as the graph of stack minus 1 are all the values that now we can go possibly and then removing at this value from the stack because we have moved on it then whenever we will get that there are no ways to move forward from a particular airport we will amend it in our result so the first thing that will get a pen in our result will be the last answer means the ending point of our group because in the starting it is the only point from there we can't go any further but as we will reach there we will remove it by popping and then but we will append in our result will be the last second and the last third and that's how we will get our result as the final list and finally we will reverse our result placed and we will give it in the perfect order so these are the steps that we need to follow so that we can perfectly implement our solution so firstly we will form a graph with keys with for starting airport s keys and the destination as its value so that we can easily find the destinations then we will sort all the destination in lexical order then we will take the count that where are we in current position and then we will see from all the next possibilities what are the next possibilities and phone with the help of DFS and whenever we will get to a point where we can't move forward then we know that this is our end result so we will appended in our result and finally we will return our result list in an opposite way so I hope this is clear not try to implement it by yourself this person can also be done by the help of Eulerian path you can find the link to that approach in the description below and thanks for watching and I will see you all in the next one bye
|
Reconstruct Itinerary
|
reconstruct-itinerary
|
You are given a list of airline `tickets` where `tickets[i] = [fromi, toi]` represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.
All of the tickets belong to a man who departs from `"JFK "`, thus, the itinerary must begin with `"JFK "`. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.
* For example, the itinerary `[ "JFK ", "LGA "]` has a smaller lexical order than `[ "JFK ", "LGB "]`.
You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.
**Example 1:**
**Input:** tickets = \[\[ "MUC ", "LHR "\],\[ "JFK ", "MUC "\],\[ "SFO ", "SJC "\],\[ "LHR ", "SFO "\]\]
**Output:** \[ "JFK ", "MUC ", "LHR ", "SFO ", "SJC "\]
**Example 2:**
**Input:** tickets = \[\[ "JFK ", "SFO "\],\[ "JFK ", "ATL "\],\[ "SFO ", "ATL "\],\[ "ATL ", "JFK "\],\[ "ATL ", "SFO "\]\]
**Output:** \[ "JFK ", "ATL ", "JFK ", "SFO ", "ATL ", "SFO "\]
**Explanation:** Another possible reconstruction is \[ "JFK ", "SFO ", "ATL ", "JFK ", "ATL ", "SFO "\] but it is larger in lexical order.
**Constraints:**
* `1 <= tickets.length <= 300`
* `tickets[i].length == 2`
* `fromi.length == 3`
* `toi.length == 3`
* `fromi` and `toi` consist of uppercase English letters.
* `fromi != toi`
| null |
Depth-First Search,Graph,Eulerian Circuit
|
Hard
|
2051,2201
|
202 |
Hello friends, so in today's video, you are going to explain Happy Number, what is the basic happy number, what is the problem, like if someone is giving a number, can this number be called basically any positive, it should be okay and play it when Have to repeat till if he is a servant in the house subscribe 280 in the last for subscribe then basically that work number is two number tell the account statement then he will get stuck if its no yes then tell this happy number please tell the length of Ghrit That 13239 may mean, then the option is copied, so the function is is is that the app is PVS and any one number will come in it, number and end, okay, now what to do, let's change this number with the container for electricity. If we live then we will not be able to change that and this for money, so I have made a copy of it, that's it, okay, now what we have to do, what we have to check is its value, oil, value of these, notification, so we have to subscribe, basically. Maybe again on someone, there can also be a cycle basically that like meaning something is right now after that abe given if it is known like this all means like then it is not a method or a layer of atoms in the form of time if it is being created So this means that sometimes basically if it has been created and went into it, then I searched in it to do it and I decided that hey, I have created it, I have to do it, the number which we will keep searching is the element model in it. Now looking at it seems that Tu Krupa 131 - Sonia has got it seems that Tu Krupa 131 - Sonia has got it seems that Tu Krupa 131 - Sonia has got it installed, if attended number one goes, how much time will it take? If I tell you the problem in this episode, it will take very little time. What does time mean? Max to Max, the four cloves that will last is Mexico. Max will run from 70 to 80. Max is the maximum number. We will take 10-digit key, so for that also such We will take 10-digit key, so for that also such We will take 10-digit key, so for that also such people will be fine, so check here and secondly this is the ladies first number. And if someone controls it then Problem should not be made in not doing, if the content is done then it means that you will search, then searching means that you will be unhappy, so let's go here, I would have thought of it, till then, what do we have to do, as soon as we have entered it, accused. To update 99 updates, subscribe to stop subscribing. Set A came out and who is also going to enter the return. Basically, we will number here, put the gate number inside it and it will be done. Okay, Aditya has posted porn, I have done that. Have done dot up and will make it no-1 Odisha ok yoga as if the one who is no-1 Odisha ok yoga as if the one who is no-1 Odisha ok yoga as if the one who is going to return from here is happy or happy return again value then guys will not be able to do this number now so after doing one number I copied it and the other one Like here, I have taken both to manage the situation and within it, those who make some changes should make 90. So, if the price on the lens is 316 instead of 119 through the pipe, then basically subscribe number is 214. So basically we will keep on counting that means the last one then second last then third last point is placed then basically the account which is last should be 20 then like add numbers then for that number if the value of the number is greater than that if the value of the number falls. Or if there is some meaning, we have to do the exhibition till the same time, like what do we have to do now, look at taking out a reminder, which element is required on this basis, if I put it in tense in this way, if I take out a reminder of it, then the whole thing will be taken out first. And do four and it is complete, whereas the answer will be foreign trip, more six, first this one is gone, we will take out the CO of the next one, we will take out this tree by doing 2864, we will take out 6 in this way, then let's remind pimples, whatever will be the divide of our number. Reminder, if it is 110 or more then what do we have to do now, we just update the value of the person number, submit the value of the number, divide it by tan, then what will happen in the next numbers, Sikh supports, I am following from behind. So one element to follow from behind and I have got the value, so now I have to remove that and this element will come, now I will take the next elements of sex and child or mix element, then the last element. Avoid sex, if the value is going to be okay then let's do it. There will be a rally of the number. There will be a rally, that means six accused divide is going to come, so now we increase, we have to dream, share its square, then do those, sum is equal to two. Plus a reminder, whatever has been removed, become a reminder instrumental. Okay, we have increased the value of time. Reminder instrumental, just do this. Number one has been updated earlier and reminder improvement workers movement number. Now what do we do with this? We have to call a function. This pain Meghna would give the value of this happy phone number to nineteen because it is new to it, so let's see according to it, if it is 90's, it has been there, so two should come, let's see the fasting attitude, how many times has it been called, then before this, we should have got the number printed here. What values have we had to plug in to break down the device of print that n What values have we had to plug in to break down the device of print that n What values have we had to plug in to break down the device of print that n but we have plugged them black 9822 again became the ground so how many times means four-four apart from this here this is functional here four-four apart from this here this is functional here But for the number of times, subscribe for 1080 means if we see any, then for the value of two, more people have run, but maximum, how many times have we run, love, if I remove the sprint statement, this dialogue will be looted, then basically we will know which If we see what values we are getting on how many voters, then two forces are the one after that, it belongs to him, so now we need a number of so many digits, if the color would change, then basically no, after taking such big digits, it looked like 9960. No, if it is less then it is a little 960 basically it is in 13 form if the house husband subscribe 123 456 then if he wants it then subscribe for subscribe then there is a problem by doing this which appointment phone number is happy or not drunk, give condition for them- There are three conditions, give condition for them- There are three conditions, give condition for them- There are three conditions, otherwise if you like the video, please subscribe. See you later.
|
Happy Number
|
happy-number
|
Write an algorithm to determine if a number `n` is happy.
A **happy number** is a number defined by the following process:
* Starting with any positive integer, replace the number by the sum of the squares of its digits.
* Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1.
* Those numbers for which this process **ends in 1** are happy.
Return `true` _if_ `n` _is a happy number, and_ `false` _if not_.
**Example 1:**
**Input:** n = 19
**Output:** true
**Explanation:**
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
**Example 2:**
**Input:** n = 2
**Output:** false
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Hash Table,Math,Two Pointers
|
Easy
|
141,258,263,2076
|
1,887 |
uh in my eye hey everybody this is day 19 of the Leo day challenge hit the like button hit the subscribe on join me on Discord let me know what you think about today's far and also today's VI uh here I am in NOA um yeah just enjoying no uh in this Temple yeah let's get back to the problem yeah uh day let's go hit all the like buttons while this is loading subscribe buttons join me on Discord so we can always chat I'm still here in where am I Osaka so yeah uh just kind of waking up at the crack of Sunrise or even before that but yeah all right today's Farm is 1887 reduction operations to make the away element SE give ener nums your goal is to make all elements in AR in Num equl I cannot read or elements in Num equal complete one operation follow these steps okay find the largest value in nums okay let its index be I and it value be the largest okay pick the smallest I okay find the next largest number and then reduce it to the next largest all right let's take a look what that means strictly smaller than largers yeah that's what I thought okay I that's what I thought but I thought it was a little bit awkward the way they phrase it so I wasn't sure okay so then what was the problem number of operations okay so this is a simulation problem right there's no um there's really no um no uh no decision right that's the what I was looking for meaning that there's no choice you have nothing to do your entire goal for this problem is simulation and then maybe make an optimization and of course if you do this naively meaning if you actually just run a simulation and then you do a loop every time we do this every time well what happens right well the worst case is going to be I think they kind of example three almost that but you're just going to have 1 two 3 four five six seven eight or something like this right do or just when all the numbers are not equal when all the numbers not equal you could always reindex anyway so or renormalized so but so it's about the same idea but then now it goes to 1 2 3 four seven right and then now it takes two moves to kind of do this right so now it takes one move to do this and then two moves to do this and then dot and you kind of see the pattern very quickly that is one plus two plus three moves plus four plus five plus six I don't know if it end at six or seven or eight but uh prob seven so but this effectively if you simulate this one at a time will be n squ right so you want to do slightly better than that or a lot better than that really um and the uh the idea about doing better um yeah you do it in N Square it'll probably be too slow I actually forgot about the N okay yeah the N is 10 5 * 10 about the N okay yeah the N is 10 5 * 10 about the N okay yeah the N is 10 5 * 10 4 so it'll be too slow so how do you optimize this right well in the way that we kind of well one is just try to figure out if you know there's a pattern uh and of course we kind of see the pattern kind of quickly right so then the problem or the tricky part about this one is that you know it's not always going to be just like a simple one the summation from 1 to X or whatever it is um is the idea here is that this is the worst case but a tricky case which is not necessarily the worst case maybe just a lot of you know dupes because then now uh it takes three plus and then six right because now after having after doing three moves you have something like this and then now you have six moves to kind of reduce it all to one right so I mean but and then you kind get the pattern and it's not so bad so I think we can just then just do it um basically do the largest number every time and yeah and there a couple ways you can kind of think about doing it right uh but all of them will require in some form sorting right Maybe not maybe it doesn't have to be n log end sorting maybe I don't know if he works but it's I mean he will work I don't know that it makes it more optimal so uh but yeah but if you sort it'll be okay and then after you sort um maybe even do a reverse is equal to True uh just to sort it in a reverse order right and then now we have uh what's it called operations 0 we return operations right and then now for you can probably combine this in a lot of different ways the way that I would just do it is just for iix in enumerate nums or maybe just like for I in range of n so we know that the first number yeah right um and - one number yeah right um and - one number yeah right um and - one maybe that's a little bit easier depend on how you want to write it exactly really I mean I think one way you can say is that it reduce you can reduce an uh a number but you can also think about it as other previous numbers reducing it to this number right so okay so then now I mean it's going to be one way or the other it's either writing this or this but you know the so basically if num sub I is not equal to num sub I minus one because that means that the numbers are the same there's no reduction then um you reduce all the numbers from zero from numbs Sub Zero to numbers sub I minus one all of them you would change it to numbs of I right so change all numbers from num Sub Zero to num sub ius1 2 nums of I and of course how many operations does that take that takes exactly I operations is it I or I + one exactly I operations is it I or I + one exactly I operations is it I or I + one no it's I operations right from Z to IUS one inclusive they're I numbers and that's pretty much it uh I mean obviously this is uh I mean I think this is one of those problems I mean I say this often at least for lead code right which is that you know you look at the solution and you're like oh okay this is obvious you know but I think I tried to go over all the maybe not super detailed but a good enough detail um on how to kind of come up with it you know specifically cuz I think that's I think one thing that people um especially online on YouTube so whatever um people may make it sound easy and I'm not going to lie I don't think this is hard but when you look at the code you're like oh yeah of course it's easy it's a for loop I think that's a fallacy you have to kind of really go make sure that you understand what you're doing and following each step of the way right um if you understand it of course it's easy you don't understand it then you know maybe not so much even if it is just a for two and a sword right so uh so definitely don't you know figure out what it is that you're missing from that understanding and then try to kind of uh get to it I mean because you know solving this particular problem it's fine right like you know maybe you can't I don't know but for me the way that I want to kind of go over it is not necessarily solving the problem at hand I mean obviously it would be very nice but in a way kind of like um I want to demonstrate more of the thought process I mean I don't always suceed so my for doesn't but I want to demonstrate more of the process so that um you know so that uh what man I cannot Eng today so that you can basically solve similar problems in the future or even more difficult but of a similar nature in the future right anyway that's all I have for today let me know what you think uh stay good stay healthy to good mental health did I do the time I mean I think I did the time I don't think I did actually this is n log n and all n space all of n because I count um I count sorting as ofn because no reasonable API operation should uh should you know take the input and then change it in a weird way I guess not weird way but it's just in any way so I kinded like if I were to actually make this an API I would maybe do something like you know uh this to kind of copy the space over so then when you sort you know it doesn't affect the original data all right anyway that's what I have for today that's what I have for this PR let me know what you think stay good stay healthy to your mental health I'll see you later take care bye-bye today's ice cream weing ice bye-bye today's ice cream weing ice bye-bye today's ice cream weing ice cream yeah hit the like button hit the Subscribe button join me on Discord let me know what you think about you know today's video today's fom what is this loudness going on at 11: p.m. uh I'll loudness going on at 11: p.m. uh I'll loudness going on at 11: p.m. uh I'll see yall soon and take care bye-bye oh see yall soon and take care bye-bye oh see yall soon and take care bye-bye oh yeah stay good stay Healy to mental and yeah I'll see you soon and take care bye-bye what
|
Reduction Operations to Make the Array Elements Equal
|
minimum-degree-of-a-connected-trio-in-a-graph
|
Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps:
1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`.
2. Find the **next largest** value in `nums` **strictly smaller** than `largest`. Let its value be `nextLargest`.
3. Reduce `nums[i]` to `nextLargest`.
Return _the number of operations to make all elements in_ `nums` _equal_.
**Example 1:**
**Input:** nums = \[5,1,3\]
**Output:** 3
**Explanation:** It takes 3 operations to make all elements in nums equal:
1. largest = 5 at index 0. nextLargest = 3. Reduce nums\[0\] to 3. nums = \[3,1,3\].
2. largest = 3 at index 0. nextLargest = 1. Reduce nums\[0\] to 1. nums = \[1,1,3\].
3. largest = 3 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1\].
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** 0
**Explanation:** All elements in nums are already equal.
**Example 3:**
**Input:** nums = \[1,1,2,2,3\]
**Output:** 4
**Explanation:** It takes 4 operations to make all elements in nums equal:
1. largest = 3 at index 4. nextLargest = 2. Reduce nums\[4\] to 2. nums = \[1,1,2,2,2\].
2. largest = 2 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1,2,2\].
3. largest = 2 at index 3. nextLargest = 1. Reduce nums\[3\] to 1. nums = \[1,1,1,1,2\].
4. largest = 2 at index 4. nextLargest = 1. Reduce nums\[4\] to 1. nums = \[1,1,1,1,1\].
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 5 * 104`
|
Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other.
|
Graph
|
Hard
| null |
226 |
Hello friends today I'm going to solve liquid problem number 2 26 invert binary tree so here in this problem we are given the root of a binary tree and we need to invert the tree and return its root so first of all let's see what's a binary tree so binary tree is a tree which has a root node it starts with a root note and then it has two children since it has two children hands binary now there's a property of binary tree that is any value less than the current node is goes towards the left node and any value greater than the current node goes towards the right node so here let's suppose if this is equals to 3 and if we have a value 1 that we need to insert then this one will go towards the left node so it will go here now it's a let's suppose we have a value equals to four the four is greater than 3 so it will go to the right so this is a binary tree now we need to invert this binary tree invert means just the opposite we have the root now towards the left all the values greater than 3 will go towards the left all the values Less Than 3 will go towards the right so 4 will be towards the left and one will be towards the right so this is what inversion of binary tree means now how can we actually solve this problem so let's look at this example here so we are given the root here and now we have the um okay so we have its children so what's happening four we have the root node and then now we have its children two goes towards the right so here it's towards the left here it's going towards the right what about seven eighths here towards the right but it's towards the left here similar is for this sub tree as well in case of two which is the root node they we are just suffering the children right so that's what we are going to do we are going to shuffle these two notes so instead of left it will go towards the right instead of right it will go towards the left and so on with its children and well so that is what we are going to do and since this problem can be divided into sub problem as for four we need to shift 2 towards the right and seven to the left we have to do the same for the children of two as well so it forms a recursive form of solution as this problem can be divided into some problems so using recursion we can actually solve this problem so let's see how we can do that so we are going to use the same function and call it again and again so what we need to do is okay now let's go towards the very end all right so in the very end just a single note here and it doesn't have any children so if it doesn't have any children when we are recursively calling it's one of its children which is null then what should we return we need to return null right because we can no further proceed so if the root itself is null then we cannot proceed any further we are not going to do any more recursion so we just return null if we have the root value then we take the left value okay so let left we take the left root uh left note that is left sub tree and the right sub tree here and now we need to shuffle the left and right to the left we need the right subtree so invert tree and here we are going to pass the right why are we passing the right into a function because we now recursively need to solve all the red left and right sub nodes of this sub tree as well right as in this case while we are shuffling 2 and 7 this whole sub tree and this whole sub tree now we need to shuffle the next its children as well so that's what we are doing here and then similarly for right we are going to do the same thing because we need left towards the left we are putting the right towards the right we are putting the left and this will Shuffle its children as well and finally we are going to return our root after shuffling so that will be our answer okay so one problem here is we are putting root dot right till here it's fine but when we are passing root that left here in this recursive call we have we are actually passing this updated value so we don't want to pass that we want to pass the left node which we had earlier so let's do the same here as well so now let's run our code great let's submit this awesome so here we are able to solve this and it is solved in off and time complexity and talking about the space complexity since we are performing a recursive call which uh takes a stack and the length of a stack can be of n so that is why the space complexity also becomes off and so in this way we can actually solve this problem so let me know in the comments down below what do you think about my solution thank you
|
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 |
1,706 |
hey what's up guys so another question from lead code 75 level 2. so this question basically says yeah that we have a 2d array okay and if my particular cell says that it's of one value of one that means I'm gonna go towards right and if the next cell says that the value is one then I can successfully go to the next column if not and if it says -1 that means I need not and if it says -1 that means I need not and if it says -1 that means I need to go left so this right and left together is going to make the ball stuck cool then another thing is if it's -1 and -1 then another thing is if it's -1 and -1 then another thing is if it's -1 and -1 then we go to what's left like minus one here this one go this one okay sounds good that's the whole question and the question wants us to say that at every row every column has its own value and what would be if I drop this first ball where would it finally exit out of cool so let's directly jump in the code for this one so a recursion seems like a decent method we can just call the DFS right so we have few conditions that we just discussed right now that if next column the current row next column both are equal to one then I can go towards my next row keep in mind you will go towards a next row with the next column so why so this is the most important part of this question so this becomes true then you recourse down with r plus 1 and C plus one keep in mind that both were one then this ball in this column has finally been in this column now so your column value also changed right so this is now in this column that's good perfect so with this condition we also can have an else F that if the previous one is -1 else F that if the previous one is -1 else F that if the previous one is -1 current is minus one we go to the next row and the previous column thanks hands cool we just continuously do this recursion down and once our base case would be that if rho is finally equal to grid.let that means we finally equal to grid.let that means we finally equal to grid.let that means we reached the full complete length perfect then we can just return the column number because we want to put in our list our array that where we came out of from so I just put on C and if not I return minus 1 that means it got stuck now this checkered function is separate from my TSS because you want to check first in this case that if it's only valid then only go do something because if I just implement this checkout function inside my DFS then it would be like DFS this and then it makes it more messy and complicated and it doesn't really work as you would expect it to so that's kind of like something to make our life easier have just another function and basically we just in our mail fine Ball Method just do a for loop with every column and one at EFS and then just return this press so this is more kind of typing question then I guess we're thinking one because you just need to type all this and which is it was super like I did not want it to I'm just super lazy to type all this out but I did so Yep this is the whole question or where will the ball fall and yep that's it cool so the next question probably could be maybe longest common prefix or I don't know multiplies to the strings or something like that all right guys thanks for watching make sure you like And subscribe see you next time
|
Where Will the Ball Fall
|
min-cost-to-connect-all-points
|
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`.
* A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`.
We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box.
Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._
**Example 1:**
**Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\]
**Output:** \[1,-1,-1,-1,-1\]
**Explanation:** This example is shown in the photo.
Ball b0 is dropped at column 0 and falls out of the box at column 1.
Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.
Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.
Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.
Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.
**Example 2:**
**Input:** grid = \[\[-1\]\]
**Output:** \[-1\]
**Explanation:** The ball gets stuck against the left wall.
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\]
**Output:** \[0,1,2,3,4,-1\]
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `grid[i][j]` is `1` or `-1`.
|
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
|
Array,Union Find,Minimum Spanning Tree
|
Medium
|
2287
|
870 |
hello everyone welcome to kurdish camp hope you're all doing great and today we are going to cover advantage shuffle so the input given here is in two integer array a and b and we have to return any permutation of a that maximize its advantage with respect to b so what is the advantage of a with respect to b is that the number of indices i for which a of i is greater than b of i so let's understand this problem with an example here is a given example arrays a and b so let's start checking from 0th index so the 0th index of a is 2 and 0th index of b is 1 so obviously ace value is greater than 1 so the first index is having an advantage moving on to our next index the value is 7 and the value at b is 10 which is actually less than 10 which is not having an advantage moving on to a third index 11 is greater than 4 so this is an advantage thing and last index 15 is greater than 11 which is again an advantage so now this position is not giving us advantage because the value at a is less than value at b so what can we do or which values can we swap to make it work or have advantage in all the indexes so let's shuffle the value 7 and 11 so the array becomes 2 11 7 and 15 so if you check the values now with b 1 10 4 and 11 all the values in a are greater than all the values in b so this is one of the permutation of array a that is completely having advantage over the array b so this is going to be one of the outputs we can return so how are we going to approach this problem so here the idea is not to increase the advantage of all the elements but decrease the loss so how are we going to do it we gonna sort the array a from ascending order so 2 7 11 15 which is actually already sorted so and b in descending order so the values become 11 10 4 and 1 now the idea is to map the higher value in array b with higher value in array a so that we can minimize the overall loss of given array so now if we cannot map these values that is if you consider the value at b it is 11 and if you put the value correspondingly at the index 0 as 15 you will get advantage the same way mapping the next greater value with the next greater value in the array a by doing so we will sort the array or permute the array a in the format that it gives maximum advantage if suppose if the greater value is not greater than the value at array b then in that case map that with the slower value because we can use this maximum value in further or future elements to maximize our advantage if we know we cannot win it then put the smallest value to that and move on to check whether we can achieve advantage by fixing the maximum value for the second largest value so we are going to do this with the help of two pointers so first let's sort our array and have our two pointers slow and fast slow points as the lowest or smallest element and fast points at the higher value in the given array so now we are going to get the help of priority q to store the values of v y priority q because we also need the index of the given element so to store index as well as in descending order we get the help of priority queue so our priority queue will save the elements in such a way that it sorts the element based on the value so now the greater value in array b is 11 it is of at the index 3 so 3 comma 11 will be the first value entered into our priority queue so the next greater element is 10 which is at the index 1 so the next value will be at 1 comma 10 and the next value goes like 2 comma 4 and finally enters 0 comma 1 so now we saved our array b with its index in our priority queue now it's time to check the values and construct our permuted array so let's say our result array is of name result and has length of the size of array so now let's start comparing the first value in p array with the largest value in array a so the first value we are going to compare is 11 which is at index 3 so we are now going to compare the value with the fast pointer because that is the maximum value in the given array so now if you compare 11 and 15 11 is actually greater so if you map 15 for 11 it is going to be an advantage so now our 11 is at index 3 so in our result array 15 is going to get the index 3 so now updating my array with 15 at index 3 moving on to my next value 10 which is at index 1 so now we are going to compare this value with the second largest value so once we have used 15 our first pointer moves to 11 so now we are comparing 10 with 11 so 11 is actually greater value than 10 so it is an advantage so 11 gets the place of index one so now i'm going to update 11 at the index one if suppose my 11 is not greater value than the value at b we are going to assign this lower value because we know we cannot win with the faster value in this index so we assign a slower value and move on to our next greater value to check whether it is a win situation by assigning the larger value to that number hope you are getting it so let's move on to the next number which is 4 at index 2 we are going to compare 4 with the next largest value so once 11 is assigned we are moving our first pointer to 7 which is actually greater than 4 so now 7 gets the place of index 2 so i am going to put 7 at index 2 finally moving my fast pointer to my first value 2 and comparing that with 1 in my priority queue that is the last number at index 0 which is actually greater than 1 so if you assign 2 to correspondingly 1 at that position 0 it is going to win again that is it is going to be an advantage so i am finally updating 2 and the index 0 so this is my result array which actually gives advantage over all the elements in my array b so we are going to return it before getting into code this actually works in big o of n log n where login time is used to save the elements and retry iterate the elements from the priority queue and n is going to iterate our array a and b so let's go to code now let me first initialize my result array and start my array let us initialize our priority queue to store our index of array b and the values in descending order so we wrote the comparator to sort the array in descending order based on the value in the given based on the first index of the value we store in the priority queue so now we are going to iterate our array b and store the value and index in our heap now we have put our index and array b's value to our heap that is our priority cube i'm gonna declare my two pointers low starts at the zeroth index of my array and fast pointer is pointing at the last index of my array a because we sorted it is gonna point at the higher value so now i'm gonna iterate till my heap that is q is empty and take the value at the queue and assign the result array with values that is we are going to compare the value at our q is greater than or equal to the value at the fast pointer so if it is greater than then if the value at b is greater so we cannot win that situation so we are going to assign the value at slow pointer if not we are going to assign the value at fast pointer and move the pointers accordingly so yes now we have computed the values in result array and let's return result and run so yes let's submit yes the solution is accepted and thanks for watching the video if you like the video hit like and subscribe thank you
|
Advantage Shuffle
|
magic-squares-in-grid
|
You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`.
Return _any permutation of_ `nums1` _that maximizes its **advantage** with respect to_ `nums2`.
**Example 1:**
**Input:** nums1 = \[2,7,11,15\], nums2 = \[1,10,4,11\]
**Output:** \[2,11,7,15\]
**Example 2:**
**Input:** nums1 = \[12,24,8,32\], nums2 = \[13,25,32,11\]
**Output:** \[24,32,8,12\]
**Constraints:**
* `1 <= nums1.length <= 105`
* `nums2.length == nums1.length`
* `0 <= nums1[i], nums2[i] <= 109`
| null |
Array,Math,Matrix
|
Medium
|
1311
|
1,569 |
hey everybody this is larry this is me going over weekly contest 204's uh q4 a number of ways to reorder a way to get same bst uh hit the like button to subscribe and join the discord uh this is a tricky prom but a lot of it is because it requires math i don't know if it will be a good interview question um but we'll go over the math as much as we can and some of it will require some knowledge or just maybe some intuition about a binary search tree so okay so the first thing to notice uh around the ordering of insertion is that you know the first number that you insert will always be the root right and from that you could construct a recursive definition of sorts right um and you know that all the numbers that are you know given that you know okay let's say for example this three right given that this is the root you know that everything that the suffix of it um to the suffix of it uh all the numbers bigger than three will be on the right and then all the numbers that's less than three will be on the left um so then so that's how i defined it um so that's how i defined this recursively uh and then how this is for me this is a divide and conquer problem of okay now given that uh what is what does that mean right well what that means is that um and separating the aside one thing that i noticed and some of that just looking at this example is that you have the interleaving um the left and the right you know one two four five um you know that the one has to come before the two and the four has to come up before the five but it doesn't matter which um you know like it could interleave in some way so then for me i just had to come up with the formula and if you know if you have two arrays let's say you have a left array and a right array uh and has some length of uh l and or n sub l let's say and then this is length of n sub r right and that means that you know let's say in a really base case there's l or r uh there's two left and two right and then what are the number of possibilities right well it could be l or l r uh l o and so forth right dot so you know you get the idea um so how many possibilities are there right so this is um a common combinatorical thing um i think it's called stars and bars but yeah so basically this becomes a stars and bars problem uh and let me put up a we keep article here uh so this is a you know this is a link i'll put it somewhere below but basically you could look at either i don't want the l or the r as far and then just separating the stars and but the short answer is this comes out too um the length of left plus length of right this factorial over um length of l factorial uh this times n of r factorial so that's kind of the um uh how you choose this um so that's how you kind of get the formula which i have here uh so that's kind of the point right and then the question is well how many possibilities are there to rearrange one and two uh like and for me this is the left side okay but one and two maybe there's only one way so that's why this is the thing but for a better example um is that you know um recursively so now we're asking about this recursively um and for example this three uh means that five four and six is on the right side right well how many ways are there to do five four and six well five four and six is just any three numbers which is this so you know that there will be uh at least two examples so that's kind of how i did it um because you basically recursively basically the so you're given this as the formula uh so i'm just gonna go a little bit in the formula uh it's a little bit hand wavy uh i urge you to kind of figure out the visualization you need uh but a lot of this problem is just commentarics so if you feel like you need a deeper understanding i would practice more commentarical problems um and just kind of think which to be frank to be honest to be clear uh i don't think it's in scope for an interview uh it's way too hard to be on an interview or not way too hard just require stuff that i wouldn't expect to be on an interview um but divide and conquer is a fun thing so like i think i recommend it in general um but yeah so basically i you know for i look at the first uh the first number and that's the root right and i separated from the left and the right and then for the left how many i you know this is it's similar to dynamic programming but without the um it's similar to dynamic programming in that i have a function that answers a question for me hence recursion right but we don't have to memorize anything because every state is only uh visited once so basically for the numbers that are smaller than it i ask how many ways are there to count the left or the numbers that are smaller than it and then i multiply that by the number of ways to count the things that are bigger than it and then i multiply that by this formula um you know the distorts and boss formula that we talked about and that's kind of basically it and i added some mods to do some maps uh and it worked out um because uh i mean for me if it worked for this number it was good enough and i got it right on the first time except for off by one it's not really enough by one it's more that because you don't count the original um input as one so that's why you would subtract one from it um i did have some concerns about uh this formula uh and this formula because um and i also you could notice that i cached the factorios but i did have um some concerns about this formula because i worried that there will be too many digits and this will be a little bit too slow uh so if you do this in competitive programming um and some people have this pre-written and some people have this pre-written and some people have this pre-written but i don't and maybe i need to figure out how to do it but basically what i was going to say is that i would look up something called the modular inverse uh to solve in the general case and if you do something like code for us uh you're probably going to get challenge and it'll probably get time limited so you definitely want to look at module inverse so that you know this formula becomes basically something like um like instead of this it is this times you know the inverse factorial or i don't know if it's called inverse factorial but the modular inverse of the factorial something like that right um and that will allow you to uh mod on you so that because of that then now you could do mod on each one so that they just don't get that big but so that's an optimization that i would uh urge you to kind of read up on which is module and verse but you know if you haven't got the mathematical background you will notice that i did a lot of stuff already there's stuff that's basic combinatorics meaning like counting the left and counting to the right and there's the right-hand concrete which is very right-hand concrete which is very right-hand concrete which is very uh computer sciencey but there's definitely like commentary goal portion and the modular inverse which is a little bit number theory slash whatever um so this is a very tricky problem with a couple of components so i so if you don't understand it or if you didn't get it during the contest uh don't feel bad uh definitely read up about these concepts and you know it'll be okay so let's go with the complexity right so the worst case scenario um is if it's basically a linked list right because you know because this is going to start with um being a list of size n and then a recursion would be the size of n minus one uh and then n minus two with all these like arrays construction so what that means is that the worst case is gonna be n squared um or that's it's n plus n minus one uh plus n minus two dot which is n squared right i don't know i think i said it uh incorrectly the first time and that's okay because n is a thousand so i knew that n squared would be fast enough uh even with this recursion then and yeah uh in terms of space obviously i have factorio here that's of n um but also uh stack space could be of n as well um though you know you could also depend how you want to count it because i have a lot of these things so kind of n squared but for n is equal to thousand it's okay um yeah but you can also obviously do it not that way uh but yeah by just keeping track of indexes or something like that uh and kind of similar to how you would do a merge sort so you could definitely be more space efficient but uh but yeah uh let me know what you think about this problem is like i said it's really hard don't feel bad if you don't get it there's a lot of maps that you might not know um so like and these are not maps that you could prove uh in the moment or like you know like it's really hard to prove in the moment um so yeah uh you know let me know what you think about this problem uh how you salvage yourself in another way hit the like button hit the subscribe and drop me a discord and now you can watch me solve the contest right about now eat this one first a thousand huh there's a mod as well okay hmm i see the recurrence bit hmm that's one way you went one way to leave the left and the right of two notes that's just so there's two on the left and two in the right that's just over two factorial is six and then minus one okay so then that's just left something like that okay i hope this is fast enough should be unsquared do um unique so yes times the possible love factorial so if i should cache this but i just want to get this right all right maybe let me just oh yeah minus one so i think i'm right except a minus one so that means we have to do some okay just okay this is actually annoying maybe i'll leave it turn off numbers okay i don't want to deal with to inverse mod right now let me get full where's my menses and doubles though why is this in double doubles oh i'm just being dumb uh hey everybody uh yeah thanks for watching um you know this was a fun contest so yeah let me know what you think hit the like button the subscribe button and join me on discord and i will see you during the next contest
|
Number of Ways to Reorder Array to Get Same BST
|
max-dot-product-of-two-subsequences
|
Given an array `nums` that represents a permutation of integers from `1` to `n`. We are going to construct a binary search tree (BST) by inserting the elements of `nums` in order into an initially empty BST. Find the number of different ways to reorder `nums` so that the constructed BST is identical to that formed from the original array `nums`.
* For example, given `nums = [2,1,3]`, we will have 2 as the root, 1 as a left child, and 3 as a right child. The array `[2,3,1]` also yields the same BST but `[3,2,1]` yields a different BST.
Return _the number of ways to reorder_ `nums` _such that the BST formed is identical to the original BST formed from_ `nums`.
Since the answer may be very large, **return it modulo** `109 + 7`.
**Example 1:**
**Input:** nums = \[2,1,3\]
**Output:** 1
**Explanation:** We can reorder nums to be \[2,3,1\] which will yield the same BST. There are no other ways to reorder nums which will yield the same BST.
**Example 2:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** 5
**Explanation:** The following 5 arrays will yield the same BST:
\[3,1,2,4,5\]
\[3,1,4,2,5\]
\[3,1,4,5,2\]
\[3,4,1,2,5\]
\[3,4,1,5,2\]
**Example 3:**
**Input:** nums = \[1,2,3\]
**Output:** 0
**Explanation:** There are no other orderings of nums that will yield the same BST.
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= nums.length`
* All integers in `nums` are **distinct**.
|
Use dynamic programming, define DP[i][j] as the maximum dot product of two subsequences starting in the position i of nums1 and position j of nums2.
|
Array,Dynamic Programming
|
Hard
| null |
617 |
Hello guys welcome to my interesting video not only coding that time also you can do it problem school malls 2nd T20 series level professional life get started solving abilities and physically mode tours and it's true love you all the value of the other is the note viewers you tree To understand what is this tours and so let's move and just not liquid values and will be the first to know liquid values and will be the first to know liquid values and will be the first to know of republic day function subscribe to the channel to second plus one should be worshiped for eggs and avoid all the function of units loop chat soen industry To Vacancy The Channel Ok And Of Childhood Itself Which Is The Child Of Countries Last Not The Tree To Attach This Is Gold Channel Ko Subscribe Button Hai 400 Vijay States And Will Love You Do n't Know They Are Back To Do The Child Does Not Alone Plus Trivikram fi suvidha and will remove should absolutely love function recovery inside left and right end som that thumb have no clue channels' drop-drop now life style should develop children channels' drop-drop now life style should develop children channels' drop-drop now life style should develop children of national interest Vikram null in this case and willam call function inside right child sober note Which is entry one vijay sengar welcome to that is the guide channel button and from below notary do maza-3 channel button and from below notary do maza-3 channel button and from below notary do maza-3 baithyou 770 note from this when will attach from which they here morning sacrifice of voters of return gift due recognition and will strike and left and right children And Now You Can Find It And Second So Let's Start Coding Detained After Coding My Home Credit Will Be Coming Years Will Just Room Met A Little But Before Being In Coding Sun Adhuri Don't Have Any Issues In Visibility That's Why Sometime To Move That Left Side Have torch start Let Me Do Anything Laxmi zoom out Android app I let me push west side the panel Let me zoom now so sorry for the evening College will start Okay so what they want to do Is viewers welcome to check the condition of any one else should Investors And Other Street Lights Of What Does n't Look So They Can Give 122 Others Can Give Me To 9 Return On Also Sleep Festival Snarls This Condition Will Welcome Equal To A B 2252 Personal This Condition Will Welcome Equal To A Big Returns And Teams Addition Wicket Name Just Second You Will Just Major Changes 231 And Finally 20180 Active Value Trees Particulars And Roots And Now Particular Notes Value Will Just Welcome Equal To That Value Plus Davinder 22330 Statement Attendant To Possibly They Listen And Vic Enrique WhatsApp Recorder Function In The left and right children so much free clearly will call and rap children stevens lt that laptop in water was getting don't but will welcome equal to the laptop the nutrition and they can also ajay that [ __ ] they can also ajay that [ __ ] similarly the condition for the right to Let me hand over the right side picture Naagin ke darshan se mila record sub recorder function majuri hai absolutely light on the right child leave one right and will have to right ok and finally water and tools which can else increase in state 21st observe this Jaswant Singh all The Value City One Vihar and Changing Left and Right Children Mitti and Sunil Up to Return All 100T One Only and I Hop Decimal Activities Actually an Easy Level Problem Middle Song Not Much of and Thinking Type Problem Basically Vinod Question and Droid Amla Definite Value Sake OLX Per Expression Steven Let's Check What Is The Pain Here Were Given Up And Started Worshiping And With Us The Spirits Will Organization Check Much Lutaya In Mein This Clean Water Space Application Thank You For Giving Speech And Listening Please Like And
|
Merge Two Binary Trees
|
merge-two-binary-trees
|
You are given two binary trees `root1` and `root2`.
Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
Return _the merged tree_.
**Note:** The merging process must start from the root nodes of both trees.
**Example 1:**
**Input:** root1 = \[1,3,2,5\], root2 = \[2,1,3,null,4,null,7\]
**Output:** \[3,4,5,5,4,null,7\]
**Example 2:**
**Input:** root1 = \[1\], root2 = \[1,2\]
**Output:** \[2,2\]
**Constraints:**
* The number of nodes in both trees is in the range `[0, 2000]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
349 |
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is intersection of two arrays so in this question we given two integer arrays nums one and nums two and our task is to return an array of their intersection so by intersection it means the common elements among both the arrays and the common elements should be found out by this condition each element in the result array must be unique and you may return the result in any order so I've taken the first example here we given two arrays nums one and nums 2 so you know the answer should be two because two is repeating here two is the common element in both so we write two in our output and there is one more two which is common but two is already present inside the output array and the elements inside the output array should be unique so if you add this pair of uh two inside the output it is not a unique element because two is already present so two will be remaining as the single element inside the output area so this will be our output which is expected here so we know we have to deal with uniqueness and we don't know the size of our output array first so because we don't know the size of the output array let us create a list I'm going to name it result so this is going to be an empty list in the beginning and now we have to deal with uniqueness right and also we have to keep track if we already encountered a common element so a good data structure is to use a map so let me create a ash map so this map is going to have key and value pairs right so first we're going to iterate through the nums one array from left to right we start with the zero element we check if it is present inside the map no it's not present so set it as key and set its value as one next element we are going to pick two check if it is present as key no so set it frequency as one next we have a two again so two is already present so we don't have to increment its count let it be one because we already encountered a two and we will deal with this uniqueness property by doing this so whenever you find a new to which is already present inside the map don't increment it let it remain as one so create a new entry so two will be overridden with the value one now again we are at this element it's a one so one is already present so no need to increment so overwrite this existing one by adding one and set its frequency to one again because we have to deal with unique elements as in the result now we filled the all the elements inside NS one into the map now using this map now we are going to iterate through the elements inside NS 2 so first element is two check if two is present inside the map yes two is present inside the map as key and check if it has a value one yes it has a value one so only then add that result into the map and now in the next case we are at two again but two is already inside the result so whenever you add this two into the result make this value as zero so override that value as zero because we already encountered a two so this will be return as zero so now we are at this element check if this element is present inside the map as key yes it is present also check if it has a value equal to 1 but this has a value equal to zero so it means two has been already added into the map so there's no need to add this two into the result so two will remain as the output now we reached the end of the nums 2 array we processed all the elements and now we have our output present inside result but this is a list right I have to return a integer array as our output so convert this integer uh result into a array so I create an array I'm going to name it answer which is going to be of the size of the result so I create a variable answer and then I'm going to iterate through this result and access one element at a time and add it into our answer so answer is the array right so array will be created and whatever is present inside result will be added into the array two is added into the array and now finally you can return this as our output because this is an array so two is the expected output here which is matching here now let's take a look at the code to implement the same steps now here as you can see first I'm creating a map let's take this example two so I create a map and I also create a result list now we are going to iterate through the nums one so we iterate through nums one and add all the elements into the map so as you can see we are adding that element as key and setting it value to one so four will be added into the map and set its value to One 9 will be added into the map and set it value to one five will be added into the map and set its value to one now we finished processing all the elements now we have to iterate through nums 2 so we iterate through nums 2 from left to right we check if 9 is present inside the map yes 9 is present inside the map we also check if 9's value is equal to 1 yes 9's value is equal to 1 only then we are adding that element into the result so add num is equal to nums 2 so this is 9 is added into the result and now before going to the next element we have to set 9's value to zero so 9's value was one it will be turned to zero now in the next element we are at four check if four is present inside the map yes four is present check if its value is equal to 1 yes only then add it into the result and now we have to set its value to zero so Four's value from one it will become zero now we are at 9 again check if 9 is present inside the map yes 9 is present check if 9's value is equal to 1 no 9's value is not equal to one so this will be skipped now we are at8 check if 8 is present inside the map as key no8 is not present anywhere inside the map so8 won't be added now we are at four check if four is present inside the map yes four is present so this part is true now check if Force value is equal to one no Force value is not equal to one so this condition is not true so this steps will be skipped now we finished processing all the elements inside nums 2 now we have a result present inside a list but we have to return a array as our output so we convert this list into array so create a answer array so this answer array is going to be of the size of the result list so size of the result list is equal to two so answer will have two elements so we use a for Loop to iterate through the list result from starting index I will start from zero so we are at this index so take this element and add it at the answer of I answer of zero is this index so add 9 here next I will be pointing here we take the second element and addite at that position inside answer now we finished processing all the elements inside result so come out and return whatever is present inside the answer array so whatever answer has 9 and four will be returned as the output which is matching here so the time complexity of this approach is of n + m where n is the size of the nums one + m where n is the size of the nums one + m where n is the size of the nums one array and M is the size of the nums 2 array the space complexity is of n because we're using a map and a list to compute our output that's it guys thank you for watching and I'll see you in the next video
|
Intersection of Two Arrays
|
intersection-of-two-arrays
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[9,4\]
**Explanation:** \[4,9\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
350,1149,1392,2190,2282
|
131 |
What are you going to cover? Video: Paren What are you going to cover? Video: Paren What are you going to cover? Video: Paren Drum Partitioning is a thing of the exam. Let's do it. Parallelogram Partitioning is fine. You can solve it with DP also. If you have not studied the degree then you will have background and this is fine. Let's know a little about it first. I have a medium level question, okay, you can find it on other platforms, what happens is different, and open a single element, okay, I have introduced and introduced and introduced and made it anything so This is not going to be a palindrome, okay, and let's keep it a little closer, man, these people are useless members of ours What is our What can I take after this What is our What can I take after this What is our What can I take after this So what can I take now Either I can take single A or I can take next I can increase and I can also give both A's from here, I have already taken these two, so I can take A and B from this, A and B, our palindrome will not be left, it will not be formed, what is left in this, I have taken both A's in this. I have done that one time, this one once, what is left of B, so I will put B once here, then my parent drum, if you check, I have to do it with the other hand, here I noticed one thing, I am watching with one hand. I have moused over it accordingly, otherwise it wo n't work. A B. Already A. The first one is gone. You can see it. A. B. A. Okay, so this is here. A. B. If I see, if I raid you, this becomes one thing. Gone is our now let's see the second one okay here I had the area okay so what do I have left with the B one so I took the B maybe A B maybe the chrome one got done okay if I get this good B The one is also done, now what will we do to check it? We will check it first. There would be a simple closing for it, which we have already covered, so in the lecture, if we take some pointer 2 pointers approach, then we will do the same thing. Today in this video, let's quickly see the code. If you see the code then it will be easy to enjoy and after that I will explain it once again. It is okay for you, proceed here like this There is a There is a lot of problem in the laptop, friend, it is okay. So what will I do What will RS do? Rest, which will remove the outer errors, you can give meaning to the data, this outer one also has some errors inside it, okay, what will I do to pass it, I will also put mine in it. Any one can increase the name, it comes in total depend upon, what will I do, then there is one more simple thing, because I did not tell you, I told you and it is already ready, you can do it in this way also, I want that too, okay, I will put it for gen range, it will start. Take care and the length will come A lot of meanings go here wherever I told you, I think I told you, I am not doing it, the follow up here is doing less for you, so in this case we do not have to call again. We will have to pop it directly and after that it came here Okay like this Forgot to return We will Forgot to return We will Forgot to return We will also do it and it will be even more messed up, man, look a lot and you will get it Take one or more, take more, not taken, that's left, take that in the next turn, this applies to this also, what's in the next term, take 1 kg or more, okay, I have a choice, I took one Took the A area, now what's left with me, now I'll write it somewhere here baby [ write it somewhere here baby [ write it somewhere here baby I can take either Elu or what I'll take, now I can take both, now I've taken it, so for this case my I have one more thing left, B has one more thing left, so I can take it later, now I have utilized both of them, here I do n't have anything left, so why ca n't I save that one, so I can't do it. I will get it, now let's move ahead, in this one I had an area, now I can take A or I will take all three, so I have nothing left, I cannot give you anything empty, now in this case, I took A, two are given together, so I have One thing is left, that last B, if it was E then I would have had B and Di, then I can also take the empty one and or in some other case, I can remain beedi. If I drank the empty one, then in the next chance I will get Di. I have only one chance left here to take A. After B, I will simply take B here. In this way, if I see what is being made here, it is okay, I will check in the room first. One is A B A. Second one is A and B. Let's check it simply. Here we look at the left right corner. Let's make left hand rider quanto and do magic on both to see if it is right or not. If it is matching, if it is not matching, then we will force it to be true, then it is the same thing, here we have made a mistake here, mistake, we have made a mistake here, if I have taken 'when' in the for loop, then 'my' is taken 'when' in the for loop, then 'my' is taken 'when' in the for loop, then 'my' is here. This variable has to be inserted from here to here. If you have inserted this variable here, then you will have to insert it from here. Our above one will not have to be inserted. This will be a simple thing, okay, and what else have we done? Forgot to return, that's why we are returning, we forget to return anytime and what else brother, nothing left here, one will go till Pay K Plus Van, one is fine, it will go till G Plus Van, rest of them, put any one of yours and comment. And you will get the solution. You will get the solution in the description box and I will also share this. Along with this, the phone will come in the version of c++ and I am also planning some more things. phone will come in the version of c++ and I am also planning some more things. phone will come in the version of c++ and I am also planning some more things. Now do a little editing and start uploading a lot of videos. Friend, I have not uploaded Wi-fee, now it will be loaded, wait till then, I Wi-fee, now it will be loaded, wait till then, I Wi-fee, now it will be loaded, wait till then, I will try to watch two or three videos in a day, as of now, I am shooting two videos a day in a week, but have not uploaded even one yet. All the videos, if I talk about detergent recycling, they are not even doing videos for 6 years, they are pending and after that, Didi will start, then after DP, I am thinking what to do, we will try, after the race, we will have only one topic left, that will be Hey, let's start with strings and strings are almost the same, there is a little difference, so hey, I will give the topic of strings, only those people read it first, but I will give them my rest, there will be a lot more in it, binary search has been done, a lot of searching has been done. All are done, then only 1 video will be left and a small video of Strike End will be left, so we will watch it all later and will try to post 2.0, rest of this is in this video, will try to post 2.0, rest of this is in this video, will try to post 2.0, rest of this is in this video, see you in the next video
|
Palindrome Partitioning
|
palindrome-partitioning
|
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= s.length <= 16`
* `s` contains only lowercase English letters.
| null |
String,Dynamic Programming,Backtracking
|
Medium
|
132,1871
|
862 |
hello guys welcome back to tech dose and in this video we will see the shortest sub array with some greater than equals k problem which is from lead code number 862. a prerequisite before watching the current video is to watch my video on lead code number 209 because the technique being used here is used in this problem as well minimum size sub ism okay so i hope you have seen this video and i will assume that you have seen my video on elite code number 209 throughout the explanation before looking at the problem statement i would like to announce about our data structures and algorithms program which is a guaranteed three months upskilling mentorship program and it is highly focused for interview so all the interview topics will be covered in three months along with the assignments as well as live discussions so if you are interested to know more then you can whatsapp us on the given number now let us look at the problem statement now in this problem given an integer are in nums and in integer k return the length of the shortest non-empty length of the shortest non-empty length of the shortest non-empty sub-array of nums with the sum of at sub-array of nums with the sum of at sub-array of nums with the sum of at least k if there is no such sub-array then you if there is no such sub-array then you if there is no such sub-array then you need to return -1 need to return -1 need to return -1 a sub-array is a contiguous part of an a sub-array is a contiguous part of an a sub-array is a contiguous part of an array okay i hope you understand this so let us look at an example for some better understanding now in this case in this example i have taken 0 to 5 which is 6 elements and there can be multiple windows where the sum is actually greater than equals to my k value which is the target value okay now in this case the target value is 12. i have drawn only two windows which are of smaller size and there can be other windows which will be having some greater than equals to target okay now in the first window the sum is 12 which is obviously greater than equals to target and the window size is 3. in the second window you can see that the sum value is 14 which is again greater than equals to target and the window size is two now out of all possible windows where the sum inside the window for all the elements if it is greater than equals to target you have to consider it and take the minimum of all the window sizes and that will be returned as an answer in this case let's say you have just two windows then we will take the minimum of three comma two and then we will get the answer as two i hope you understood this now one thing to note is window and sub array has same meaning both are contiguous part of the same array right our goal here is to find the minimum window size which has some greater than equals to target so let's look at the sliding window technique which i had explained in lead code number 209 which is a prerequisite of this video and i hope you have seen that so in that video i had explained that you can use two pointer technique and use the variable size sliding window in order to find the minimum window size which will have some greater than equals to a value target okay and in that video i had mentioned that you cannot do it if the elements can be negative you may or may not get the correct answer using that technique now in this case i have taken an example with six elements if i draw the cumulative sum graph this is a cumulative sum graph so if i take the first element i'll have 2 if i add the second element to the previous element i get 9 if i add 3 to 9 then i get 12 and so on right so this is a cumulative sum graph if you look at the graph and compare it with the graph which i had drawn in the problem number 209 then in 209 i had explained that the graph will be monotonically increasing but in this case this graph is not monotonically increasing okay in this case it is also decreasing and the decreasing curve is created because of the negative numbers fine now if you have negative numbers then actually you cannot apply your sliding window technique using two pointer so let us see for this example if that technique works now that technique works using a left pointer as well as a right pointer okay and using a current sum value so let's say the current sum is 2 initially now as soon as the current sum reaches to our target or exceeds target then we will stop and we will move our left uh pointer to the right but it is still less than the target so i'll keep moving the right pointer i'll add 7 to it and this becomes 9 now i will add 3 to it and this becomes 12. now you see that your value here is actually exceeding the target value so yes your right pointer will stop here but this may not be the smallest window possible so in the previous problem i had explained that you will compress from the left side and the left pointer will move to the right and you will keep on moving it unless your current some value actually decreases and becomes less than your target so if you move your left pointer to the right then this two will be decremented and this becomes 10. now the current sum has actually fallen below your target so you will stop your left pointer here and this will be your window along with that you also include the previous element okay so you have to do r minus l plus 1 and plus 1 to this which i had already explained in the previous video so it will give you a window size of so let's maintain a shortest window size which will actually be containing the minimum window size with some greater than equals to target initially i will give it a max value which is basically our infinity value and then i will try to minimize it because 3 is less than infinity fine now once this is done we will keep on moving the right pointer to the right unless again the sum exceeds our target so when r reaches to this minus 8 then the sum will fall to 2 now when it reaches to 4 the sum reaches 6 and when it reaches to 10 then the sum reaches 16 again 16 is greater than equals to target so our right pointer will stop at index 5 now this may not be the optimal window size may not be the minimum window size so we will compress the left pointer from left to right so while compressing we move the left pointer one position to the right and then we will subtract this seven so if i subtract this seven it comes to 9 and now 9 is less than equals to your target so the current window will be the optimal window according to the sliding window technique along with that you have to include the previous element as well so how many elements are here you have five elements so the window size is five now five is greater than this three so it will not get updated and now again you move the right pointer to the right and you will stop because all the elements have been passed by the right pointer now three is given as your answer if you apply the sliding window technique using two pointers okay but you will see that this example has two as answer because if you take only these two elements 4 and 10 then you will have a sum value which is 14 and this is greater than equals to your target and this window just has two elements so obviously 3 is not the answer right so you have to remember that whenever the graph is monotonically increasing then you can apply your sliding window using two pointers but when the graph cannot be guaranteed to be monotonically increasing this happens due to the negative numbers right then you cannot apply the sliding window technique you can take more examples and you will come to an understanding okay now what are our requirements in this case let's say that the graph was monotonically increasing then i could have applied my two pointer technique to solve it okay so if we can maintain a monotonically increasing curve then we will solve it easily by using the two pointer techniques now when we find a window with some greater than equals to target then we minimize the window size by compressing from the left side and this technique is the same which i had explained in lead code number 209 in the previous video okay now this is an observation may not be required here but just i have written it for simplicity that no two sub arrays can be of minimum size where the sum is greater than equals to target and starting at the same index so if i say that what are the sub arrays starting at this one the sub arrays will be 1 5 3 which is starting at this one now both the sub arrays has some greater than equals to target so this is sum 6 and this is sum 9. but then there will be only one window of minimum size starting from any index okay i think this makes sense and if it doesn't make sense then you can just leave out this point three it is not very important now what will be the choice of data structure for solving this problem the simple thing which comes to mind is stack because we are talking about maintaining monotonically increasing values and you know that monotonic stack can do that job of maintaining the monotonically increasing value right so this can perfectly do it because you take a stack and you keep on inserting element as long as the elements are increasing and as soon as you find a lower value number then you pop out the elements unless the stack is empty or you find a lower value number and you push the new element above it okay this is how monotonic stack actually works and maintains a monotonically increasing value now the second requirement is compression of the window from the left okay so compression of the window means there were two pointers so one pointer was right which was moving to the right was parsing the array and as soon as you find some value greater than equals to target you had a left pointer which was actually compressing means you have to remove certain elements from the left side now if you look at the stack the insertion as well as deletion can only be done from the top end only one end you cannot do insertion and deletion from both ends so this operation will not be supported by our stack so we have to choose another data structure and you will see that dq is a more powerful data structure dq can do all the jobs which the stack can do and it can do even more because in a doubly ended queue you can insert and delete from both the ends so a dq can maintain a monotonically increasing value as well as we can do push and pop from both ends either in the beginning or at the end so both these operations will be supported by a dq but cannot be supported by a stack and that's why we will pick dq and not a stack okay now what are the dq operations which you will be doing insertion of the new sum value at the end to maintain a monotonically increasing curve as we keep on passing the array and the second thing is whenever we find a window with a some value greater than equals to target then try to pop out the elements from the left side in order to compress in order to minimize the window size okay these were the two requirements and it can be supported by your dq so let us look at a dry run about how we will actually solve it okay now i have taken the same example so in this case i will start my parsing from this index 0 now as soon as i see index 0 i will increment by some value and this becomes 2 now i'll compare this 2 with the target is it greater no it is not greater fine so we will not do anything now we will have to push it into the dq is empty right so we have to push it into the dq so the dq node will be value comma index so value is your cumulative sum value okay so what is the cumulative sum here it is 2 so 2 comma index is 0 so this will be inserted into your dq move on to the next element and the sum becomes 7 plus 2 which is 9 now is 9 greater than your target no it is not greater than your target now the next thing you can do is you can compare with the first element of the dq so that whatever is a sub array you can find what is the sub array sum basically right but in this case 9 minus 2 will be 7 and again it will not be greater than equals to your target so just push 9 because 9 is maintaining the increasing order of the stack i mean it is not a stack it is dq it will maintain the monotonically increasing order 9 can sit over 2 because 9 is greater than 2 now you move to 3 add 3 to it and this becomes 12 now this value is greater than equals to your target as soon as this happens then you can compare it with the shortest window size it is already integer max and you can update it with the new window size which is i plus 1 which is index 2 plus 1 and this will become 3 okay now can we insert this sum 12 to the end yes 12 is greater so we can insert it at the end twelve comma index is two fine now we move on to the next element which is minus eight and this reduces the sum from twelve to four twelve minus eight is four now is 4 greater than your target no can we insert 12 to the right of i mean can we insert this 4 to the right of 12 no because then the graph will come down it will not be monotonically increasing so if you want to maintain a monotonically increasing curve you have to remove this keep on removing the items unless you find an item which is less than 4 otherwise your dq is empty so i'll remove this 12 i'll remove this 9 and 2 is actually less than 4 so i can insert this 4 now ok so this will be 4 comma what is the index it is 3 fine now we move on to the next element which is 4 so if 4 is added it becomes 8 is 8 greater than your target no it is not so can it be inserted here yes because 8 is greater than the top element so i mean this is basically your front element okay or your back element whatever you call if you call it back then this is front so you insert 8 comma index is 4 now you move on to the next element this is 10 and this becomes 18 and this is greater than equals to your target so obviously if you keep on adding from the beginning till this point then this entire array sum will be 18 and this will be greater than equals to target and the size is i plus 1 which is 6 5 plus 1 is 6 compare 6 with 3 but 3 is lower so don't do anything now can we insert 18 here yes you can always insert 18 right so you can up you can insert it at the end like this or you may delay the insertion you may do some other process so if you insert it here then try to compare it with the beginning one so if i happen to remove the beginning one like i have found a window with some greater than equals to target so the second thing is we want to compress from the left side how do i compress it you check with the last element if i subtract 2 from 18 will my sum be still greater than equals to target yes it will be so just pop it out okay so if you pop it out the sum value will be 18 minus 2 which is 16 still this is greater than equals to target can we remove this 4 comma 3 if we remove this 4 comma 3 then the cumulative sum till this point is 4. if we remove this then the remaining sub array will have some 18 minus 4 which is 4 i mean 18 minus 4 is 14 which is greater than equals to target so you can remove it okay now the next element is 8 can we remove this so if i remove this then the sum available with us with the sub array from starting from index after 4 will be 18 minus 8 which is only 10 so if i happen to remove it let's say we removed it then the sum left with us will be 18 minus it which will be 10 and now it has fallen below our target so we'll keep popping it up unless we fall below the target and as soon as we fall below target whatever was the la was the last popped item i will store it in my current popped item okay that item will be the starting point of our window so 4 will be the starting point of our window and the current items index will be the end point so this will be the window and what will be the size 5 minus 4 plus 1 which will be 2 so compared to with the shortest and 2 is less so it will be updated now you move your pointer and you have passed all the elements now when you are done passing all the elements whatever is stored in your short test will actually be the smallest window size where the sum is greater than equals to your target if while parsing throughout the parsing your short test did not change the value from integer max it remained as integer max then you have to return -1 saying max then you have to return -1 saying max then you have to return -1 saying that there is no window where the sum is greater than equals to target fine now in this case if you see each element can be inserted into the dq once and can be popped out of the dq once but once an element is inserted and taken out it will not be reinserted so the total time complexity is order of n and the space complexity for this is order of n due to the use of this dq let us now look at the code in this problem we are given the nums array as well as the target value which is k so i will find the number of elements and i have taken a dq in the form of pair which is basically your cumulative sum comma your index value current index now i have taken a long sum variable as well as the shortest which will keep track of the shortest window with some greater than equals to your k value now i will parse all the elements one by one whenever i see an element i will add it to my cumulative sum which is sum as soon as my sum value is greater than equals to my target i will update my shortest with the minimum value possible already known shortest value comma i plus 1 because the current window till the ith index from the zeroth index will be containing a some value greater than equals to k because the sum is greater than equals to k right and sum is being calculated from zero index now once this is done then we will try to compress the window size from left maybe compression is possible maybe we will remove the zeroth element and still we will be taking from index 1 to index i and again the sum will still be greater than equals to k it might so happen right for that reason we will keep on compressing unless the compression is not possible okay so if we take out 0 we will check for the sum from 1 to i is it greater than equals to rk value if it is then i will also remove 1 and i will check from 2 to i and i will keep on doing unless my sum value actually falls below k otherwise my dq is empty ok so this is that condition so this condition here checks if you have popped out any element if you have compressed by any element then the last popped item will be the starting index and ith item will be the ending index of the current sub array and you have to compare it with the shortest sub array already found and take the minimum of these two and store in the shortest okay so you have to dry run this code in order to understand it properly now the last case was before pushing any item let's say before pushing 10 over 8 we have to check if the top of the dq that means the front of the dq or you can say the back of the dq whatever so we say back so the back of the dq should have a value less than the current item and then only you can add 10 to the back otherwise if it was let's say 18 then it will not be monotonically increasing right then you have to pop out some items unless you find an item which is less than 10 in the back of the queue otherwise your or dq is totally empty until then you keep popping out the elements this is that case and after the suitable element is maintained or your queue is empty then you can add your suitable value which will actually maintain your graph in monotonically increasing order once the entire processing is done if the shortest is never updated it is integer max then none of your windows actually have a sum greater than equals to k so you will return -1 otherwise if this was will return -1 otherwise if this was will return -1 otherwise if this was updated at least once then you will return what is the minimum window size with some greater than equals to k okay so this is the entire code and in order to get a better understanding you should do the dry run by taking some examples so i hope you are able to understand it if you want to join our dsa mentorship program then you can contact us on whatsapp to get more details and we can guarantee that you will be interview ready in just 3 months if you like this video then please hit the like button and subscribe to our channel in order to watch more of this programming video see you guys in the next video thank you
|
Shortest Subarray with Sum at Least K
|
find-and-replace-in-string
|
Given an integer array `nums` and an integer `k`, return _the length of the shortest non-empty **subarray** of_ `nums` _with a sum of at least_ `k`. If there is no such **subarray**, return `-1`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[1\], k = 1
**Output:** 1
**Example 2:**
**Input:** nums = \[1,2\], k = 4
**Output:** -1
**Example 3:**
**Input:** nums = \[2,-1,2\], k = 3
**Output:** 3
**Constraints:**
* `1 <= nums.length <= 105`
* `-105 <= nums[i] <= 105`
* `1 <= k <= 109`
| null |
Array,String,Sorting
|
Medium
| null |
241 |
hey folks welcome back to another video today we're looking at question um 241 different ways to add parenthesis the way we'll be solving this problem is by using recursion um and memorization as well so the reason why we're using recursion right here is because every time you look at a problem it can be divided into sub problems so for example if you look at this example right here we know that this is the entire expression that needs to be calculated but this is a sub-expression that needs to be sub-expression that needs to be sub-expression that needs to be calculated before we actually get the value for this expression so therefore since this problem can be broken down into smaller parts we are using recursion and the next part next key part of the problem is why do we use like memorization right and the reason why we use memorization is because when you divide up an expression into two different parts right um there and these two different parts can have different values um themselves when they have different placements of parenthesis so anytime you take a sub value you calculate all the possible values that you can calculate using that expression with different placements of parenthesis so that you don't have to calculate them again so that's the reason why we'll use a hash map which is globally accessible um so the key type that you see here is string and the value type is a list of integers so basically what that means is for a given expression you can place parentheses in different uh spots and that will give you a list of different values will be which will be stored in the list of integers that we see right here right um so once we have that set up uh we can jump into the meat of the problem so the meat of the problem is you need to create a returning list right and let's call it result and let's call it me and it is a type array list we can initialize that awesome um so the next part is actually figure like iterating through all the characters um in the expression string um so let's say for and I equals zero I less than an expression dot length um and then you increment I right so um so we need to get the character value at that given in text and that's called it car C equals um expression not character art C add I sorry yeah and then we know that a particular um expression needs to be divided at a given spot only if it's like a like an operation right a positive negative or a multiplication so let's build another um small helper method let's call it blend um is expression uh no it's operation character um okay vector and let's just say Char C and basically if C equals Plus R C equals minus R C equals uh yeah that's a string so we take character if any of these values are present and we know that only these um these are the possible operators so these are the only ones that we need to care about if it is we return true if it is not we return false right so if c um so is Operation character so if the character that we are looking at is indeed um an operation we need to split that up um and we need to call the split strings uh into um like we need to call that like different ways to compute again so let's call it um string left equals expression um Dot substring and we need to take from zero so from the start to I um so I even though it is like an expression when you take the substring method it's exclusive of the end index so we need to take it as I and string left string right would be equal to expression Dot substring of I plus one and when you give it only one a parameter it means it needs to go all the way to the end all right um so once we have the string values like the substring values we actually need to call this on different ways to compute so um and the returning uh type is list of integers so let's call it list um and integers um and let's call it whatever we want to call it let's call it left compute equals um different ways to compute let me pass in the left substring and we do the same for right okay let's take some time to think about this right uh because it's a little complicated so basically what you're doing here is that as soon as you have encounter an operation um character it means that expression can be divided at a given spot and then what it's doing is that when you're calling this different ways to compute you basically calling it recursively on the left side and the right side and it's being divided again and again when you call uh different ways to compute and it gets you all the values that you actually care about so basically um different values that you could possibly get by rearranging parentheses in different ways on the left side and the right side so once we get those values um we basically need to use this combination so for example int um end l in left computed and for and R and right compute so basically you get a list of integers right so those integers need to be either added subtracted or multiplied based on the expression um the operation character that you're looking at so if C equals positive you would say um the given uh array of integers which is address and this particular value that we're looking at the left plus right and then else if C equals negative you do res dot add L minus r and then um else if um C equals multiplication you do rest dot add uh wait um awesome so once you have that basically what you're doing is for the for a given sub expression we have calculated all the values that you can possibly compare from the left and the right so once the for Loop is complete where does this actually close up okay once all of that has been completed what you need to do is that you need like one base check that we need to so if res dot is empty so what exactly does this mean that means none of the values were added into um the system into the list which means that the characters like the expression that you're looking at is like a single value expression that means like it's a single integer so what you do is um it would be res dot add um you need to parse it to end because it's in string uh parts and then yeah expression only if it is empty that means like none of these computations have come through that means it is a single um single cat like single integer um so that's the reason why you'll add that and then in the end um you need to add it so it would be map dot add or not put expression and then right so what are you doing here basically you're saying for a given expression um add all of the values that I've computed in that so that it can be used for something for the higher cases not the base cases because base cases are the ones who are actually putting in the values and for the higher cases they can be added and then in the end you just return Russ awesome let's try compiling this and see if it's okay the first two test cases are okay everything else is okay as well awesome so if you have any questions about this problem please let me know in the comments below I know this is not the easiest problem to understand but once you walk through it a couple of times with examples it becomes a lot easier um so if there are any other questions on lead code that you'd like me to solve also 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 it definitely keeps me motivated to make more videos um thanks so much and I'll see you all soon peace
|
Different Ways to Add Parentheses
|
different-ways-to-add-parentheses
|
Given a string `expression` of numbers and operators, return _all possible results from computing all the different possible ways to group numbers and operators_. You may return the answer in **any order**.
The test cases are generated such that the output values fit in a 32-bit integer and the number of different results does not exceed `104`.
**Example 1:**
**Input:** expression = "2-1-1 "
**Output:** \[0,2\]
**Explanation:**
((2-1)-1) = 0
(2-(1-1)) = 2
**Example 2:**
**Input:** expression = "2\*3-4\*5 "
**Output:** \[-34,-14,-10,-10,10\]
**Explanation:**
(2\*(3-(4\*5))) = -34
((2\*3)-(4\*5)) = -14
((2\*(3-4))\*5) = -10
(2\*((3-4)\*5)) = -10
(((2\*3)-4)\*5) = 10
**Constraints:**
* `1 <= expression.length <= 20`
* `expression` consists of digits and the operator `'+'`, `'-'`, and `'*'`.
* All the integer values in the input expression are in the range `[0, 99]`.
| null |
Math,String,Dynamic Programming,Recursion,Memoization
|
Medium
|
95,224,282,2147,2328
|
817 |
hi everyone let's solve this problem linked list components so the problem statement says we are given this linked list 0 1 2 3 and a list g which has subset of values from this linked list which is 0 1 3 all we need to return is total number of connected components so what's the definition of a connected component so the values of g right which are appearing consecutively inside this linked list forms a connected component so for example 0 1 these both values are appearing in this list g right so this is forming a single connected component this is not a connected component because it's separating uh this component with this guy so this is a single connected component of length one so let's see how we can solve this there are two techniques to solve this problem one is this event trigger algorithm what it says is the moment i see my event some something happened right i take some action so the another one is event termination algorithm where we say okay if something finishes let's take some action so we'll solve with it with first with this event trigger algorithm let's see how we can solve it and then we'll jump to the event termination algorithm so let's first convert this g list to g set because it's easy to check uh if this element exists inside the set rather than in the list so all i say is my total components right are zero and while i now i'll start iterating from left to right i say okay if head dot val is inside g set right it means oh this value was inside g set and in this case something triggered now so what happens okay i found the first value while i'd rating i found that value was inside g so what i'll do i will process this event how can i process this i say okay total number of connected components now increments by one but now let's reach at the place where the value is not inside the g right so let's do that it's okay my total components will be incremented and i ask for new head so okay so give me new head and what is my head now i'll pass it head and g set and it will give me a new head where the value will not be inside the set g otherwise i'll take my head to next position once i'm done i just return the total components so let's write this function give me new head so i say okay so if you have to give me new head take this g set all you need to do is check if you exist and head dot and while head dot val is inside g set i keep moving right so once i'm done either i'll be null or my value is not inside the g set which is what i wanted right so let's see guys if it works okay let's submit it awesome it does so let's jump to this event termination algorithm so in event termination algorithm let's get rid of this setup first so what you say is okay we don't need this guy and maybe we need this loop and total component right so this is what we want so all i'm trying to say now is the moment my event will finish so what is the event finish okay if i find my value is inside the g set right which is like one was inside this g set but its next value should not be inside the g set then i'll make a count and probably if next element is also null then again my event finished right so i just keep making that count so let's see how we can write this setup i say okay if head dot val is inside g set i just need to see does this end here like is event end right if it says yes right all i need to do is i need to count my total number of components and i just keep moving which i have to do every time so this is what the setup is so let's write this function i say okay in order to find if this event ends right so this is my g set sorry this sorry before this so all i say is okay if not head dot next right i will return yes it is end of the list right if not head dot next dot val in g set right again i will return true otherwise i just returned false right so we can just keep it in a single condition also but i think this makes much sense let's see guys if it works let's submit it also meters see you guys in next video
|
Linked List Components
|
design-hashmap
|
You are given the `head` of a linked list containing unique integer values and an integer array `nums` that is a subset of the linked list values.
Return _the number of connected components in_ `nums` _where two values are connected if they appear **consecutively** in the linked list_.
**Example 1:**
**Input:** head = \[0,1,2,3\], nums = \[0,1,3\]
**Output:** 2
**Explanation:** 0 and 1 are connected, so \[0, 1\] and \[3\] are the two connected components.
**Example 2:**
**Input:** head = \[0,1,2,3,4\], nums = \[0,3,1,4\]
**Output:** 2
**Explanation:** 0 and 1 are connected, 3 and 4 are connected, so \[0, 1\] and \[3, 4\] are the two connected components.
**Constraints:**
* The number of nodes in the linked list is `n`.
* `1 <= n <= 104`
* `0 <= Node.val < n`
* All the values `Node.val` are **unique**.
* `1 <= nums.length <= n`
* `0 <= nums[i] < n`
* All the values of `nums` are **unique**.
| null |
Array,Hash Table,Linked List,Design,Hash Function
|
Easy
|
816,1337
|
338 |
hey guys welcome back to the channel in our previous video we solved this problem counting bits the easy problem but we started using a method called extends okay this solution was pretty good it gave us a hundred percent timing it was a really good method of solving this but however i found this it might be a little bit difficult to wrap our heads around this function right here so as always we like to take one step further a picture of it okay so say we were given n equals 15 okay and we want to count the number of one bits obviously the problem is asking hey give an array up to n from zero to n where each element is number of ones in that binary representation so this is a good example of it okay so we want a picture right now okay so i'll go ahead and visualize it as always okay so we define our function define n call our function so now this is the function scope okay so first always we create our result variable it's zero and like we explained in our word file we're just gonna use that same formula we created just go ahead and watch the previous video so this can make sense so anyways the first elemental result is zero okay like instructor right here so we go into our while loop saying while the length of results is less than and less than or equal to energy so the first step is we want to extend our results by extending it by i plus one so meaning for each element in results just make a copy of him add one to him and add that to the result and i'll show you what that means okay so we create our list comprehension object right now so right now we're right here we create a list comprehension object right and all he says is take this result variable create a copy of him add one to it and append him back to it so see what happens okay so for the zero element we create a copy of him we add one to it so now this is literally just a copy of the results we copied it right here and added one to it and now we're going to return this value and appending back to result or extending back to result boom so we have this okay and we're going to go back the length of this guy's now two still less than n because n is 15 right we're going to do one more time okay create our list compression obviously take this result cut him down here okay and add one to each element in him so boom this is literally this right here at least comprehension now this is a copy of results but one is added to each element and results so now we take this value and return it back here and that append it to it there we have it okay so again next situation the length of this guy is still less than 15 right it's just four which length is four okay so boom we'll create a this combination of it again where we're gonna take results make a copy of him add one to each element that's what this line is doing and then append him back extend it back okay boom this is this again is a copy of this guy but we want added to every element so now we're going to return this value back here and extend it bam okay so now we're up to seven right but well eight characters and eight elements in our list but we want 15 okay so we're gonna do one more time okay at least comprehension again we're right here okay i'm gonna take results make a copy of him add one to every single element and result okay now we're going through it we're doing it good bam so this is results but we won't add it to every element so we'll take this return value and append him to result bam so just so we can picture it so literally we just appended it to result so let's see what it was before okay we take this we append him is this so now we have everything we need okay results is now the 16 elements in here but we only care about 15 right so the while loop is going to break okay so now we're going to have our return value just from like it says everything up until n plus one and n is fifteen and plus one so all 16 elements are gonna be returned and we're gonna print it out here to our console so that's about the video guys i hope this was helpful in picturing how this works and i'll see you guys in the next
|
Counting Bits
|
counting-bits
|
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,1\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
**Example 2:**
**Input:** n = 5
**Output:** \[0,1,1,2,1,2\]
**Explanation:**
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
**Constraints:**
* `0 <= n <= 105`
**Follow up:**
* It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass?
* Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
|
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
|
Dynamic Programming,Bit Manipulation
|
Easy
|
191
|
285 |
all right so this question is in order successor in BST so you're given a rot of a tree and there's a p value and then you want to make sure who is the parent of P basically right sucessor is going to be no two in this case so if no six um you will return no because there's no in order so it has to be in order so what does in order mean um in order mean like so you go to the left TR first right and then you go to your uh you go to yourself and then you go right so this is in order so for one this is two right in order uh successors too because um this is how it is right so two and one's connected but why this is not what this is not this is because six so in order is going to be five goes to three and then three goes to the children right and then come back up to five is the second step and then it will go right for the six right six is the last step for in order right so in order have three step so left and then yourself and then right so this is how it is so in order successful for this p is not so we can basically Target for what for the not for root. left only right root. left we don't care about rot. right um they just you know go through the answer and then use get it right away so I'm going to say three no successor equal to no so well root is not equal to no I know I'm still traversing and then I'm going to just make sure the P Val is greater equal than uh rout value right so if this is a case like P that Val is too big then we need to go to the right uh branch of the tree right and else it's going to be left right so if you want to be a left guy then look at this so one is right here two is here the successor for one is two so you make sure you assign your successor equal to root and then you say roal to ro left so this is a trick right um you want to make sure like um you want to go to the left before sorry you want to go to the left sub uh sub Branch uh with the a sign for the successor so assign the successor first then you go to the left branch and then you need to return successor this is a little bit you know uh Twisted but anyway so in this case for time in space is going to be constant time this is going to be log um uh H uh represent the height of the tree right you always you know cut the tree in into half right based on this guy right and this is a BST is always you know it's balanc for sure right the left side the left child the know is definitely you know less than the root right and right side is going to be good greater right so that will be it all right so if a question a Comon then I'll see you next time bye
|
Inorder Successor in BST
|
inorder-successor-in-bst
|
Given the `root` of a binary search tree and a node `p` in it, return _the in-order successor of that node in the BST_. If the given node has no in-order successor in the tree, return `null`.
The successor of a node `p` is the node with the smallest key greater than `p.val`.
**Example 1:**
**Input:** root = \[2,1,3\], p = 1
**Output:** 2
**Explanation:** 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type.
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,null,1\], p = 6
**Output:** null
**Explanation:** There is no in-order successor of the current node, so the answer is `null`.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-105 <= Node.val <= 105`
* All Nodes will have unique values.
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
|
94,173,509
|
1,706 |
That Album Pack And This Suggestion Will Take Another List Ko Problem Vriddhi Phil All Problem Appeared In The Doctor Just Watch This Video And Have Something Interesting For You Feature Problem Sirf Hai Vipin Ki Vriddhi Date Of Science And Roshan And Behavior And Goals Ok Sukhvind Sanobar Kabir Vidron In Witch Ear From Top Left Corner Dhan Right Corner And Another From Top To Bottom Work From Every Mother And Sleep From Bigg Boss Date Of The Problem subscribe free I Will Propose Exchange Top To Motivate Plate Servi Or So And Behave Great You Looking So Requested Lord Krishna By Subuddhi Krishna Das Home Pregnancy The Times In The Pic Shabbir Width Can Travel To The Bottom And Come To The Second Subscribe And Subscribe The Channel Subscribe Our MP3 Song But Starring 125 Decorations For This Solution 100 Condition Is This From where the body will never come down his enemy a general diary channel like this appears and polls due to the state and all will never reach from terrorism that when bill gets stuck into this portion of the grandmother will never come and another is at the British Babe That Venter Khush Who Will Never Come Down When In Quintal Beej Siddhesh Schezwan Gold And Acted In This Award Mila The Answer Is - 151 And Subscribe So Let's See Answer Is - 151 And Subscribe So Let's See Answer Is - 151 And Subscribe So Let's See How Definitions Of Key Program The First Indian To Minor And Colleges For Subscribe Say it is the end of kar do hu is this is apna ka sangeet Sudheesh condition course for its just so is dabir woh galat hai so isht bolkar saath poshan sudheer wa junior commission for the da loot 850 hai jo here the bill Gets Stuck And Will Never Stop Not The Condition Is For Checking Bhavya Vishwa Seat Full Beach Akbar D A We Want The Point The School Attendant To Subscribe To That And Authority In Chords Discuss Now Is Considered Quite Difficult To Like And Bottom Left Side Effects And Switch Off But He Died In Love With Subscribe Button Or This And Take Off But Not Behave With Sunil Basically About This Point Question And Answer For Class 6th Day Of The Week 900 Female For Only Jasbir Want And Had Tak Subscribe Plus Subscribe To Hai So Let's See The Code of Deposit Problem Fifty Years in the Food Misal Pav Yesterday Morning Shahid Problem Not Know Let's Co Problem First Form Will Make a Solve Function Will Quality and Will I Don't Know the Answer From Dar Hai Loot MP3 I Left in English Summary Bus Ab Aadhe Notes Two Rose Number Of Rose And E Know What Is The Number Of Columns Tomorrow Morning Making Person Name The Answer Will Contain The Answer To Our Problem And Tell Bill In His Life For Look Pet Will Treat For Every Body's Problem I am meeting now Researchers of variable in options trade and both that in the great and widget denote the column value over with bollywood top 10 particular time swimming garlic sauce 261 all roads and briggs check weather they can actually a chapter bottom of vicky donor the software will hide folder for Conditioner Tweet A Senior Leader Hindi Video And Will Check Brother Died But Club Bol Will Reach You Do Not Know What Is The Meaning Of This Condition Pet Certificate Means The Bol Will Never Reach To The Photo Kar Do Ki Main Kar Do Hua Hai Ajay Ko And Sunao Aur Sunao Bhaiya Viruddh Ford Foundation Ne Kabir Checking Gift That Was Judged Signaled Its Departure From The Top Left Corner To Zoom Gautam Right Corner To Be Implemented At Kollam And Others Will Declined To Kollam A Flexible Indicators Vaidya Ab Bol Can Read In The Bottom Don't Shove Bol Can't Waste Your Time With Vipul Singh Minus One To The Answer And Wealth Will Pushing The Column Value To Varanasi And Sunao Will Return The Answer Buddhist Philosophy That Tomorrow Yes Before To Art Increment Stop Column Shop Vihar To Agreement Key Plus Hai Lakhan Thakur Yes Yaar is King at this time Yes Choose Contacted So Guys If You Like the Video So Please Like Button Share the Video and subscribe the Channel and press the Surprise Gift Saunf Wahab Link Post Interview Description The Flash Lights of Rings Request Bathroom Key 119 Orders C You can avail date of birth link below description subject-wise and below description subject-wise and below description subject-wise and events related 2nd question and to this question suggest option comment blue and always different ghulamon thank you nice thanks for watching
|
Where Will the Ball Fall
|
min-cost-to-connect-all-points
|
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`.
* A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`.
We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box.
Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._
**Example 1:**
**Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\]
**Output:** \[1,-1,-1,-1,-1\]
**Explanation:** This example is shown in the photo.
Ball b0 is dropped at column 0 and falls out of the box at column 1.
Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.
Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.
Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.
Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.
**Example 2:**
**Input:** grid = \[\[-1\]\]
**Output:** \[-1\]
**Explanation:** The ball gets stuck against the left wall.
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\]
**Output:** \[0,1,2,3,4,-1\]
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `grid[i][j]` is `1` or `-1`.
|
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
|
Array,Union Find,Minimum Spanning Tree
|
Medium
|
2287
|
115 |
Hello friends, in today's video we are going to talk about liquid problem district, first of all this problem is a very famous problem, it is a very important problem because of the limit of Indian etc. and many times it means that it has been asked in the interview of a good company, then it is okay. Is the problem now tuition like TV where written number of district is the most images of S visibility is ok a sequential definition is there, you have definition of subjects like C such easy subjects of ABCD but it is not like that because see CID just change the order of these two. Emphasis in listing is the thing in it, this is coming first in Ranjish, this is coming before this, so I am all right, okay, so do it for this, now see this, we have example SNT, in addition, its answer is free, how to write stone, it is rabbit, in which often what It was like once you took these two doubles in your rabbit and once you took this and this also in your rabbit's fair, so your Team Anna, okay, this was yours, what did you do in this, you have made your team in three ways, okay, after making your team in this way, okay, let's see how we will solve this problem, see what we have here like this. What is the system? Is Aspirin ok and what is this system? But this is your assistant and what is our artistic? What do we have to make? In the third part we have rabbit double B that the idea is simple. If you have to subscribe and admit teenage then what will you do now matching character. After leave, the line from your study is matching, if you have gone to this, then you have not seen that air, it is not matching, okay, this is also a very good thing, if you have also gone to this, then this is also matching. Next If Vijay is on then baby match is taking place here, if next comes then come and add here too, this is not a match, okay, so you did not do this point, you made the ATM intimate, okay, if you want to make, then you can do some program of bread. You cannot leave it because today we had given it in the printer and this point had been given to Amethi. Okay, now the High Court has given you increment on verification. Come, next on this garlic letter pad has come. What is there here neither is the matching ok so Egypt this is done then next is Twenty20 match ok so book from here get an answer Vansh we are ready from here now let's do the next thing is back when we do from here That the match of RSEB was happening is fine but if we leave this one here and come forward and this one also but both of them have declared their matches, then it is fine for both the pieces and that After this, here you have Next also, so you have declared both of them as a match, then you have iPad, you have made these two i as a match, then you have team, which team has got the answer of half of the match killing, okay it should be one plus one. Okay now once again in this team world so you have this rabbit this situation and let's call you R8 double VIT we just did aa we have this that also left us okay this time what we Will try to leave this channel also, it is ready, it is coming a little earlier in between, the match is done, cut it, this match is done, okay wife, the match is done, now this one, whatever I choose, this is also yours. If we show it from here then it is also matched, it is strong from here and got the answer that you just got the total from everything, it is okay inside you, what is this method if any character of representatives If it doesn't match, then delete it. Okay, so when you were here, this is your rabbit string, which is your string, this is yours, and what is this strip, okay, you have to convert all the western dishes, all those chords into it. What we will do once we do is that you leave this between the two countries, then look now, this match will also take place here, so what can you do, either you can keep them as yours or you can also keep this one. By clicking here you can skip this part and give the secret of the second match with the result. You have the option to make the match on the match which Vanzara character is doing or you can make some track of it and make it available to someone else in the future. I am sure that someone from the teacher will match whatever clay is there in our printed leave with it. Here it is also said that you have matched, okay, now I have reminded the next one too, match these two, okay. I have come, both matches are Tuesday, maturity is traveler, you have to do this that whenever you have a chapter match, box office, two bus meetings, either you will mash it, then you will have a method of yours, or you will write it down, then this method will either I always confirm, either you do the school, the light is here, the man is also coming, cigarette, SMS, where the fourth character is also on, then we are the fourth character here, he leaked it, this too is not a test match, he expressed his views. Because we want to click on it in all the juice or if you just send any message that you have also consumed the medicine, whenever you have to match two characters to do the Ghee Percentage Festival, then you match them once in both acting. What is the different way, in this app, you can skip this one exactly in this fort and in the kitchen, any other middle path in the list of countries can also come and match with the middle of our President, but if there is any character then that match. If you don't want then you leave it with your hands cardamom if you have a cat here and what you have to do is you have to match it with the daughter so it is yours and this is the cartridge okay so you gave the start starting your this I don't see But this festival is fine that C so with this I have to use the same in the office if you have to use it then this remake is holiday mail messages if you message on the other side fear that intermittently two batteries are found fraudulent that you can't So to make the right or vaccine we will explain to any character by leaving the job, you have to click on his house but if there is a match then there are two ways, either what you will do is either you will take those seeds and made the sequence then you will get that land. Give your subscription by taking it, okay, here on the network, this person also wrote to us, so our 125 will be made, if you consume half of this pizza too, then you will go to this different subscriber, okay, so you have to miss it. You will just follow what we talked about and fold it. You will not get much. First of all, we will get half of this. Do you want to mix 6% of this? Whenever I mix 6% of this? Whenever I mix 6% of this? Whenever I ask, you have two options, either you leave it or you add it. If you have the option to leave the peepad by doing this and have the right to take it, then give us a way to block all the cosmetics, then we will do all the chords in it. Okay, take this topic and leave your lower one too, then everything else will stick but if In the middle also, this is the cardamom in your speakers, RSB, these three have been matched, what do you think about this year too, it has been declared a match, okay, so what side have we been made, so come and there is also matching in this. So you will have to click on this, then you will see this one, these two matches of this character are Twenty20 matches. Means, here we go now, we took it, so I told you its shy and here too, we were small, till then you cigarette is fine. If you are also strong then this is fine from two Kashmiris so I will try to write its total and reached Uike city to write something. Click write that we will have to take all the buses in between that I all of you will have to write rickshaw only then we will work cash. Withdrawal above Pandey, so we have given help obscene, hey, this message will be given to us, will return the answer to us, so here I will highlight the answer and later we will retain this answer, okay, now we have so many things but we have given you the answer. But just reached from here, how to see like this, how to write this cream, how to write Hague Helper and also this 800, both of these, how from the starting index, your speciality, which is your character, this is your eye point, this is to be pointed, which is the point. Make this point and start your I and JS at 80 position. Okay, then start your pair that is stop assistant. Okay, so it is printed in *. Okay, this is the point and printed in *. Okay, this is the point and printed in *. Okay, this is the point and what we will do is the string and offspring address that bar- You are going to call Bar Infection, address that bar- You are going to call Bar Infection, address that bar- You are going to call Bar Infection, if you do not pass the address then I will exceed my limit. It is big in this, it makes the base of this station its own wish, in which falsehood has taken place, means this is your point, that TV has reached. So you are going to get it here, okay, the meaning is that if you have a jet point, it has reached here and after this and it matches the tractor, then your appointment will be stopped, if this size yagya is done, then you will get the answer to it. You will get it, okay advice, if this is the condition, this ID has a delete price, then what will happen, you will have to do zero return that I did not get you the answer, so take the spice example, you have a string, this is the system, your baby, and what is this testing? Or TRP, both of these pieces are fine, so you are here right now, so do your matches so that yes friend, if the teams are not a match, then you cannot delete it, if you have to do testing for it, then your actually that you are also on Heavy, you do n't even click to return in the 30th match. If you are finished in this, then if you don't get it from there, then where will you get the cover from. Still zero money but I don't touch. All the troubles of coming here are over, so the return is in full swing. Now what will we do with this thing, if this, we have taken the necklace from the robbers from our place and will see if this is an ideal team, this match is happening in both the correct matches, the match was happening famously from the land of animals or you have to match them. Do it oh my sai plus one is for intermediate batter don't be fooled at all because the match is happening right and this is done by not matching them and in the feature match with someone else's character or teacher in search of someone else's career path. How is it right and the next question will be asked, that is, you limit it to yours, it is right here and what we have done is that we have also destroyed the i. Here we have given you the character of your present i by writing it. Okay, so all this is done, either you have matched it with your here, okay, and next time, what we are going to do is leave the earthquake and age to match it with the next one, which is also next, okay. This is when and how to match both, if but you have to match both, then you have only one way, you mute the present character of your president confidence or the present side has to click on the obscene item because this has to be done for you and not for any person. Ca n't reply to anyone, okay then this is it, next positive yoga, will give it to you in your next question or like your relative, subscribe both of them, will return our tears, okay so this is our correction function, has it come today? So, at that time, you can run it, thank you that after all, we are running it, so what else is there, you are zero from here, how can we do it or I can do 60 SST message channels by doing a little festival, yes, I can dip ads. And what will we do with this mark or do the school like three now submit it okay let's see what happens in the submit vitamin new time new why what will we do at every level this that British Zara I that We will have as many benefits as our brain, this is a different solution, its time click is fine, it is near you or far away, if any character matches then you can deposit it in or you can skip it, so if we year for what. Mila To End Positions Back Every Question Mitthu is 1434 So you are the tweet power of information that is the suggestion that Twenty-20 this one which is our solution Twenty-20 this one which is our solution Twenty-20 this one which is our solution will be time limited to accept Islam and after testing what is this bar- and after testing what is this bar- and after testing what is this bar- Same function is happening for kids, okay, that's why if we have installed DP here, how is DP, all we need is a DPR, we will get the weight and size of the macrame of our acidity, we have kept it was our website. Okay, what will we do, this is on the side, we follow this tomato top-down, she will we follow this tomato top-down, she will we follow this tomato top-down, she will write DP and she thought that after minus one t, so she gives it to Shahid Rafiq, we did it for a minute that now on which They may also be struggling with us, what should they do? We are taking Gemstone which is our sugar level from this point, Sathiya, after this, we will check the blank check which is being deposited below, so that we can get this notification in this DPI and this call. But this function has already been exited, so what should we do, we will do it directly in Delhi skeleton, okay, he has a free computer, okay, now you take this, I will come here, whether there is barcode or not, come here, apply semicalculus on this. Did the show more the morning running submit by hand and tell a specific Mishra if we set it and this is the same accept by activating it you have society solution pass this print solution complexity is fine 600 why then see whatever your From the DP key, its value is the same maximum, the same time is felt. Okay, now let's go, because once we take the digestive person, now let us return it directly that I have got these pimples more than the ones he got *Subscribe to Abs, it was ours. Remedy and this is ours which is this and subscribe this is the admit rabbit's one yoga and this is money and this is our this Marathi problem ok papa this person and this decide among yourselves then you here and here now on the basis Subscribe to appointment and subscribe to subscribe Tennis Championships are repeated many times, so what to do, there will be duty here, we have to do this first by dipping, so in this way our solution will be done, okay, you can also convert it into water from all sides. Can bottom work contact so what is it that top dukia button by converting automatically till we embroidered size on west side I sexually frustrated size with amazon family size and this you wi-fi off servi aa size and this you wi-fi off servi aa size and this you wi-fi off servi aa me sir ji If your s is if all this puja cab your eid is ok and tiffin time is very soon then you subscribe if not subscribe the channel then click on the text now and if seen then what will we do we will subscribe both of these one this we that we match And what did in this will try to meet this so subscribe this if you subscribe button and if you just so that if you this and this then if just and subscribe can't make because if a now school and so now what we To do this, we will subscribe, if we copy the old Ali to it, then it will be made. Now see this is matching. Do subscribe, so I have it here and here, see here, this is sure and here is a copy of this. Will do now see here click on this above and subscribe my channel if you subscribe like and if this I if it is not matching with yours then do the above value which is our romantic just above I M N S Manju copy If you want to make two dozen matches, then you will do this, we will text this thing that if you are a match, then let's take the host, okay, let's look a little bit with this, if you have seen it, then whatever it is, then just copy the valley problem above. The given cover was also matching, if it is placed on top of it, then mix it and if you match it, then this one here, it seems that this one should match with any of the above, then you should subscribe to our channel. Now if school robber also has problem then you must like, comment, if you like the video then you like the video, subscribe this channel, share, I will try to present such good interview problems in easy language for you. You definitely need some solution, I should thank you very much, I was in a hurry, next day, take care by thank you.
|
Distinct Subsequences
|
distinct-subsequences
|
Given two strings `s` and `t`, return _the number of distinct_ **_subsequences_** _of_ `s` _which equals_ `t`.
The test cases are generated so that the answer fits on a 32-bit signed integer.
**Example 1:**
**Input:** s = "rabbbit ", t = "rabbit "
**Output:** 3
**Explanation:**
As shown below, there are 3 ways you can generate "rabbit " from s.
`**rabb**b**it**`
`**ra**b**bbit**`
`**rab**b**bit**`
**Example 2:**
**Input:** s = "babgbag ", t = "bag "
**Output:** 5
**Explanation:**
As shown below, there are 5 ways you can generate "bag " from s.
`**ba**b**g**bag`
`**ba**bgba**g**`
`**b**abgb**ag**`
`ba**b**gb**ag**`
`babg**bag**`
**Constraints:**
* `1 <= s.length, t.length <= 1000`
* `s` and `t` consist of English letters.
| null |
String,Dynamic Programming
|
Hard
|
2115
|
844 |
Hello everyone welcome to my channel Quote Surrey with Mike So today we are going to do video number 23 of our strings playlist Lee number 844 is a very easy question we will make it with two approaches both small and approachable asked this question and it is very important And this is a good question, from the interview point of view, the question is quite simple, you have been given two strings, S and T, okay, you have to return two, if then equal, type into MT text editor, where and the string will contain either character or So hash must be written. Hash means that you must have pressed the back space button. Okay, so let's say s = A. B is hash. So if you = A. B is hash. So if you = A. B is hash. So if you type this in a text editor, then first you will write A, then B, then back space. Dabe hash means back space, what is the meaning of back space, if this b is removed then the final string will be formed, okay, similarly S and T have been given, like look at this, S and T are there, so if you input this, you will type it from the keyboard first. A will be written, then B will be written, then D will be written, then if you click on the hash, D will be removed. Okay, similarly, if you type this, A will be written, B will be written, C will be written, then as soon as the hash comes, this one will be removed, so see the final. What happened to the string A? It means that the final string is both the same then its answer will be true. Okay, similarly look at this string A C B A, then a hash came, then A got removed, then again a hash came, so this B got removed, after that. E came then F and then look at this C B A three hash came so this went this also went MT string came then e came then F came then are these two equal otherwise the answer will be false Okay let's look at this A B then hash came twice, then this B went, then this also went to A, so MT string is left with me, let's see in this, because of C hash, C got removed, then D came, then because of hash, D got removed, so this also MT string remains. So its answer is true because look, this is also MT and this is also MT, okay so see, this approach one is very simple, whatever I just told you, make a string of this and make a string of this, okay After creating, compare whether both are equal or not. If you are looking at the string then you have to create it separately. You are taking extra space. You are taking o of m for this and o of n for this. So brother, my first approach is very simple. That you will have to take extra space because you will create a new string and compare it. This is a very simple approach. Simply form the new string and compare them. Okay, so take any one example. For example, if you take this example, then I will take a simple one. I will write a function like this which will take a string and what will be the resulting string, it will create it and give it to you like this is a bd, so what will I do, I will take a new string named temp, now it is mt, now I will iterate over it, the first character is a. So the first character I put here is a, the second character is b, I put b, the third character is d, then put hash, then temp dot pop back, temp dot pop underscore back, what will happen with this, the back character will be deleted, so because of the hash. It got deleted. Then there is any character after that, otherwise look at my resulting string. Look at this. Who is this? Removed, ok, now see the resulting sing, this is A and this is A, both are equal. Yes, the answer will be true. So the first approach was so small, it was simple but you have to take extra space, so its follow up question can be this. Show that without using extra space. Okay, so let's look at approach two. Now let's look at approach two. Using oven space. Okay, so before starting, understand a small logical thing. Look at this string like this. Let's first assume that it is C. Then came B, then came A, then later, because of the hash, both of them got deleted, so what does it mean that now I have written these two, now I have written these three, but it is possible that they may get deleted in the future. Okay, so what is better than writing again and then deleting it, if you traverse it in reverse like it is CB, it is Sha, if you travel in reverse, then what is the benefit, like assuming that you are here, it is a character. This is also a character here, so count how many hashes there are. If there are two hashes, then you will skip two characters and come directly here, so the advantage is that you do not have to go back and delete again and again. That's why I am saying that why is reverse traversal good, here it is okay, so I told this logic, Y traversing from n-1 means from end, from n-1 means from end, from n-1 means from end, why is it good to traverse from here is good, okay, so we will do reverse traversal and see. What is the benefit we are getting by traversing in the reverse direction? Okay, so look, pay attention here, let's assume i is here, j is here, okay, are both the characters, yes is the character and is the character, then it should be equal, is equal, yes is equal. So we are good, I am here, J is here, are both characters, yes are characters and both are equal, so we are good, I am here, J is here, okay, now look here, as soon as hash Found, I will count how many hashes are there. I means how many hashes are found in What did I do to get Aa skipped two more times? It's okay just like Aa was here so I counted, I got one or two hashes, so two characters I skipped and Aa will come here. Okay, similarly J has also got a hash. Skip. How many skips will have to be done in these t strings, let's see, if I get one hash, two hashes, ti hash, three hashes, then what will I do by skipping three characters and directly bring j here. Okay, so now notice that i is at 0 and j is at -1. is at 0 and j is at -1. is at 0 and j is at -1. Okay, so now j has gone to 0 and -1, so let Okay, so now j has gone to 0 and -1, so let Okay, so now j has gone to 0 and -1, so let me check here which character is there at the position i is at, which character is i = 0 but c is j = - which character is i = 0 but c is j = - which character is i = 0 but c is j = - Which character is there on 1? E-1, if it is out of Which character is there on 1? E-1, if it is out of Which character is there on 1? E-1, if it is out of bounds then take any random character, that means invalid character, we take dollar. Are these two equal? If not equal, these two equal? If not equal, these two equal? If not equal, then obviously our answer will be false. It is very simple, one more. Let's run through the example, let's do a dry run and it will seem easy. Look, first let's come to this from this example. Okay, I started from here. Is this a hash? Yes, so I have to skip how much, I will write that to the characters. I take, here I have got a hash, then I came here, is this a hash, yes, then I will be able to skip in the future in two characters, then I came here, is this a hash, no, there is no hash, but look at the value of skipping, it means two. I can skip two characters, if I find the first character, then I skipped one character, made the count one, then come here, okay, I can skip this too because my skip value is one, now it has become zero, come here. It is here, now look, it is obvious, it is equal to -1, the lesson has look, it is obvious, it is equal to -1, the lesson has look, it is obvious, it is equal to -1, the lesson has become 0, so we will stop here, now look carefully at this, J is here, okay, so is this the hash, yes, I did the value one, let's come here, is this the hash? It is not there but it can be skipped. Look at the value of skip. If it is one, then I have skipped it and also made it zero. Now let's see if this is a hash. Yes, this is a hash. Then again the value of skip became one. Then when I came here. So this is not a hash but look at the value of skip, if it is one, then it is skipped and j is here, now j also becomes -1, so we now j also becomes -1, so we now j also becomes -1, so we stopped here, okay, so let's see which character is on i. So If j is -1 then we put a dollar character is on i. So If j is -1 then we put a dollar character is on i. So If j is -1 then we put a dollar and if j is also -1 then we put a dollar. and if j is also -1 then we put a dollar. and if j is also -1 then we put a dollar. Okay, so what happens is that both of them come to equal -1 at the same time, meaning our come to equal -1 at the same time, meaning our come to equal -1 at the same time, meaning our answer will be true. From this we know that i. Look at i which is lesson 0, but j has become 0. Look here, i has also become 0, j has also become 0, meaning any lesson can be 0, no lesson can be 0. So what does it mean, for how long will I run the while loop, either i takes 0, it is okay, no, that is, i = 0, or 0, it is okay, no, that is, i = 0, or 0, it is okay, no, that is, i = 0, or j > = 0, any one = = 0, till then j > = 0, any one = = 0, till then j > = 0, any one = = 0, till then I will run the while loop because look here. This was greater than equal to 0 but this less than 0 still I ran the loop that's why I came to know that both of them are unequal so look here the day both of them are not greater than equal to 0 then only I will break the for loop and then from the while loop It is clear till now, you must have understood it, right, after that, what did I tell you that we will calculate the count of skip s and calculate the count of skip t, while till i is greater than equal to 0, okay look, pay attention. If s of aa i ect if it is hashed ok then it means we will increase the skip count ok and aa minus we are doing ok because i which is my n - starts from 1 ok because i which is my n - starts from 1 or else if and when We can proceed when skip t is greater than 0. Okay, so skip t will be minus. Okay, and I will also be minus. Okay, that means either it is a hash or skip my now gr zero. If neither of these two then break. Will do means I have got some character, this time then we will break in that case okay, similarly j greater e 0 means do the same thing for the string t also if a if t of j is equal to e equal to if the hash is okay then skip t plus are increasing the count of skips and j minus okay if it's not there if it's not a hash then there will be a character so can we skip that character then we can do it when skip t is greater than 0 okay So skip t make it minus and j minus and if any character has come ok then what will I do I will break these two things were doing now see i and j let us assume that the character has come then remove the character. Let's take care which character of s is there, it will be A of A, but I told you that Aa lesson can also be zero, so put a check here that if Aa lesson is zero then it is okay then consider it as dollar if not. If it is equal to zero, then assume it is dollar, otherwise off, assume it is OK. If if, this first character is not equal to the second character. If it happens then return false s simple as that and if it does n't happen then it's ok go ahead aa minus j minus ok and as soon as the whole while loop is finished return true at the end, meaning anywhere we have returned false. If you did not do it, then it returned true in the end. All were equal, that is, it is a very simple code. You must have understood it like a story, that is why I have shown it by dry running it with two examples, so let's quickly finish coding both of them. do b i
|
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 |
1,696 |
hey what's up guys this is sean here so today let's take a look at uh this one 1696 jump game number six so you're given like a zero index integer arrays then read nums and an integer k so you can do uh a move uh basic a jump right so which means that you can you start from index zero and your goal is to reach the end of the array which is the n minus one index and you can only jump forward at most k steps which means that you know you can jump from one to k at most and you need to return the maximum score you can get so the score is a summary of all the number of other indexes you have ever visited so for example this one you have like a one minus one and the step you can jump is two so which means that you can at the most jump uh two numbers so and the for you in the example one here so the uh the optimal uh solution is you jump from you start from one and then you jump from one to minus one and then from minus one you jump to four and then from four you jump to three that's why the define the total the answer is seven and similar for this one right for now example two here you jump from 10 to four since you can skip two numbers basically you can jump three steps right and then from four to three that's why the answer is 17. yeah so on and so forth and here's the constraints right so the constraint is uh 10 to the power of 5. so this gives us like a hint what kind of solutions we can choose from and i think it's not that hard to figure out this is kind of like a dp problem you know so i think the dp transition function is pretty straightforward right so it's like the dpi right the dpi means that from 0 and the ending the target the ending point is the ice numbers what's what is the maximum score i can get right so i think the state transition function is pretty straightforward so basically we just need to get the maximum right the maximum from all the uh all the dps right the dps from uh from i minus k minus one to two i'm to i minus one yeah this minus uh i think this one is plot plus k so i mean you guys get the idea right and then plus nums plus the card number right so it means that you know the uh so we have these numbers here right i mean the uh and let's say we are at this number here right this is the i and i say the k equals to 2. so it means that uh when we if we want to stop at this location right so we can only pick we can only jump from how many players how many pla how many options we have to jump to this to the current uh location we have uh if k is equal to two we can jump from here so here is one and then we can jump from here so this there's only these two options we can choose from because here it's out of the range right so here from here to here actually that's a step three right and yeah so basically that's the state transition function basically we just at each of the i here we just need to go through all the previously dp within the range of the i minus 1 here right that's i minus 1 and then from i minus 1 to i minus k plus 1. yeah and then we just plus the numbers and in the end we simply return the dp n minus one that's gonna be our answer but the uh the time complexity for this knight of dp approach is like uh n squared right because for each of the eye here we're going to loop through k numbers of dps and the k can also be as big as the number itself the length itself so that's why it's n square solutions and it will tle so which means that we have to find a better way to solve this right and so here we're getting the maximum of some values here right and actually this is like a big hint right and here actually the problem can be converted into a maximum value for sliding window right and here since k is equal to 2 that's why the sliding window size is what is 2 plus 1 h3 because we are including the current one right so and the size of the starting window even when the case equals to two is three so we just need to have a find a more efficient way to give us the sliding the biggest the maximum values right within the sliding window and to do that i mean i think some of you may have already known right so we have two options right so first one is that priority queue second one and the priority queue is the unlock and solution and there's even a better way to do it which is by using the to use the monotonic queue and which will give us a log n time complexity i mean in total which is basically here will be a one but we have o n in total if it's priority q it will be a log n time complexity for a priority queue i mean you can choose either use either way but i'm since we know there's the better options that's why not just use to just use that so i'm just going to use the monotonic queue to maintain the maximum value within the sliding window and actually so to be more specific to get the maximum values we need to use a decreasing q so and similarly if we want to maintain the smallest numbers in the sliding window we use the increase in q because when we have like a decrease in q here we can use i mean the decreasing q of zero that will always give us the maximum values for the current sliding window which will only take all one time yeah so let's try to implement this then all right so we have n equals a lot a length of the numbers that's going to be the total length and then we have a dp right so the dp is the uh since we're getting the maximum we are i'm initializing everything with the negative big negative numbers here so at the end here and then we have a dp 0 right so the 0 is num 0. that's the base case um yeah because here i there i don't think we need uh like un plus one size here we can just use uh insides because uh we can just get the values for dp zeros and then when we start the loops here right we can just start from uh one start from one because for if there's only one numbers right actually the starting point is the ending point which means that will there's a there will be only one numbers we ever visited which is the number itself that's why the dp zero it will be the number itself the number is zero and here we have it and in the end like we just need to return the dp minus one which is the last one okay so and now we need to also define uh decreasing q which will be used to store the maximum dp value within the sliding window and actually the way this decreasing uh the monotonic queue for the work is that instead of storing the number itself we'll be storing the index because there could be a duplicated numbers right uh on different indexes that's why we have to use in index so that we can do the pop and append correctly and so for dp zeros since we're starting from one here right i mean at the beginning the dq will have like index zero okay that's gonna be the uh basically the biggest numbers we have when we have like uh only one numbers and now and we have we need to maintain this monotonic uh the monotonic the sliding window so actually this i spent some time i was using the k because i didn't notice that actually to jump k actually the size of the sliding window it's k plus one so and i'm just going to use this one here k plus one the size right size of the sliding window and now we can use the k so this how this thing works is that you know first uh with the new i here we check if there's any uh if there's any numbers that we need to move out of the sliding window so basically if the is equal greater than k right and then we need we know that so the numbers on the left most needs to be moved out of the sliding window but since we are only maintaining certain numbers in the in this decreasing q here that's uh that's why we also need to add a second conditions here right so if the current biggest number right so if the current biggest index the number index is the i minus k then we just do a decreasing q dot pop left right so the reason we add this one is otherwise you know if the one that gets moved out of the sliding we know it's not the biggest one then we don't have to do anything for this decreasing queue we only do this when the ones gets moved out of starting we know it happens to be the current biggest one that's why we need to remove that one because that will affect our calculation okay so that's that and now we have what do we have like uh we have a sliding window right we have a valid sliding window and then we can just use it to calculate the current dp which the dpi might equals the nums i plus the dp of decreasing q uh zero right because this is the biggest dp values we have right and okay now the next step is to update the sliding window let's start update the decreasing q basically to maintain this monotonic q so while q is not empty and the dp of the decreasing q of -1 if the top one the dp values of -1 if the top one the dp values of -1 if the top one the dp values is either equal smaller than the dp of i here right and then we just need we need to pop this thing out and then in the end we just increase we just append the current index to this decreasing queue yeah so i mean so this is i mean this is pretty i think it's not hard to understand right so with the reason we're doing this while loop here is because you know we're maintaining like a decreasing uh dp values in this decreasing a monotonic q here uh so that right so that we can have we can use one time sorry so that we can use one time to get the biggest values and here since oh even though we're having a while loop here right and b is b uh because each numbers or each dp will only will be pushed and then popped from this decreasing q only once so we so may which makes this while loop also o1 time complexity uh sorry o n time complex in total basically this one will not uh basic uh add another level of time complexity on top of this one here yeah and yeah i think that's it is and if i run the code here to accept it right and i submit yeah so it's a pretty fast right so the reason being is that the time complexity for this solution is o of n like i said the only thing we need to care is the this for loop here and the while loop here it's not it's like uh in total it's in total is 2n so it's basically the o of n plus o of uh to anything yeah this that's append and pop so in total it's still of n time complexity yeah i think that's it for this problem you know it's a i think it's a pretty standard it's a very standard db problem just with a little bit of optimizations because of this 10 to the power of 5 constraints and the way i'm using is to use the monotonic queue because that will give that has the best time complexity and some other options is that you can also use the priority queue right i won't imp i won't implement that but it should be pretty straightforward to use priority queue basically this protocol is it's also being used to uh to maintain the uh the maximum number based in a sliding window i think that's that and i think there's also we can even you can even use the segment tree to solve this problem but that's a little bit more complicated to implement i will not uh go over that at the moment yeah i think that's it thank you so much uh for you guys to watch this video and stay tuned see you guys soon bye
|
Jump Game VI
|
strange-printer-ii
|
You are given a **0-indexed** integer array `nums` and an integer `k`.
You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**.
You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array.
Return _the **maximum score** you can get_.
**Example 1:**
**Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2
**Output:** 7
**Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7.
**Example 2:**
**Input:** nums = \[10,-5,-2,4,0,3\], k = 3
**Output:** 17
**Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17.
**Example 3:**
**Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2
**Output:** 0
**Constraints:**
* `1 <= nums.length, k <= 105`
* `-104 <= nums[i] <= 104`
|
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
|
Array,Graph,Topological Sort,Matrix
|
Hard
|
664
|
160 |
Hello Everyone Welcome to Centerpoint Today We Are Going to Solve Analysis Problem Name Intersection of Princely States Software for President subscribe and subscribe this Video Subscribe As Suffering From One To Avoid This Particular Intex Existence To Return Back To 1282 Where is the intersect 90 Pushpendra Films Show Laddu Subscribe Button More Subscribe Video Channel Ko subscribe and subscribe the Video then subscribe to the Page That Noida Traffic Jeevan Nowhere Else Can The Can See Only One Destroyed In The Beach Sex Ok Sudhish Will Be Interacting Noida Will Return C1 To Pocket So What Will Be The Time Complexity Of Difficulty In Amlo Prize For Science And You Will Be Order Of Name * And Correct Soft Ise Jalil The Name * And Correct Soft Ise Jalil The Name * And Correct Soft Ise Jalil The First Class Ninth Of The Second Remedy An Egg Subscribe And Like And Subscribe Now To Receive New Updates Time To Subscribe to Time Channel So How Can Fall Within That Time Subah Clear Point To You Samay Expressway Se Zinc Specific Any Soul Within That Time Ok No Problem You Can Take One Seth This Video Seth And Tried For The Hole For Telling List Services One Should Not Be Tried For Enabling Cystitis Acid Nothing But A Restaurant Association And Not Have Some Unique Reference Okay Sweet Can See There Lives After No Affidavit Discrepancy Like That Is Not He Didn't Want To Know What's The Difference Of The World Subscribe to Channel Off List Aadhar No One Should Contact Will Schools Can Avoid subscribe The Channel subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the Video then Play List Topic Find Latest Me Bhi Desperate And Went To Take His Definition Of The name of a northern extra cloth cutting solved Video then subscribe to The Amazing Channel and subscribe the Channel subscribe now to that he did not next ok fennel you all sorts of head appointed nodal officer to subscribe my channel subscribe to jo hair ko * hit on set 2010 not jo hair ko * hit on set 2010 not jo hair ko * hit on set 2010 not interested in stayed in to effective exist in mid turn on the particular intercity not free from fear why history please mom dad jain minister mukul taneja point tha left behind also a dot next ok point that and sop this tool in cases If this pond is destroyed and don't forget to subscribe and subscribe to how to cancel fat loss qualification for giving us the effects of other nor can see subscribe this Video then subscribe to the Page if you liked The Video then subscribe to Main So Gaya Express Will Be Properly and Tough Times without subscribe to the Page if you liked The Video then subscribe to the Page The person who tested the 22017 device to 200 degrees Celsius absolutely welcome to the self I will leave was also checked And Subscribe Our The First Flight To See 110cc Varanasi In This Quest Welcome To And Welcome To Siwan Pregnancy 102 Not Request Welcome To See Two 9 This Then Move To CESC To Bebeautiful.in Will Rule Mist Rich And Famous Bebeautiful.in Will Rule Mist Rich And Famous Bebeautiful.in Will Rule Mist Rich And Famous List A 25 Should Avoid You Will Not Equal To Our Video subscribe this Video plz subscribe Channel subscribe and subscribe this Video not Sona Vishisht Atithi Ne 1999 Subscribe To 189 Small Right Now Will Come Into A Given Only Side Effect Vinod And Busy Interesting Point Has Proposed Fast Point Is Point Internal David Warner Dheer Wa Set The Subscribe And Welcome To Subscribe My Channel Subscribe And Share And Subscribe Button Thank You 500 Index Acid Hui Niswat 1.8 Teacher 500 Index Acid Hui Niswat 1.8 Teacher 500 Index Acid Hui Niswat 1.8 Teacher Student Fix Hai Arvind Subscribe To 241 Punishment And Transport Number Five Topic So Let's Previous directly surplus of so lets previous comment is required so lets previous direct code so add discuss welcome to take two point on instant face pandava dynasty so initially point to has notes2 a little point to head b that nine will involve vrat in distic centers and not equal Ok subscribe to the Page if you liked The Video then hai aur is nuskhe channel like this point to the next not to come for water similarly for people with pintu this request null additional little point to that point to do the father Given up to you can see a boy loves not tried so let's field under 7000 compiling and not a on this occasion stitch compiling and let's get started and solution of math of you can see all districts and thus much better than time so check it just now Another Solution Hair Note You Can Express Fennel Time To Misery Will Be For Tender Kind Of Employment And Space Congress President Can Stand Ok And Request For This Video If You Like This Video Please Subscribe My Channel And Difficulties And Comment Section Thanks For Watching By
|
Intersection of Two Linked Lists
|
intersection-of-two-linked-lists
|
Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`.
For example, the following two linked lists begin to intersect at node `c1`:
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
**Note** that the linked lists must **retain their original structure** after the function returns.
**Custom Judge:**
The inputs to the **judge** are given as follows (your program is **not** given these inputs):
* `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node.
* `listA` - The first linked list.
* `listB` - The second linked list.
* `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node.
* `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node.
The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**.
**Example 1:**
**Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3
**Output:** Intersected at '8'
**Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.
**Example 2:**
**Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1
**Output:** Intersected at '2'
**Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
**Example 3:**
**Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2
**Output:** No intersection
**Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
**Constraints:**
* The number of nodes of `listA` is in the `m`.
* The number of nodes of `listB` is in the `n`.
* `1 <= m, n <= 3 * 104`
* `1 <= Node.val <= 105`
* `0 <= skipA < m`
* `0 <= skipB < n`
* `intersectVal` is `0` if `listA` and `listB` do not intersect.
* `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect.
**Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?
| null |
Hash Table,Linked List,Two Pointers
|
Easy
|
599
|
1,730 |
so this PA to get food I solved this problem in 11 minutes and now let me try to solve it again to check how many minutes I need to solve this problem while am yeah while am also giving a introduction of this problem and explain how to solve it so normally for this problem we are giving a people so the people want to eat food the food can be any places and we also have the obstacles so this kind of a war structure it is obstacles so the people cannot reach to obstacles but the people can eat food and people go can go for direction and we're going to need the SED path to get the food so these people just need to eat one food don't need it but for any of the food we just need to calculate the S part so of course this problem going to be a BFS there can be two solutions so the single Source BFS is just starting from people and eat the food and there will also be multi Source BFS so we're going to start from the food and then with the people but for Simplicity for this problem I'm going to use the single Source BFS yeah now let me just start coding I'm going to do some preparations so for the RC would be length of the grid and length of the grid zero and I'm going to prepare a direction array so the direction array inside it going to be the for Direction yeah so I just need to prepare those four directions so this going to be the four directions yeah now I'm going to check the RNC so far R in r and for C uh in range C I'm going to check the grid so if grd RC equal to the this people so this people are is star if it is equal to Star it means I'm going to start from the people now I'm going to prepare the BFS so I'm going to prepare a DEQ so inside it going to be a tle so it going to start from the RC and with the steps of zero and I also need to prare a Ved set so it going to be a set inside and it going to be a top of our and C now I'm going to check the Q and while text two uh we are doing the BFS so I'm going to pop out so for RC and steps so be equal to Q do pop uh left now I'm going to check this R and C so if grid RC equal to the food so the food is a has so if it is equal to a has I got the result I just needed to return the steps so this going to be the sest pass so otherwise I'm going to check the directions so for Dr R and DC in directions I'm going to calculate Z and this column it going to be r+ d r+ d r+ d r and C plus DC now I'm going to check if it is inside the boundary or not so for the row it should be more than equal to Z less than R and similarly for the column yeah it will be less than C and then I'm going to t this row and column tle should not be invited and our low column not in invited set and I also need to check it is not a obstacle and grid RC should not equal to the obstacle so the obstacle is X so if it is not equal to x uh we're going to Che put it inside of the Ved set so the Ved set should theend uh yeah the set should add a top of row and column and similarly for the que the Q need to attend a top of Z and column and here steps would plus one so this is my template if we didn't find the solution we're going to return a minus one if we find it we're going to return the steps so this is the entire code now let me run it to T as you can see it works now let me submit it and the time complexity is R * c as you can the time complexity is R * c as you can the time complexity is R * c as you can see it's really fast and RN C it is 200 * 200 so that is why it is so fast and * 200 so that is why it is so fast and * 200 so that is why it is so fast and this time complexity is just this R times C it means the length and WID of the grid yeah as you can see this is a typical BFS problem and it's just like a reading the problem if you understand it normally you can solve it because no matter which way it's going to be EAS easier than you expected no matter the single Source BFS or multi Source BFS it going to be similar you just need to f a star F this people and then you start the BFS until you find a solution if you didn't find you're going to return a minus one thank you for watching see you next time
|
Shortest Path to Get Food
|
special-array-with-x-elements-greater-than-or-equal-x
|
You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell.
You are given an `m x n` character matrix, `grid`, of these different types of cells:
* `'*'` is your location. There is **exactly one** `'*'` cell.
* `'#'` is a food cell. There may be **multiple** food cells.
* `'O'` is free space, and you can travel through these cells.
* `'X'` is an obstacle, and you cannot travel through these cells.
You can travel to any adjacent cell north, east, south, or west of your current location if there is not an obstacle.
Return _the **length** of the shortest path for you to reach **any** food cell_. If there is no path for you to reach food, return `-1`.
**Example 1:**
**Input:** grid = \[\[ "X ", "X ", "X ", "X ", "X ", "X "\],\[ "X ", "\* ", "O ", "O ", "O ", "X "\],\[ "X ", "O ", "O ", "# ", "O ", "X "\],\[ "X ", "X ", "X ", "X ", "X ", "X "\]\]
**Output:** 3
**Explanation:** It takes 3 steps to reach the food.
**Example 2:**
**Input:** grid = \[\[ "X ", "X ", "X ", "X ", "X "\],\[ "X ", "\* ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "# ", "X "\],\[ "X ", "X ", "X ", "X ", "X "\]\]
**Output:** -1
**Explanation:** It is not possible to reach the food.
**Example 3:**
**Input:** grid = \[\[ "X ", "X ", "X ", "X ", "X ", "X ", "X ", "X "\],\[ "X ", "\* ", "O ", "X ", "O ", "# ", "O ", "X "\],\[ "X ", "O ", "O ", "X ", "O ", "O ", "X ", "X "\],\[ "X ", "O ", "O ", "O ", "O ", "# ", "O ", "X "\],\[ "X ", "X ", "X ", "X ", "X ", "X ", "X ", "X "\]\]
**Output:** 6
**Explanation:** There can be multiple food cells. It only takes 6 steps to reach the bottom food.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 200`
* `grid[row][col]` is `'*'`, `'X'`, `'O'`, or `'#'`.
* The `grid` contains **exactly one** `'*'`.
|
Count the number of elements greater than or equal to x for each x in the range [0, nums.length]. If for any x, the condition satisfies, return that x. Otherwise, there is no answer.
|
Array,Binary Search,Sorting
|
Easy
| null |
818 |
cool 8:18 race car or your car starts at cool 8:18 race car or your car starts at cool 8:18 race car or your car starts at position zero and speed past one an infinite number line your car can go into negative physician's car drives automatically according to sequence of instructions a and are when you get in instruction a your car desta following the position yeah you gain some speed and then you speed up shift by one when you get an instruction all your car just following your streets if your speed is positive dance okay so you just change signs and also stop or not stop but your speed goes to just one so okay so do we move we don't necessarily do we have to mister late like that sir first number after all you go stuff so there's not like a stay and just cruise now for some target position say the link with the show his sequence of instruction to get there Roka and the targets between one and ten thousand okay he's ready professor cause yeah I mean I did but research maybe concerns too many candidates and you can actually like we pass us all of 10,000 try to be fancy let's not do of 10,000 try to be fancy let's not do of 10,000 try to be fancy let's not do it but research and the tools the only to state my position and speed so how to do maybe no I'm with try it out and see okay yeah by definition the length will be the shortest but I strongly hit that know what and I think their notes are precision and speed and you want to get precision where want the precision is evil target right it's okay start with start position you know at speed of one I'm doing C++ in text for a second tiny I'm doing C++ in text for a second tiny I'm doing C++ in text for a second tiny actually I might just like mixing languages too much little bit I'm off with the schooling is real quickly don't mind me in Tonopah father and what is Wow yeah just pop and in the index field I won the business and screw the performance of this let me go get that real quick just to cute very fun this guy should use tack okay I use collections that King attack only like subset collections so I'm not coming how he caught us some T's libraries Easter okay group and return okay cool look I know okay and now if I should use was a name tapas I think you always tell me like we I need to practice okay otherwise we cue up or kinda ticklish okay I so get Q and a and the position just at speed yeah this would really be more I think maybe this benefit a little bit from cleaning some of the search space but we just stood out it kept because with quite test bounties and only you can see what their performance is I'm gonna see what that is the entrance oh wow okay that's good to know so we definitely just need them who does it make sense to go to the negatives no I do not I guess I should have kept some mistake it's not we need to hear I just wanna make sure my sin that is yeah I just said to doing good stuff in the tight dad wait yeah I didn't that's why it's that which is unexpected cotton Krishna yeah there's kind of a greater that's why maybe I should use a name top of okay I'd finished pretty quickly okay miss think what it's like a good number to test ten thousand it was to today with 12 13 it's eight thousand so no that's right find out again between two powers of 2 s or something like that okay one time see don't practice don't notice now my output is really one so I actually know why somebody did yeah I was not paying attention I just want to get rid of the time limit but it's because I do not a soul away it's just not cool yeah so of course it takes that long oh now it's much a little bit Elise it is still well hopefully bit hmm there should be or at least like it's not give you a blunder enter its my sleep the waste one this may be a little too slow so I'm gonna have to think let's see make sure that this picture is at least wait for then we can do some optimization uh-hmm Wow so you meant this as well let me place my things what we sure should be why even if it's not efficient all right No and I'm just a little surprised that it is or that it takes so long because if you're like I'm doing too much bit like I imagine there's only like about 40,000 States x times the number of 40,000 States x times the number of 40,000 States x times the number of speed and speed is like 10 so like they've half a million states maybe some like that like it takes that long and also it well that kind of wines like a crappy doctor swing but half a million so why does it take that long to happen in the States maybe the cutest they just think maybe I could that I could clean up I don't have to use the tech but why is it alright let's move out let's say we don't care about memory for now much first mmm slightly faster probably said it still to hear him go ahead Isis vodka Wow huh I have to sign it on the screen correct okay that's why that makes it tick sure it's good data I can fix the cash so I don't read stuff okay good thing is that it works by thing is that it's really slow okay at least my intuition I think one thing here is speed if speed is greater than 20,000 maybe we don't is greater than 20,000 maybe we don't is greater than 20,000 maybe we don't need to do this point for sure well maybe that's you that helps enough just be devilish to a branch out absolutely anyway this means that costs pretty good huh like a second pastor okay can you precision as well no better advice wash to that chakra position so we've got this bacteria that's in there but that way slightly faster opens it right I mean it's a little bit on slow side we'll see how we do no steam it's fast you know I might have to do a few optimization okay that's fast enough oh I never understood sighs I don't use any memory so maybe I just want memory that'll be okay hey awesome I guess girl we have a huge lookup tables because oh they precalculate and I guess I mean it's also like similar to dynamic programming right so you could look at these states and then just you know do the search that way and maybe even search backwards now back but I guess they have more crazier look-up guess they have more crazier look-up guess they have more crazier look-up tables because I'm using 180 max I understand five mics and it's still less than 100% whether we saw my stuff is than 100% whether we saw my stuff is than 100% whether we saw my stuff is slower so okay uh yeah I mean I think my first search is fundamental so the way I erase the way I did it I think you would totally expect to give this an interview in some way maybe not just exact problem but like you know some structure that is similar to this I could definitely have yeah it's a post modem much more I could have between the self as I mentioned I would definitely use name topo so that all these stuff though these away industries are easier to read and so forth but what this is just like a queue and like a professor is Turkish military standard for that purpose we had the typical T standard ish I mean I think it's a little bit hard side to the optimization you know that's funny to talk about anything we're possibly but I think definitely the court justice standard I don't know there's a maybe there's a harder intended solution that they won by the but the way I did it I think it's relatively straightforward I've been one thing to notice also that if you store stuff like we have a dynamic programming flow then speed always tableau so you could actually just keep the power of two that you're in versus you know doubling every time which is inferior depending on what you're doing or how you storing the table it could be easier but that's my only observation on dad you know I'm okay I think and I could definitely see this or something similar on a into real research comes in handy live yeah cool
|
Race Car
|
similar-rgb-color
|
Your car starts at position `0` and speed `+1` on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions `'A'` (accelerate) and `'R'` (reverse):
* When you get an instruction `'A'`, your car does the following:
* `position += speed`
* `speed *= 2`
* When you get an instruction `'R'`, your car does the following:
* If your speed is positive then `speed = -1`
* otherwise `speed = 1`Your position stays the same.
For example, after commands `"AAR "`, your car goes to positions `0 --> 1 --> 3 --> 3`, and your speed goes to `1 --> 2 --> 4 --> -1`.
Given a target position `target`, return _the length of the shortest sequence of instructions to get there_.
**Example 1:**
**Input:** target = 3
**Output:** 2
**Explanation:**
The shortest instruction sequence is "AA ".
Your position goes from 0 --> 1 --> 3.
**Example 2:**
**Input:** target = 6
**Output:** 5
**Explanation:**
The shortest instruction sequence is "AAARA ".
Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6.
**Constraints:**
* `1 <= target <= 104`
| null |
Math,String,Enumeration
|
Easy
| null |
1,609 |
hello and welcome to another video in this video we're going to be looking at even odd tree and in this problem you have a tree and all of its nodes are on different levels so the root starts at level zero then the next is level one level two level three and for every even level the nodes all have to be odd and increasing and for every odd level the nodes have to be um even and decreasing left or right so let's take a look at the examples so in this first one this is true right this is odd has to be odd these are even and decreasing then odd in increasing and even in decreasing so this is correct so we want to return true um in the second example the first level's fine right it's odd second level is even and decreasing which is fine but the third level is not um strictly increasing it has to be strictly increasing and it's not so you want to return false and in the third example the first level is odd the second level is even and decreasing and the third level is um oh actually yeah sorry so I missed that so this is not even and decreasing um this needs to be even and decreasing and the nodes are odd right so for every odd level the nodes have to be even for every even level the nodes have to be odd um yeah and there's 10 fifth node so you want to have like a linear time solution there's kind of two ways to do this and let's talk about the two ways I'll briefly describe one and then I'll kind of describe the other one so one way is to do a DFS and the way to do this is you can basically store for every level like what's the last node you visited right so in the beginning we didn't visit anything so we can store this in like an object or something we start the route and we basically just go we want to make sure that we visit nodes left to right or we can't actually technically visit right to left but essentially we want to make sure like we visit the 10 before the four we visit the three then the seven then the nine and so on you have to have some kind of order you can either be left to right or right to left and this is pretty easily accomplished by just whenever you recurse left and then right and then for every level we just check like is there a node before this node and do all the things that we have to have are they all true right like if I'm on an even level the node has to be odd if you know all these things and then also compare it to the node before and so let's say we visited 10 and now we visit four since we know we're on an odd level we know this has to be um we know these have to be even and decreasing so we just check like okay we're at the four is it even yes is the number we visited before the 4 10 is it even yes or not is it even but is four less than 10 so let's briefly walk through that like that solution I'm not going to show the code for that but we can briefly um walk through the solution so essentially like at level zero and when you recurse you just pass down like the level and the node so at level zero we check okay we're at the root we don't really care where we're at the root but we basically check is this odd this has to be odd it is so if it's odd we're going to check have we visited anything on this level before no we haven't so we're going to mark this level zero with the we only need to Mark the last value we visited so we Mark we mark one then we go left probably need to make this bigger so I can like make it go okay so we go left and same thing we check is it even because we're on an odd level yes it is and have we visited anything before no we haven't so at level one we're going to visit node 10 and when you recurse you just pass down like the level down so if you're at level one when you recurse you just pass in level two and so on so that it's pretty straightforward so we recurse left again same thing we check um let's actually move this over here so you see better so we check is this odd or even so we're on an even level so no has to be odd it is odd have we visited anything yet no we haven't so we're going to Mark level two node three let me go left one more time think it's a little bigger there same thing it's fine to be even because we're on an odd level is this the first node we visited yes it is so at level three we visit 12 then we recurse back up and then we go right then for this node we're going to check is it even because we're on all level yes it is have we visited anything before yes we have and remember this has to be strictly decreasing so a is strictly less than 12 so that is true so we just replace 12 with eight now and this ensures that you're basically storing the least amount of information possible you can alternatively store an array like for every level you can store an array of all the elements but because you only need consecutive elements to be strictly increasing or decreasing it's fine to just store one so this will give us a little bit better space so we recurse up here we're done with that now we go down here so we're on level one so it has to be even it is have we visited something yes we have it's 10 and is this strictly less than 10 yes it is so we can replace it with a four um yeah okay and then uh we recurse right actually sorry we recurse left so we check is this odd yes it is this have we visited anything on level two yes we have is it strictly greater because this is an even level so our node has to be greater so it's just like a bunch of basic if statements like on an even level your nodes have to be odd and greater and so on so we recurse down here then same kind of thing it's fine what did we visit before we visited eight six has to be strictly smaller it is and then for every node you can just return like do all these things match and do all these things match for the children and if any child is false then you just recurse return false for the whole thing so that part's pretty straightforward as well um and then yeah so we do that then basically we come over here and do this kind of same thing right so here um on level two this is nine it's it we visited seven nine is strictly greater so we'll change it to nine then we recurse down here and this is the last one and here the last thing we visited six is strictly less yes so we'll update it to two then we just like recurse all the way up and return true so that's how you do a DFS um a BFS is pretty similar except the BFS we can just for every single node we can just have a Q instead so the way this one's going to work is pretty similar except now we'll just have a Q so we'll start off with the root in a Q and then we can just keep track of the um route and the or the node and the level and then we just check like what level are we on if we're on an even level it has to be odd and we check is there a node after it and if there's a node after it then we'll also check those values so let's kind of walk through this really quickly um so for in the beginning we'll have this node of value one and I'm going to store the node not the um value but I'll just write down one here so we're going to have node value one level zero put it in a que then for every single node that we pop from the queue we will put in its children so I'm not going to have these brackets I'll just have it like this and move this over so I have a little bit more space so for this node we're going to put in its children so we're going to put in 10 at level one and four at level one so we pop it put in it children and then we have to make sure that it's strictly um less than nodes on its level so when we pop it we're going to check is the Q does the Q have anything so when we pop this from the que the node like the que won't have anything yet because we put these in after we pop so we pop it put in its children uh there's nothing in there yet so this is fine then for this node we're going to pop it and then we're going to check okay is the node after it there is a node after it now is it on the same level yes it is and because this is an odd level the node after it has to be strictly less so we check is this strictly less yes it is then we can pop it and put in its children so we can pop it put in its children so we have for 10 we just have the three and it's on level two then for this 41 we're going to check okay is the note after on the same level by checking the level no it's not so we don't need to compare it all we have to do is just make sure that it's even because it's on an odd level so every time we pop a node we'll just make sure if it's even or odd and then we just check is the node right after it on the same level by comparing the level and if it is then we have to make sure it's like strictly increasing or decreasing and if one of those is ever false we just return false and if we're able to make it through our whole Q then we'll return true so we pop the four we put in his children so we have seven with a level of two and nine with a level of two and notice how in a BFS you're automatically getting like level order traversal and it's in order right like we have three s then nine so for this three we're going to check um obviously is it odd or even it's the right thing right we want an odd and then we check the one after it so this is on the same level and the one after has to be strictly increasing so we can just check these values so that's fine it matches all of our criteria so we can get rid of all this node is fine and we put in its children so it's children R 12 with a level of three and eight with a level of three then for the seven we do the same thing compared to the nine um they on the same level nine is strictly greater so that's fine everything's fine there and then we put in the children of seven it's just six with the level of three then um for the nine We compare it to the 12 they're not on the same level so we don't have to compare like is it bigger is it smaller but it does have to be odd which it is and we put in his children so two with level of three okay now for 12 it's on level three so it has to be even it is we compare it to the node after has to be strictly decreasing it is it has no children so we just remove it from the queue for eight same thing it's on the same level of six no children six strictly less so perfectly fine get rid of from the Q then finally for this one same level two strictly less get rid of it from the Q and then for two there is no like Noe after it so that's fine like we don't have to compare to anything because there's nothing left in the queue and it's even just like we want it so we were able to get through our whole queue um successfully so we can just return true so that's the BFS and the DFS is the way I described earlier where you just have a dictionary or something outside and you just write down the last node you reached on every level either one's fine so let's look at the um BFS solution so we have a Q we append the root to it then while we have nodes in the que we're going to pop the node and the level so our all of our items in the queue will be the node and the level kind of like I showed in the picture then we just check so notice that for an even level the node has to be odd and for an odd it has to be even so you can do this little trick to uh make sure to check all this all these cases in one if statement so essentially if this basically checks is this one odd and is this one odd so if they're both odd or if they're both even then this will be true and then you want to turn false right because one has to be odd one has to be even right for an even level we have to have an odd node for an odd um level we have to have an even node so you can just do like one if statement take care both of those then we want to check for the node we popped is there a node after it so if there's still a BFS and the level still matches right because we only care like when we're on a node like let's say we're on this node and this node's after we don't need to compare those but if there's a node after the node we're on and it's on the same level then we do need to compare those so uh if there's a node after our current node and it's on the same level then we have our two edge cases right or two cases so if the level is odd then the nodes have to be strictly increasing so if um uh actually did I do that right no I got that backwards yeah so the level is odd then the values should be strictly decreasing right so these are the odd levels this one and this one so they have to be strictly decreasing so if the next node is greater than or equal to our current node then it's not strictly decreasing we return false and then for even it's the other way it has to be strictly increasing so if it's less than or equal to it then we return false as well then we B basically just check for the children so if the node has a left or right child we just add it to the queue and we add one more level and we just return true for we're able to get through our whole queue successfully so these are like the two main things you have to re you have to practice for trees I think a lot of people only do DFS so it is occasionally good to do BFS but I think um recursive DFS Solutions are a lot easier so generally I'd stick to that but this is one that you can kind of do both ways so I decided to do BFS because I don't do it very often um yeah and so we can run this one and it's pretty good it's like everything's kind of the same so just run it a bunch yeah um so we can talk about time and space so basically no matter what no matter which method you choose um and for the DFS no matter what you store technically like I always say if your tree looks like this um the for this the recursive solution will be oen space they'll both always be over in time because you do have to go through every node but for this the recursive DFS will be over in space because you keep adding stack frames now worst case scenario for BFS because we are storing like the level um like we're going to have a level or something uh on there at a time actually for BFS you prefer to have this kind of thing because then you pop a node you put it in a child so then that will only have one node so that's good but if your tree is perfectly balanced and that's going to be the worst case scenario for the um BFS because essentially you're storing like a level at a time so if you store this bottom level that's half the tree so that's still o space so like worst case scenario for both of those is going to be ENT space and for the time pretty much for almost all tree questions you're trying to get an noen where you visit every node only once and that's kind of what we did here right we visit a node we put in his children we pop off the node and so on so this is oven and oen this is like the case for 9 95% of tree problems like the case for 9 95% of tree problems like the case for 9 95% of tree problems probably um so yeah you can briefly talk about like for what kind of trees your space gets better and so on for a BFS versus DFS so I think it is good to have like an understanding that you know like I said if it's like this is bad for BFS because you store a level um but this is good for DFS and the other way it's good for BFS and so on so yeah um that's going to be all for this one hopefully you liked it if you did please like the video and subscribe to the channel and I will see you in the next one thanks for watching
|
Even Odd Tree
|
find-all-the-lonely-nodes
|
A binary tree is named **Even-Odd** if it meets the following conditions:
* The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc.
* For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increasing** order (from left to right).
* For every **odd-indexed** level, all nodes at the level have **even** integer values in **strictly decreasing** order (from left to right).
Given the `root` of a binary tree, _return_ `true` _if the binary tree is **Even-Odd**, otherwise return_ `false`_._
**Example 1:**
**Input:** root = \[1,10,4,3,null,7,9,12,8,6,null,null,2\]
**Output:** true
**Explanation:** The node values on each level are:
Level 0: \[1\]
Level 1: \[10,4\]
Level 2: \[3,7,9\]
Level 3: \[12,8,6,2\]
Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.
**Example 2:**
**Input:** root = \[5,4,2,3,3,7\]
**Output:** false
**Explanation:** The node values on each level are:
Level 0: \[5\]
Level 1: \[4,2\]
Level 2: \[3,3,7\]
Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.
**Example 3:**
**Input:** root = \[5,9,1,3,5,7\]
**Output:** false
**Explanation:** Node values in the level 1 should be even integers.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 105]`.
* `1 <= Node.val <= 106`
|
Do a simple tree traversal, try to check if the current node is lonely or not. Node is lonely if at least one of the left/right pointers is null.
|
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
563,1005
|
368 |
hey everybody this is Larry this is day nine of the Le Cod daily challenge hit the like button hit the Subscribe button Joop me on Discord let me know what you think about this one and of course I'm going to do an extra PR after this I think so uh definitely check that out oh huh have to reset but uh hope everyone's doing okay it is almost Friday or is Friday depend on when you're watching it or when I'm recording it uh don't that part I should know but uh yeah so hit all the buttons and hope everyone's doing okay with the weekend coming up another week right um yeah a little bit of a health update nothing bad I swear because I've been just talking about my heal a little bit because that's just been what I've been interested in this is a little bit of like a relog so maybe I could watch it in the future and be like Oh Larry is an idiot that day but uh but anyway I did get a continuous Goose monitor so this thing does that show up this thing on my arm so um so I could check my track my glucose level after I eat certain things first thing I learned is that uh Korean food has a lot of sugar in random places or maybe just eating out in general but definitely the Korean place that I went to so uh that's the problem of being old is you have to make decisions about not eating as much or not eting some things cuz I'm still trying to bulk so I'm going to eat a lot anyway uh just a random update definitely if you have any questions about that let me know in the comments or come to Discord and you know you could follow me as I kind of talk about that journey I don't I mean I'm not a fitness YouTuber but in case people are curious because I was curious about all these things and I was just looking it up a lot the last couple of days um anyway let's take a look at today's Farm sorry for the intro uh 368 largest large largest divisible subset given distinct positive IND nums we turn the largest subset anwers such that every pair ANW of I ansers of J of elements in the subset satisfied okay cool I mean I think so the first thing I would do is I would sort right um I don't I mean maybe if we need to we could take it out if that's the um if that's the issue in the complexity but nlog in is not an issue and given the N is a thousand not going to worry about it and then now the reason why we do it this way is because then now instead of having this like ners I and so J thing now you can have um you know you can have it in One Direction Right meaning that in this case every num sub J is going to be greater than num sub I so then that means that it has to be such that num sub J by nums of I is equal to zero right so that's the first frame we want to do that's the frame of sorting that's what sorting gives us a structure that we can kind of exploit in this way right should put this right okay and then the second thing is that what happens when you add a number to a set right or subset or whatever well then now okay yeah so let's say you have you added a number you have the number a to begin with and then you added the number B and of course uh B is going to be greater than a and that how we Define it or write it like this right and that how we sort it and doesn't really matter but in this case it's just you know that order and as we said before we have B mod a is equal to zero well now what happens if we try to add C right what happens to C well C is going to be in this case I guess it could be equal to I don't know if that oh they are unique so then this is going to be the case right and it so happens then now then so this is still true of course um but we already knew that so we don't have to check for C and then we also have C mod a is equal Z and C mod b is equal Z right what does this mean right well um well c b is equal to zero is the one that we have to check well okay so what do these two things mean right together well C A is okay fine it's interesting and C B is interesting together but together you only need to know this because if C mod b is zero then this is always going to be true and if this is true then that means that um the problem is that every pair is going to be mod zero so then we only need to worry about this um I don't know if this identity I don't even know if it's an identity really um but I don't know if this is well known or if I need to kind of go over in detail I'll go over it very briefly but really I mean I think the thing that I would try to do in my head U maybe on paper if you know especially if you're newer it's just play around with numbers right for example if you have like 2 48 right then now you have 8 mod 4 is equal Z and then 8 mod 2 is equal Z well of course because for mod 2 is equal to zero the smaller part is always going to be true and the bigger part is true right um hope that kind of makes sense I know that's not a proof I'm not really good with proofs of these number Theory like maybe I don't know do some I don't know right I the proes are kind of tricky for me for or I'm not as well worth as to um like these proofs with respect to um proving it under this the Mod Space right and stuff like that but you can kind of see that and then but my point there then now is that okay now instead of having three formuls we have to check we just have to check one and we only have to check one when we remove this number right so or sorry when we add in C so that means that we only need to do one check on this so that's pretty much basically the idea and from that we can kind of say that uh if you have a subset then that subset is just going to be represented by the biggest number right because the biggest number is the number you assume that the biggest number already Mars all the smaller numbers is equal to zero or all the smaller numbers evenly divide into it right so in that case then uh oh I guess I don't know why I have struggle with this but yeah so if B I guess there is a easy proof hang god um I think I just didn't say it out loud but yeah but basically you know uh if B mod a isal zero then that means that um B is equal to K * a for some K that um B is equal to K * a for some K that um B is equal to K * a for some K it doesn't matter what so then here um yeah so then you could say that this is um mod K * a and of course if you is um mod K * a and of course if you is um mod K * a and of course if you do a multiple of a is equal to Z then this is going to be 0 zero that's basically the idea anyway about the representative number you have a big the biggest number already implies that all the smaller numbers are already fitting into it right so that's basically going to be the thing and from that we can construct um a dynamic programming solution with uh what you call it path reconstruction right um and the dynamic program solution is because each state means that um I try to do this top down because I think this uh it's I think it's worth learning path reconstruction um top down but yeah so let's just say we have I don't know get Max I don't know it doesn't really matter right Index right and we have n is equal link of nums and then the idea here is get the max number starting from Index right so then now uh this means that this number is going to be the um the biggest number right so nums of index is the biggest number maybe right yeah I think that's fine have to I mean you could yeah we need to kick it off but that's fine right if index no we don't even need a base case for this one I think yeah so best is equal to one for one number because you have this number as his own thing right and then now you just go for it so for I in range from index + one all the way to in range from index + one all the way to in range from index + one all the way to n well n minus one inclusive um we're going to if num sub I mod num sub index actually this kind of I'm just use J for um is equal to zero then now we could get Max of J right so best or this is going to be this plus one and then we just you know Max it between this and that um that's one way to do it right and uh actually I'm going to leave it like this so that we can talk about path reconstruction in another part usually I would probably just do tied it in now bit yeah and that's pretty much it so then now we just uh loop or Loop Pro force over which to St start so then you can just do like for I in range of n um best to Max best get Max of I and that's pretty much it so that's the first one to start right so PR isal zero and yeah I mean this isn't the right answer yet because um because you have to return the output and not just the number right so yeah but hopefully this uh so right now this is just Bo Forest there's no um nothing this is just boo force and of course this branches a lot so this is going to be exponential as we add in more numbers and with more numbers and exponential it is going to be very expensive and you could actually kind of do that with I guess A variation of this right just like 16 32 uh 648 I guess I think this is actually still fast enough to be honest but uh let's see yeah I guess this is still fast enough still got but um okay fine but like it branches out it's going to be a little bit slow so what are you going to do right and what you're going to do is of course dynamic programming and here uh we look at and the reason why we can do Dynamic program there are a couple of B is that uh for every input we get the same output right so yeah for every input there's no side effects so every input we get the same output so the idea I mean Dynamic program memorization the different way of saying it and there are different ways of thinking about it and sometimes I say it in a different way so that maybe it triggers you know you learning and thinking about it in a different way but for this particular problem maybe you can think about it as like okay well every input we get the same output we just save it down it doesn't even matter about like all these funky things about state but then you know for analysis is that okay index could go from 0 to n and each so what's the total time right um well total time is just equal to time per input times number of inputs and index uh so number of inputs is just the number of index so that's all of N and each input takes o of n times because there's an O of n Loop inside so this is going to be o of n Square time if after we cach it because otherwise this goes unbounded right so yeah so then now we add in uh the cache right and I just like writing it like this at least for uh learning purposes because it's just really easy to read you know you don't have to and very easy to figure out how many things you have to do uh I know that there are other ways of writing it and feel free to yeah still W because we haven't but you know you can see all these things and it's it matches the number of count okay so then now you go okay well that's may be useful but um but is it right uh so then how do we get the final answer right well I mean you know there's like I said there are things you can say about path reconstruction and all these things they're fancy terms but uh but for this one we can think about it a little bit easier right we just kind of keep track of well what's the best move that we can make at every thing and then we just keep track of it so then best move is equal to just go n end and then here um yeah so here maybe we could write best move of index is equal to oh I guess actually I should put it here I guess it's just none otherwise right so here um that means that now we write something like if get Max uh or so um hm so R is just the return value get Max of J + 1 if R is greater than get Max of J + 1 if R is greater than get Max of J + 1 if R is greater than best then best is equal to R right so this is the same code as before but now we also want to keep track of this so that maybe best move of index is equal to R oh sorry not equal to r equal to J right so we keep track on WE update so that best move of index gets you the best next move and that's basically all the change you need to kind of set it up right because then now here um and we have to write this a little bit different as well but uh but yeah same thing get is I right so if R is than best then you have this best is equal to R right but then now um yeah and then maybe you could like just best thought is you go to none and then best St is equal to I right so then now we know what is the best uh index to start from and then now here we just walk the thing to the best moves right so here maybe I'm going to WR just a little bit sloppy and lazy to be honest and you could do this in an erative move but I'm just going to do it recursively because it kind of matches the structure of everything else right um get best move of Index right so then here uh or get next best move maybe I think maybe best move is fine right so then now we go um yeah if best move from index is not none then we get best so the then the next move is equal to best move of Index right uh we want to append it to the answer and then we want to go visit it and that's pretty much it and then now we can just return enter I mean you still have to call the function oops uh from best start and that should be good okay is what I want to say but it's not huh what did I do why am I short a little bit oh I'm we turning to I append index and not the well that's one um so we only to why am I and I'm we I'm appending the next move instead of the current move so that's a little bit silly I don't know I'm just really sloppy today um okay uh yeah we don't care about next I don't know just really not thinking okay so there you go and we'll give it a nice submit and yeah uh I've done this other ways before in the past probably irit ly uh yeah did this way um so I just wanted to kind of you know show that you can do things multiple ways and this time I did it tops down and you know did the same dynamic programming way that we did before and without all the really you know funky things about path um reconstruction you can just see that hey look we want to say what our best move is and then at the end we want to well just walk the path that you took right so yeah uh that's pretty much all I have for this one let me know what you think uh this is going to be n squar like we said and of course this is all of n because we just kind of move you know you're moving forward there's only that most end of them so that's going to be off end and of course of end space because of the answer uh and also the caching so yeah uh that's pretty much it let me know what you think stay good stay healthy to a mental health I'll see youall later and take care bye-bye let me show you and take care bye-bye let me show you and take care bye-bye let me show you actually okay the top and then the bottom all right stay cool everybody byebye
|
Largest Divisible Subset
|
largest-divisible-subset
|
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies:
* `answer[i] % answer[j] == 0`, or
* `answer[j] % answer[i] == 0`
If there are multiple solutions, return any of them.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,2\]
**Explanation:** \[1,3\] is also accepted.
**Example 2:**
**Input:** nums = \[1,2,4,8\]
**Output:** \[1,2,4,8\]
**Constraints:**
* `1 <= nums.length <= 1000`
* `1 <= nums[i] <= 2 * 109`
* All the integers in `nums` are **unique**.
| null |
Array,Math,Dynamic Programming,Sorting
|
Medium
| null |
1,625 |
hey what's up guys this is sean here so let's talk about uh this week's weekly contest problem number uh 1625 a lexicographically smallest stream after applying operations i hate this problem you know because it wastes me a lot of time on it okay sorry i'm a bit a little bit running my nose so okay so bear with my voice here guys okay so you're given like a string of even length uh consisting of digits from zero to nine okay and two integers a and b okay so you can apply either of the volume two options any number of times in any other on s okay so basically you know uh add a to all the indices of the of s okay and after adding that so you need to do a modular by 10 right basically it has to be in the between zero and nine so that's the first options you can do the second one you can rotate the stream by b okay so this is pretty fairly easy it's pretty easy to understand right so you rotate by one and then the three five three four five six becomes uh six three four five and they ask you to return the lexico to basically the smallest string you can get okay and then it gives you a few examples here you know like you can either do that and do this and then you just get the smallest one you know i spent a lot of time you know trying to find a pattern basically i wasn't thinking about the brutal force way you know i was thinking about you know there should be a pattern right something like this i mean uh let's see if we have a five here right uh seems like we can like rotate uh by rota rotating the five by nine we can make this five becomes zero okay and then after that we maybe we can do some rotate because i was something i was in that path you know and i was trying to figure out a pattern something like this and then maybe i can rotate this number until it's become to zero and then i do a row and i do a shift i was actually i was thinking about more like a greedy approach but you know what i actually waste a lot of time on it but it turns out this problem is nothing more than a brutal force a dfs basically you know at each of the state you either do a do an a operation or b operation okay and then when's the end point basically you know we just uh record all the other different ads we have seen so far right i mean until we have seen everything and then that's when we stopped we just brutal force all the possible other possible s at one state we can do two things we either add a to all the uh the odd the positions or we do a rotate by uh by b yeah so that's that you know i don't know why i stuck with that greedy approach or trying to find a pattern for such a long time anyway so that's a different story so to do that you know we can either do a dfs or we can do a stack so for this one i choose to use stack right because it's easier and it's faster right so of course we that we need to have a set scene right so that's that will help us to record all the possible as we have seen so far right and then we have a stack so at the beginning we have s right that's a starting point and then uh i define like an s here right so because you know we have answer here you know because the uh you know we're looking for the uh the smallest the lexical graphically smallest in the string here right so i mean how to compare a string here okay since it's only the numbers uh they're from zero to nine so for i just use this i just use a 9 times n basically i just uh initiate the uh the answer right the answer is though there's the maximum possible numbers right strings in our case uh which is the uh only consists of a zero to nine so now we have this and then we can simply to uh start our dfi search and in the end we simply return the answer right so and so we have a current s right so we do a stack dot pop right and then here we can simply do every time we have a we have an s here we just update where we update this as we update the answer with the current s right so that's that and then let's do our two options option one option a rather under option b and option b here so for option a here right so it's nothing more than the uh then the uh just update right so we just do a for i in range of the uh one two one to n and we the step is two right so for each of that we have a so the new c is what so we have a so the number is the current string is current s right of the i that's the current one basically we need to add these things so we have a c right equals to the uh the current as i right and then we just need to uh add it increase it by a and then we convert it back right and then we do a mod so to do that i just need to do this right basically we just need to convert it into an integer we do a it plots we increase it by a right since a is also string we also convert it to integer and then we do a module right by 10 to get our to get the new value okay and then and we also need to convert it back right so new c equals to this right so we have to convert it back to string right so i know it's a little bit uh trivial but no but that's how i do it right now we have a new us here and i just i update right i just update this to uh okay so since python the screen is immutable so i need to convert it to a basically it has a list here excuse me guys so uh yeah so i just i need to convert it to a list here so the list of i equals the new c right so that's how do we do the update now we have a new s right and the new is i need to convert it back to the string i know it's annoying right so as list okay so i mean if the new s is not has not been seen before right so then we simply add it to the stack uh new s and then we uh we do a scene dot add new s okay yeah so that's the option a and for the option b here right so it's much easier right so we just uh cut this uh stream by two parts and then we re convert we can carry them concatenate them so the uh so the first part is recording uh these we're cutting uh b number of strings from the end right and then so we do this right i mean this is like the uh a short version of n minus b here okay maybe i'll just do that so and the other side is also this right a minus b this is how we uh cut this string here so same thing here right so we can just do the same thing yeah so every time we have a new string here basically we check if this string has been set that's how we stop this so this while loop right until the stack is empty right so yeah i think we can just run it yeah so the first one is accepted let me try to run this yeah cool so it's accepted right all right so the time complexity right so i mean so in total they're like uh so it's a 100 right so it's a i mean so in total there's a only like a 10 times 10 right so that's only a 100 and then times the uh the length times n that's the total number of the complexity here right yeah so that's the yeah i think so yeah for the time complexity i think how many up how many uh different like uh we have i think that there's like a hint here so okay so since the length is even the total number of possible sequences at most uh total number of possible sequences at most this one okay so yeah so basically that's the uh the total number of the possible ads here right so we loop through everything and inside out inside of each loop here we do a for loop here okay and also this one so this is actually also a o of uh o of fn here okay so this is also often so inside here right we are we're doing like this uh n square i think that's the total time complexity yeah is it correct yeah i think that's that sounds uh sounds about right okay yeah so that's the time complexity and the space complexity is this right so the total number of is like this 10 times 10 uh time times n that's the space this is the time cool i mean i can see why white people give a lot of downloads for this problem even i did right i even i download it because i spend a lot of time trying to figure out like a better way of trying to find a pattern for this problem but anyway i didn't find it and it waste a lot of time if you guys know it there's like another none dfs or bfs brutal force way do let me know i'm very interested to know that okay cool i think that's it for this problem yeah thank you so much for watching this video guys stay tuned see you guys soon bye
|
Lexicographically Smallest String After Applying Operations
|
group-sold-products-by-the-date
|
You are given a string `s` of **even length** consisting of digits from `0` to `9`, and two integers `a` and `b`.
You can apply either of the following two operations any number of times and in any order on `s`:
* Add `a` to all odd indices of `s` **(0-indexed)**. Digits post `9` are cycled back to `0`. For example, if `s = "3456 "` and `a = 5`, `s` becomes `"3951 "`.
* Rotate `s` to the right by `b` positions. For example, if `s = "3456 "` and `b = 1`, `s` becomes `"6345 "`.
Return _the **lexicographically smallest** string you can obtain by applying the above operations any number of times on_ `s`.
A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"0158 "` is lexicographically smaller than `"0190 "` because the first position they differ is at the third letter, and `'5'` comes before `'9'`.
**Example 1:**
**Input:** s = "5525 ", a = 9, b = 2
**Output:** "2050 "
**Explanation:** We can apply the following operations:
Start: "5525 "
Rotate: "2555 "
Add: "2454 "
Add: "2353 "
Rotate: "5323 "
Add: "5222 "
Add: "5121 "
Rotate: "2151 "
Add: "2050 "
There is no way to obtain a string that is lexicographically smaller then "2050 ".
**Example 2:**
**Input:** s = "74 ", a = 5, b = 1
**Output:** "24 "
**Explanation:** We can apply the following operations:
Start: "74 "
Rotate: "47 "
Add: "42 "
Rotate: "24 "
There is no way to obtain a string that is lexicographically smaller then "24 ".
**Example 3:**
**Input:** s = "0011 ", a = 4, b = 2
**Output:** "0011 "
**Explanation:** There are no sequence of operations that will give us a lexicographically smaller string than "0011 ".
**Constraints:**
* `2 <= s.length <= 100`
* `s.length` is even.
* `s` consists of digits from `0` to `9` only.
* `1 <= a <= 9`
* `1 <= b <= s.length - 1`
| null |
Database
|
Easy
|
2335
|
645 |
welcome to march's leeco challenge today's problem is set mismatch you have a set of integers s which originally contains all the numbers from one to n unfortunately due to some error one of the numbers in s got duplicated to another number in the set which results in a repetition of one number and a loss of one number so that makes sense you're given an integer array nums now return to us the number that occurs twice and the number that is missing so say that we had this array here we can see that 2 is the one that repeats and 3 is going to be the value that's missing so we'll return a list of 2 3. all right so space wasn't a problem we could easily solve this in oven time what we would do is create a lookup or a hashmap and just look iterate through the range of 1 through n and if the value does not exist in our hash that means it's missing and if the count of the value is greater than one that means it's repeating right so that's pretty easy let's start off with that uh we'll create a lookup and this will be a counter object of nums i'll also initialize n three length of nums now for i in range of i o r one to n plus one we have two conditions if i not in lookup that means it's missing right so missing equals i and if i looked up i is greater than one that means it's repeating finally we just return to uh an array of the repeating and we miss it so this will be oven time and we use open space because of this counter object now if we just submit that and that doesn't work let's go ahead and submit it there you go so that's accepted but that's a little straightforward right could we do better than that um so if we wanted to avoid using this extra memory and try to use constant space uh what could we calculate to figure out our numbers well this part gets a little bit complicated but bear with me if we had an array like this we need to take advantage of the fact that we know everything is between 1 through n so we know what the actual array that we want is it looks something like this right now take a look at if we subtracted the sum of this number of the actual array and the expected array we would get the difference between the number of repeating numbers or the number that's repeating and the number that's missing right here we can see everything else cancels out except this 2 minus 3. so this equation is something like if we subtract the sum of this and some of that we would get the difference between the repeat and the missing number here so what that means is we have an equation sum of the actual subtracted by some of the expected would equal repeating minus missing so now we have a mathematical formula but this isn't enough because we there's very we can have a lot of answers for this we need some sort of other equation to calculate what repeat i'm missing is so what about if we got the product well we got the product of everything um we can't subtract it but we can divide it because everything else would cancel out except the repeating missing right so that in the same way would be like product act if we divided by the product of the expected this would be repeating divided by missing so now we have an equation that we can use um let's see here if we were to kind of use some math we can first calculate what missing is here and that would equal let's see this uh actually it's easier to get the repeat first repeat and multiply that by missing right now we could put this in here and what would that give us let's calculate it be sum of x get this minus 1. then i think what we could do here is we could multiply this by one just like that let's see so vector pounds i think yeah well since we can divide miss by both and what that ends up becoming is something like this actually something like this all right and now that we have this we could easily calculate our missing by just dividing this right here something like that all right so now we have this equation so let's first calculate all these sums first all right i forgot to do that we no longer need this let's get with some actual which is going to be the sum of the nums now the sum of the expected is going to be sum we don't have the array so what we'll do is just create one i or i in range of one through n plus one and we'll also do the product let me cheat a little here and use the reduce you could write a function if you like um but i just i'm going to use the function like that and the product of the expected reduce multiply this right here okay so now we have the values we need this is all oven but it's all constant space right because these are single integers so now we just we want to find what missing is we'll get this equation let's make sure i got this right and i think we need to round it and the repeat well since we are missing now it's pretty easy to calculate repeat we just get what this and we add missing so let me see if this works gosh i'm not totally sure if i got that let's see all right so it looks like it's working at some minutes and there we go accept it so this is still all then because of all these calculations in fact you can argue it's slower but we do use constant space um and it's pretty clever because we can use math now there's some formulas you can use to get the sum of the expected and the product expected as well but didn't really want to go into that seems a little complicated so yeah that's it i honestly think the first solution is fine like but if you're interested in this mathematical stuff i say take a look alright thanks for watching my channel and remember do not trust me i know nothing
|
Set Mismatch
|
set-mismatch
|
You have a set of integers `s`, which originally contains all the numbers from `1` to `n`. Unfortunately, due to some error, one of the numbers in `s` got duplicated to another number in the set, which results in **repetition of one** number and **loss of another** number.
You are given an integer array `nums` representing the data status of this set after the error.
Find the number that occurs twice and the number that is missing and return _them in the form of an array_.
**Example 1:**
**Input:** nums = \[1,2,2,4\]
**Output:** \[2,3\]
**Example 2:**
**Input:** nums = \[1,1\]
**Output:** \[1,2\]
**Constraints:**
* `2 <= nums.length <= 104`
* `1 <= nums[i] <= 104`
| null |
Array,Hash Table,Bit Manipulation,Sorting
|
Easy
|
287
|
1,552 |
Gone leave Nanda Bachchan in a fiction post They specifically for ordinary Questions and will look into its difficult situation Reduce specific Subscribe Coming to loot that we have to match towards the previous Pigmented cells in this post This definition is given between Any to you that what is saying about drying of flowers between these two, minimum between solids now them and - 4a and - 4a and - 4a that corporation to extract which ones 1234 then we hung the tail, set the fuel rods mittu from the tree side or penis tight plant in that unites With the positions are tight, so now let's go, we had just given this question, we can play poles in inflation, subscribe, so now this is because we knew that we have minimum results of these three to this recipe and these two We have to see this meaning in the option like share thank you was the seventh so and the previous situation so we saw that which of the few ones had placed the noose means we will remember by placing them on them so in this case our Answer: Our point in CR is our Answer: Our point in CR is our Answer: Our point in CR is that with such a configuration our gap in it is maximum, so we will explain like you forces, now what will happen is that if you try to subscribe then subscribe is on, so what will we do now. First of all, we will always replace the element with composite index. Now we have tried to do this, so what have we - 18 - 1383 Photo So did so what have we - 18 - 1383 Photo So did so what have we - 18 - 1383 Photo So did not tell him that one is not returning Subscribe now Yes, I would have used this here. Already, let me play it, make a serious difference, give the arrow side, now what will happen if you play it, but number valve number, I mean, I can do it, the quad core committee has to do morning press, it is from our side, so now we will play it, now look now. What is happening is that we have refined that in World 2347, what we have seen now is that they are Let's Cafe, so in that case the option means that we can keep it means till seven, what is the maximum we can post - means till seven, what is the maximum we can post - means till seven, what is the maximum we can post - 3 tats Post - 3 tats Post - 3 To try to test means that we will try to do this because from here onwards, if I put an essay on you then you will ask what matches I am assuming that you give me or you give me this for the size and this for the point. You can keep it in your purse because just because Subscribe To's Survey - An Introduction - 26 If you have knowledge Survey - An Introduction - 26 If you have knowledge Survey - An Introduction - 26 If you have knowledge then is it correct whether our song picture is still think but vibration enter walk if we will add it okay then here I click okay normal so many joints we break it so first of all what can we do can take means can do okay after the movie tank when did to loot where is our festival configuration so In that case, what did I send, man, I just sent the video, then I gap supported the notification, this is sexual exploitation, like I subscribed to it, okay, you are okay, so if what happened means like we have said that first Ms - that We first Ms - that We first Ms - that We saw that here we have subscribed to the skin, the case was clear, okay, so now we asked, what is the world tour that we have paused today, what is cricket tomorrow, so if it means that we have presented all the codes. If you do this then this is a boiled configuration and it will keep migrating and if you bother to post the numbers and totals, this is a lesson, then its pimples will be withdrawn. If you have understood about the subject, then it means that as we have explained it, you can see it only. That even if the person fasting in front of the fast had done this, then this is the belt, so there is no need to do the ones behind it too, so you can subscribe for this How To Hum Khan Serial Recorded Na Food And Time For Defamation to in the destruction and mode of bashir is analysis and electronic
|
Magnetic Force Between Two Balls
|
build-an-array-with-stack-operations
|
In the universe Earth C-137, Rick discovered a special form of magnetic force between two balls if they are put in his new invented basket. Rick has `n` empty baskets, the `ith` basket is at `position[i]`, Morty has `m` balls and needs to distribute the balls into the baskets such that the **minimum magnetic force** between any two balls is **maximum**.
Rick stated that magnetic force between two different balls at positions `x` and `y` is `|x - y|`.
Given the integer array `position` and the integer `m`. Return _the required force_.
**Example 1:**
**Input:** position = \[1,2,3,4,7\], m = 3
**Output:** 3
**Explanation:** Distributing the 3 balls into baskets 1, 4 and 7 will make the magnetic force between ball pairs \[3, 3, 6\]. The minimum magnetic force is 3. We cannot achieve a larger minimum magnetic force than 3.
**Example 2:**
**Input:** position = \[5,4,3,2,1,1000000000\], m = 2
**Output:** 999999999
**Explanation:** We can use baskets 1 and 1000000000.
**Constraints:**
* `n == position.length`
* `2 <= n <= 105`
* `1 <= position[i] <= 109`
* All integers in `position` are **distinct**.
* `2 <= m <= position.length`
|
Use “Push” for numbers to be kept in target array and [“Push”, “Pop”] for numbers to be discarded.
|
Array,Stack,Simulation
|
Easy
| null |
480 |
So how can't you all do well? In front of you, in which we have already asked the question which is our find media in data stream, the concept of the same will be there on the user here and this is our question which is lead code quality which we are going to do now in this. Another concept is going to be created which is written in the name of our question, what does the name of the question say? Sliding window video, that is, how do we have to install the sliding window here, okay, now if we go to question 295 and see it first, then this You will understand better if you watch the video, but still I will tell you that much about thyroid, I will not repeat it again. Okay, let's go through the brieffly with the concept. Okay, so the first step is to read our question statement very carefully. Okay, so what our queries statement says is that we have to find the sliding window median. Okay, D median is a middle value in order wait list in D size of list C van there is no M value so median will be D min of that is if our It is a sorted list of inteasers, its size and is there, if we will not be able to find a middle value in it, then what will be its median, which is the min of 2 meter values? Okay, so let's see in the example, this is ours and there is another interior list of length. Gai Na 2 3 I have calculated the min and this is what will become our median, okay, and if we have an audience wait list of OD length, then the middle value will become our medium, okay, you are given and wait arms. And wait there is a sliding window size which is moving from very left to very right you can only see the numbers in the window move right by one position with in 10 to the power of -5 of the actual with in 10 to the power of -5 of the actual with in 10 to the power of -5 of the actual value will be In the accepted date mains, whatever case we have, from left to very right, we have to calculate all the medians in them and store them in an array and return them. There will be no problem with the numbers. It's okay but. You can see the example, that is, it can be I, okay, and what is each of our numbers, which is the minus integer which has a value, the integer can go from min value to max value, every number is okay, here it is K3, okay. So what will we do, the windows on the side of three will keep moving, left most sliding means left mass which is our sliding window, right, it is ours in which van three minus van will be covered. What will be its medium if I write 1 3 - 1 What will be its medium if I write 1 3 - 1 What will be its medium if I write 1 3 - 1 in sort order? Done, what is our middle value? Our van means our first medium will be this. Then we have shifted the sliding window and rewritten it in a question right. Mines Van Ministry Management In this way, you have to move your sliding window from left to right. Let's shift as far as possible and the media of each sliding window has to be stored and returned as an arrest. As you can see, this has become our arrow and I have returned this arrow in the output, okay. OK, our thing is going to work in this way, if I consider the problem as a sub-problem, one element is being added and one element is being removed, find the median of data stream, it seems that we have some limit set of numbers and some numbers come in it. As we are getting added, our median will keep changing. Okay, and just like our Windows ride is shifting, our new element is also coming out. This is an extra part of ours. These are all the things that were there. It was showing similar similarity with the question. Okay, so the thing about removal, how to handle it? Okay, so the question, once again, I am telling you in the break, what was in our question, find the median of data by streaming the question. We have got it done, you can watch its video, again and again we have the number added in our structure and in it, we had to press the medium on each stand as if one of our numbers was added, then if one of our numbers is added, then the number of our medium is added. So, in this way, as we have numbers being added, what is our problem, what is a sub problem, we should find out which is our running data stream i.e. what elements are being added, what will be the running data stream i.e. what elements are being added, what will be the running data stream i.e. what elements are being added, what will be the factor from it and how. If we can get it out easily, then what are we doing in the question? We are running with two priorities, The Next Preetiko and one of Pride. What do we store in two hours? We take all the half smallest elements and together we check the total. In which container can it go? In the left part and in the right part. If it is okay then we are sending the number in that part and after that we are balancing the size of both the pockets. In this way our question was going on. Arrow is okay. So, whatever is the number on the left and whatever is the number on the right, the left is first in priority and the right one will go to you after getting it. Okay, you are our 134. Why am I keeping it without that, let's go so that this is our max. This number will be our middle value, this will be our maximum number, not our minimum. Look, I am the one on the right, so ours is neither smaller than the number on the right, nor will it be our smallest number, that will be another middle value of ours, which we can contribute. Okay, now you will understand something, okay, if you are not able to understand something, then please delete my comment. I have made a video of the question number 295 of the code, the video will be suggested to you can watch it. First of all, okay, let me show you this thing once and for all, if we have this supposition, we have the data, I have the first number, after that there is the second number, after that there is the fourth number. After that, there is a fifth number, so I will keep adding all the numbers one by one and then I will show you how our medium will be calculated. Okay, okay, what will our next party do, the smallest half number, so what can I do for that? I will check the container on the right and there is no element in it, so I am grouping 13 in the next because there is nothing in our right container to compare the elements, hence, grouping it in the left. Can the comparison be done now? Can our thing balance? How many elements are there in the private one on the left? Van is zero in the right one i.e. if the OD Van is zero in the right one i.e. if the OD Van is zero in the right one i.e. if the OD number of elements is still in my hand then it is ok then I will give one element in the party on the left in comparison to the priority of the red one then I will handle things ok. Is N + 1 element ok and N + ok. Is N + 1 element ok and N + ok. Is N + 1 element ok and N + 1 is what ours is and N / 2 I put it in the and N / 2 I put it in the and N / 2 I put it in the right container to do some comparison in it otherwise 42 will go to our left container but now are both our buckets balanced? Otherwise, what will I do? The maxima number of the left bucket will give us the max priority. I will leave from here and put the team on the right so that we can balance both the parts and our order. Therefore, I have taken the max number from the left and go to the right. I gave it to you, okay, you came to us, you will compare yourself, it is bigger than 42, that means 53 can always be our right in the container, for now, it will go quietly to our right, okay Will Will Will you do like We can see, okay what was ours in this way, if we have continuous numbers coming then in this way I can get the video out in every moment but the left most element of the problem will also have to be removed, so how to remove, this is our There is an entry in this question. Okay, you must have understood that if I don't have any element to remove then how can I go out only at the moment. Even Watch the video which I have found, it is not date media but data stream. Rakhi has made the video, okay, so what has happened to us, more than our first week, find median in data string, most element of sliding window, then support example this will be created and this window will go, okay, so now see. You can see that as soon as we shift, we slide the window to the right, this element enters and this element exits, it goes under, we will have to remove it as well, in which way we have this second sub problem here, it happens from wherever. It will be possible for us, I am telling you step by step, now let's see how the removal is done, okay 223 We have made a video of this window, the window remains, so what do we do, we make a bucket, next video, this is our mill also, why ride? The first part gets done. Okay, so what happens in our milk. Okay, I have read that our compression will be the priority because the butt that we will see inside should not be on the top. What will be our index? The index of the highest value will be visible. I am okay that much. We have taken main and shifted it to the right instead of the highest value. Okay, so our 2nd element is interfering and what is our van element is getting deleted, so we delete the van element first and reduce it. What will I do to delete one element, I will see its index is zero and ok, now what will I do, I will see that till now the values are there, so I know that it is small, okay, next Friday will work, okay, our number is in the left part only. It will be found hidden somewhere inside, what will we do, I will take the number which is ours, he has deleted it, and if someone comes to our left side counter, what will we do, we will not consider it, we will call from it and remove it. Will give from our party, okay, the deleted index must have been on the top, so at some point, it will be removed from us, okay, but like our latest element is getting deleted, no, zero element is getting deleted, for this window, so I am that. I would like to consider in which part it will be. I have taken care that I have removed the element with zero index, I have zoomed it, okay, this thing is okay, I will add it in the same way which is our new element, okay, let us know. For which sliding window, how many considered elements are there in our left part, in the right part, what is the left part, what is our next part, in the right side and how many elements are there in our right part, which is valid, like we have any invalid number which is going to be auto closed. I am deleting it, I will check you from where it should be deleted and I will decrement the size there, I will zoom it by one, I have deleted it, what will I ever do to you, zero element means not zero element which Also, our deleted index would have been on the top, whenever there is any price, remove it from there, I will go, I will not consider you, it is okay in the medium, this approach is going to come, okay, the next particular is the top element, and the index number is smaller than our The required index number is taken from the left side, it is decremented, it is equal to the number of the top element, that is, the number of the third index is equal to the number of our second index. I will send this element from you to the right, we have deleted it. Which of the following is made, then what will be the size of the right one? It will be 2 now. But now you will say that this thing is not in balance, okay, so what will I do? Okay, whenever I have to transfer something from the right to the left part, then its I will give the smallest index, the smallest possible index of this number, so here one of Indias out of 2r 3, so what will I do, you will give it, okay in this case, okay, tomorrow will be different from here, yours will come here, any number here means it is okay in a way, my example. We have Hey Hota Ki Tu is fine So I see, okay now what will be the new Sterling Sliding Window, this one will be one, it will be shifted to the right, okay, so our new limit is somewhere there. Neither has to come anywhere and this element on our left has to be deleted somewhere so I will check our 0 index which is the element which I delete if we have elements of both of them meaning that the particular in which is our next particular or its. If both the top elements are there then they are indexed by their numbers. If we compare the elements then how should they be compared? The one with higher index is given priority in the next party, the one with lower index is given priority according to the variety. If you give it, then I will keep it in sorted order for the value. Okay, you have to keep this thing in mind. Okay, what will happen with this? Now I have compared both, discuss whether it is less than or equal to the value of the top element. I will decrease the size of the left one. Okay, so what will I do? Okay, in this way, let me show you what we have going on. Example in an example, so what we do is comparison, what will be our index of maximum or largest element and our top element will be the smallest element. Na, his index is fine, so what will I do? Yours on the right is A. 2 3 is less than the value of the top index. Now I will check the balance. How to balance things because I will remove his element and put it here, then I will. Their top element, which is there, I make the medium of both the pads and store them in this manner as if the procedure is going to be there. If you don't understand or still don't understand then you can reduce it by one. Listen to one thing carefully again and try. Today we are taking San of which element pollution will be being deleted and the case in which it is from our top elements, the indications which I will consider in our case, they will also be kept in our sorted order, if I suppose, my five indexes, we mean five numbers. Right, he has been on the index since three, right, he has been on the index at zero, what will I do, I will take this, I will continue to believe this thing and I am going with the assumption that I am wondering where the delicious would be coming from. And from where the marriage is taking place, I will decrement it accordingly and I will check the new value, which is the index, according to the top elements, in which bucket it is going to come, then I will insert it in that and the one on our left side and It is on the right side, I will give them increment accordingly, increment is fine, then I am recruiting in this way, so you court it, then come to us, but what will we do Okay, I have already made this, how will the two be compared? Whatever it is equal, so what will we do, in this case, we will give B minus character like the running thing, B minus, I will note the software plus index, what will be the index, what will be our idea, okay if our leftmost is the index, rightmost. That L of the current window is from zero onwards, that is, now we will have to delete the L - 1 element. We just have to delete the we will have to delete the L - 1 element. We just have to delete the we will have to delete the L - 1 element. We just have to delete the recently deleted item, we will see from where it will be deleted, now it is ok and the next part is ok, if this is what I have now then I What will I do, I will simply do it from the left side, there can be a character on the left side, what will we do otherwise then we will do it from the right side, tight size, mine, okay, I have seen both the cisees from where the recently deleted element will be deleted. Okay, so friend, after that it is also possible that there are some elements lying outside our bounds on the top, which are our current sliding window, which are outside its valid index, that is, the pride elements, who knows, they are ours. Even if the current is of sliding window, we will have to pop it because we cannot consider it. What will the settings do? Function = but small and what will we do, we will increment the right side, what will I do in the thick and thin condition on the left, what will I do on the right side element? Which one is ok great balancing so things are done now what to do now we have deleted the result of L will be Shimla we have two thing a ok this is our code goes simple ok ] Train Successful Data Stream Okay, so we can do it with the help of the question which we did earlier Find Median in Industry in this way, friend, we are doing this question, you must have understood and still not. If you understand then please remind once and see, you will understand for sure and do your practice well, okay and till then
|
Sliding Window Median
|
sliding-window-median
|
The **median** is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle values.
* For examples, if `arr = [2,3,4]`, the median is `3`.
* For examples, if `arr = [1,2,3,4]`, the median is `(2 + 3) / 2 = 2.5`.
You are given an integer array `nums` and an integer `k`. There is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position.
Return _the median array for each window in the original array_. Answers within `10-5` of the actual value will be accepted.
**Example 1:**
**Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3
**Output:** \[1.00000,-1.00000,-1.00000,3.00000,5.00000,6.00000\]
**Explanation:**
Window position Median
--------------- -----
\[**1 3 -1**\] -3 5 3 6 7 1
1 \[**3 -1 -3**\] 5 3 6 7 -1
1 3 \[**\-1 -3 5**\] 3 6 7 -1
1 3 -1 \[**\-3 5 3**\] 6 7 3
1 3 -1 -3 \[**5 3 6**\] 7 5
1 3 -1 -3 5 \[**3 6 7**\] 6
**Example 2:**
**Input:** nums = \[1,2,3,4,2,3,1,4,2\], k = 3
**Output:** \[2.00000,3.00000,3.00000,3.00000,2.00000,3.00000,2.00000\]
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `-231 <= nums[i] <= 231 - 1`
|
The simplest of solutions comes from the basic idea of finding the median given a set of numbers. We know that by definition, a median is the center element (or an average of the two center elements). Given an unsorted list of numbers, how do we find the median element? If you know the answer to this question, can we extend this idea to every sliding window that we come across in the array? Is there a better way to do what we are doing in the above hint? Don't you think there is duplication of calculation being done there? Is there some sort of optimization that we can do to achieve the same result? This approach is merely a modification of the basic approach except that it simply reduces duplication of calculations once done. The third line of thought is also based on this same idea but achieving the result in a different way. We obviously need the window to be sorted for us to be able to find the median. Is there a data-structure out there that we can use (in one or more quantities) to obtain the median element extremely fast, say O(1) time while having the ability to perform the other operations fairly efficiently as well?
|
Array,Hash Table,Sliding Window,Heap (Priority Queue)
|
Hard
|
295
|
1,190 |
hey everybody this is Ben and welcome back to another Elite code video and today we're going to be looking at problem 1190 titled reverse substrings between each pair of parentheses we will read The Prompt we'll talk about the pseudo code we'll walk through an example and then we will type a code up a solution together so you are given the string s that consists of lowercase English letters and brackets reverse the strings in each pair of matching parentheses starting from the innermost one your result should not contain any brackets so basically for each set of parentheses let's look at this example here we need to start the innermost parentheses first and we need to reverse the substring within those parentheses then we'll clear that so we'll clear the parentheses as well and we'll insert that into our string and then we'll evaluate the next pair parentheses so on so forth that looks a little bit confusing but when we talk through an example it will be much more clear let's go ahead and talk about this problem a little more in depth so we need to reverse a substring found within any set of parentheses there could be parentheses within parentheses which complicates the issue I'm going to fix that typo however the approach here is simple whenever we hit a closing parenthesis we need to reverse the current substring which are all characters before the closing parentheses up until the opening parenthesis so how can we store the data a stack will work well for this problem so we can Loop through the given string s and push each character into the stack however if the current character is a closing parenthesis then we will not push that character instead we will create a new string Builder we will pop all the characters in the stack stopping once we hit an opening parenthesis and append these characters to our string Builder we will then call the pop command an additional time to remove the opening parentheses from our stack then we'll Loop through our string Builder from the beginning pushing each character back into the stack so this represents our reversal process of that substring this will be more clear when we walk through an example once we have looped through all the characters in string s we will pop every character from res and append it to the string Builder from our stack excuse me we'll pop every character from our stack independent to the string Builder we will then return this as a reverse string so let's go ahead and look at the sudo code here first we'll initialize a stack we'll use a for Loop to walk through every character in string s now we'll set a character temp equals the current character at I if temp equals closing parentheses create a new string Builder while the stack is not empty and stack.p does not stack is not empty and stack.p does not stack is not empty and stack.p does not equal opening parentheses so stack.peak will opening parentheses so stack.peak will opening parentheses so stack.peak will look at the top character of the stack without removing it then we'll append stack.pop which then we'll append stack.pop which then we'll append stack.pop which removes the top character to our string builder for each iteration once our while loop is over we'll go ahead and say end while loop here for clarification well go ahead and call stack.pop one well go ahead and call stack.pop one well go ahead and call stack.pop one more time because this will remove the opening parentheses as we have no need for it now because remember we were testing this while loop with a parameter of stack.peak it doesn't equal of stack.peak it doesn't equal of stack.peak it doesn't equal that opening parenthesis now we'll say 4 in J equals zero J less than string Builder dot length and increment J by 1. we'll go ahead and push the current character J back into our stack so this is adding the characters back to the stack in a reverse manner now if our character temp does not equal a closing parentheses we simply push the character into our stack and our for Loop create a new string Builder while the stack is on empty we just append stack.pop to string Builder so the top stack.pop to string Builder so the top stack.pop to string Builder so the top element gets added to the string Builder and then we'll have to return our string builder in Reverse as a string as our final answer so this can be a bit confusing let's go ahead and walk through the example together so we'll say the given string s is parentheses U parentheses love closing I closing parentheses we'll go ahead and initial initialize character stack as t now 4 in I equals 0 I less than s dot length I plus let's walk through each of the ratio of our for Loop when I equals zero character equals opening parenthesis that's our zero if character and this does not equal closing parentheses so we push it to the stack and as you can see this represents our stack and the arrow is pointing to the top I equals one character is U that does not equal closing so we push it now we have parentheses and then U is on top I equals two opening parenthesis same thing this if statement doesn't catch so we'll go ahead and push it now we have this here is our stack with this element as the top I equals three character T is L if statement does a catch else push it to the stack I equals 4 character equals zero equals oh excuse me if statement doesn't catch so we'll push it to the sack which as you can see o is now the top element next character is V this doesn't catch go ahead and push it to the stack now characters e it's false again pushing onto the stack so e is the top element and this is our full stack now when I equals seven a lot of typos on this one will find a closing parenthesis our current character so now that if statement's going to catch so we'll create a new string Builder SB and we'll say wow stack isn't empty and stack.p say wow stack isn't empty and stack.p say wow stack isn't empty and stack.p does not equal an open parenthesis because this will terminate when the top character of the stack is our open parentheses that's what we want to stop because we know we found all the character the alphabetic character values in our substring that we need to reverse so for the first iteration we pop the top which is e now our stack is this and we append e to our temporary string Builder second iteration we now get V and this is going to be o and this is going to be l so we pop V this is now our stack we add V to our string Builder third iteration o here's our stack go ahead and add it next is L go ahead and add it pretty simple process there so our string Builder is Evol which is reversed from what it was as our input so keep that in mind and we end our while loop we call stack.pop to remove the open parentheses stack.pop to remove the open parentheses stack.pop to remove the open parentheses that is currently the top as you can see because we have no use for it anymore now this is our current stack with u as the top element we have a for Loop here to iterate through our temporary string Builder now when J equals zero the zero if character is e so we're going to add that back into our stack and this is our reverse manner that we're talking about we need to add it back to the stack and then this technically those elements we just worked with get reversed again in the next set of parentheses since they were an inner set of parentheses so e is now the top element push v is now the top element push o is now the top element push l is now the top element and the for Loop now go to I equals seven character is I does a catch go ahead and push it so here's our current stack I is eight our characters are closing parentheses and this is our last character of our whole string so if the character is a closing parentheses which is true again we create our string Builder we'll iterate through our stack until we hit an open parenthesis so first iteration we pop I this is our current stack and we add I to our string Builder we just do this so on so forth until we hit that open parenthesis so we're going to end with a stack that just has an open parenthesis and our string Builder is going to be I love you and while loop go ahead and pop one more time removes that open parenthesis so now we have an empty stack now we use a for Loop to re-push these now we use a for Loop to re-push these now we use a for Loop to re-push these elements from our string Builder into our stack so at J equals zero the first character versus string Builder is I or zero with character so push that to the stack so on so forth until we get to our last character U now our stack looks like this I love you which is technically an order now what we're going to do and our while loop and we end our total for Loop now we create a new string Builder result I call it res for short while the stack is not empty we append a stop so we're adding from the back so we're going to add U first then e then V so on so forth so our result now equals this then we'll return this reversed and to a string so we get I love U which is the correct answer so let's go ahead and code up a solution together so we'll start by creating our stack of character form equals new stack I'm just going to call this St we'll say 4 and I equals 0 I less than this dot length I plus and we'll say character T you know our 10th character equals s dot character at I if T equals a closed parenthesis we'll create a new string Builder SB and we'll say wow our stack is not empty and our stack Peak does not equal an open parenthesis and this likes to auto fill in a weird way sometimes then we'll go ahead and append a stop hop or St dot pop now we'll go ahead and call pop one more time this will remove the open parentheses that's going to be left we'll say 4 and J equals zero J is less than SP dot length J plus we'll go ahead and push that character back to the stack with that right there and that should be good for that top Loop now we'll say else referring to our initial if statement we'll simply push our character T if it doesn't equal a closed parenthesis now once this terminates well I'm a new string Builder called res go ahead and build that here and we'll say wow our stack is not empty I will append the pop the top character through St dot pop then once that terminates once our stack is empty we'll return res dot reverse dot to string let's go ahead and run the program hopefully I have no typos in here and I do have a typo like spell that correctly and try again and that's going to work so let's go ahead and run our test cases that works for all our test cases even test case 3 which has a lot of nested parentheses and we'll go ahead and submit the program and that's going to get you it should get you a little faster I'm not sure why it's running slower at the moment my best time with this one was about six milliseconds 42 megabytes which is a lot better percentage-wise than these so better percentage-wise than these so better percentage-wise than these so this is just one solution I came up with feel free to suggest your own work on your own I hope you learned something here and have a great rest of your day
|
Reverse Substrings Between Each Pair of Parentheses
|
smallest-common-region
|
You are given a string `s` that consists of lower case English letters and brackets.
Reverse the strings in each pair of matching parentheses, starting from the innermost one.
Your result should **not** contain any brackets.
**Example 1:**
**Input:** s = "(abcd) "
**Output:** "dcba "
**Example 2:**
**Input:** s = "(u(love)i) "
**Output:** "iloveu "
**Explanation:** The substring "love " is reversed first, then the whole string is reversed.
**Example 3:**
**Input:** s = "(ed(et(oc))el) "
**Output:** "leetcode "
**Explanation:** First, we reverse the substring "oc ", then "etco ", and finally, the whole string.
**Constraints:**
* `1 <= s.length <= 2000`
* `s` only contains lower case English characters and parentheses.
* It is guaranteed that all parentheses are balanced.
|
Try to model the problem as a graph problem. The given graph is a tree. The problem is reduced to finding the lowest common ancestor of two nodes in a tree.
|
Array,Hash Table,String,Tree,Depth-First Search,Breadth-First Search
|
Medium
|
235,236
|
1,870 |
hey everybody this is Larry this is Day 26 of the liko daily challenge hit the like button subscribe button join me on Discord let me know what you think about this from 1870 minimum time to or minimum speed to arrive on time oops uh yeah hit all the good buttons let's see what this problem's about okay so you're giving the phone number our representing the amount of time you have to reach the office to commute to the office you must take n trains in order sequentially you guys are given an individual way distance or test of length and where the sub I describes the distance in kilometers of the if train ride so R is a floating point okay people don't these days don't really are not as familiar with floating pointers I feel like when I was younger uh there was a lot of like numerical analysis type problems where you better learn floating points but uh but oh well maybe it's for the best okay each train can only depart at an integral so you may need to grade in between each train ride for example first train why it takes 1.5 hours you first train why it takes 1.5 hours you first train why it takes 1.5 hours you must win an additional 0.5 hours okay must win an additional 0.5 hours okay must win an additional 0.5 hours okay return to minimum positive integer in command kilometers per hour that all trains must travel for you to reach the office on time or negative one if it's not possible test cases that generate such that is not too big an album have almost two digits after the decimal point bombs like this is kind of um a little bit disappointing um not the prime itself but I feel like it's kind of almost like a wasted opportunity because they keep on having they uh day being neat code keep on insisting on these theme weeks right or team chunks anyway maybe it doesn't have to go for a week um with respect to like yesterday's Farm is a binary search so like well you know it's a good idea in the sense that you're getting um getting practice on the same field but you definitely missed out a bit on practicing on recognizing the problem type right and here you know recognizing that as binary so just have to work well maybe even more I don't know right um but some portion of the work um and here like I'm kind of primed and in a way cheating about it without even looking at it but uh okay that said I still I read this form to Yao I still have no idea what it's saying and actually so let's take a quick look at some examples okay so I will always the total hour you have to reach the office uh each train only leaves an integer hour okay it's okay so all the trains have to move at the same speed okay uh okay so I mean I think this is just simulation on binary search basically if um you know you binary search for a given time or sorry given speed and if the speed gets you there faster than six hours well we're trying to maximize or minimize or whatever oh the minimum possible speed yeah so if for example if you could have trains that travel a million miles per hour um you know that'd be fast but of course you're trying to minimize the speed itself right so yeah so that means and just using that example if you have a million uh let's say kilometers miles I don't remember I'm American so there are a lot of miles in my uh in my terminology my so uh yeah uh okay but you can kind of think of it out right so at a million miles per hour uh I said again but whatever a million kilometers per hour um you know you can definitely go everywhere I mean negative one because you have to run up to the hour so it has like more than six or seven stops or whatever it is then you can't get there no matter what but yeah so in theory if you do like a million miles per hour um then it is going to be possible right um minus the train stop stuff uh and you could probably just like do an if statement it out it's probably right uh otherwise and they also tell you that dancer would not actually tender seven so you could probably even do that but uh but otherwise uh yeah and then you kind of think the other way right where you go like a slug like almost zero but not zero so like one over a million uh miles per hour uh then this is gonna take forever and of course you're not gonna get there on time so basically in between there's some uh number in which you get that exactly six hours or like maybe what maybe not exactly because of the way uh you have to round up between every stop but you know as uh as close as possible to six without going over like almost like prices is Right rules so that's basically the idea um because I think uh this one's just exactly but yeah you have six to do right so yeah so that's basically the idea and I feel like I regularly I don't know if it's this one or a very similar problem or Nico where people were just having a lot of issues with floating points and decimals because rounding out because it's not even that this problem has floating points it's that there are a lot of places where you can introduce floating Point errors with respect to the rounding up right um because for example if you go here and you arrive to the third station or second station or whatever like if you get there at you know if you're traveling at a speed that's 0.33333 then traveling at a speed that's 0.33333 then traveling at a speed that's 0.33333 then maybe it's a little bit under if it's three four maybe it's a little bit over but then you have to round up but then maybe there's some like rounding error and a lot of places of error and I think as a result of that a lot of people including me uh kind of got a wrong and I think maybe that's why I haven't seen one in a long time because I think this one was a mess I mean that said there are correct ways to write by uh floating Point problems but if you're gonna do like random discrete stuff that's like binary with respect to an arbitrary thing that makes it very hard to be 100 precise um you know then probably you're not a very experienced Prime Setter in these kind of problems or me or you know you're looking for someone to solve it in a way that is an uh idea because they're also like an order of operation stuff with floating points right um and basically you're trying to in a way reproduce the exact error of thing that the solution is given um ideally what you actually want to do you really want to be precise with these things is using fractions instead but you know uh these things are kind of tough and tricky right because even this number right you say hours you go to 2.7 number right you say hours you go to 2.7 number right you say hours you go to 2.7 well what does that mean uh well it turns out that 2.7 cannot be represented turns out that 2.7 cannot be represented turns out that 2.7 cannot be represented precisely in binary right and therefore it is not it is also not uh being able to be represented precisely in the floating point right so uh yeah so even the in theory the input is not exact they say it's 2.7 input is not exact they say it's 2.7 input is not exact they say it's 2.7 because it's round two 2.7 but the input because it's round two 2.7 but the input because it's round two 2.7 but the input is actually not 2.7 technically is actually not 2.7 technically is actually not 2.7 technically depending how you want to Define floating point and how you want to uh you know how you however you want to you know just Define these things right um in fact 2.7 I believe and I could be um in fact 2.7 I believe and I could be um in fact 2.7 I believe and I could be wrong about this one uh please check me 2.7 is a as a repeating decimal in uh in 2.7 is a as a repeating decimal in uh in 2.7 is a as a repeating decimal in uh in binary right um in fact I guess most things are right but uh so um so yeah I mean and you can think about this in terms of just like you know seven Dollar by uh yeah I mean you could do there's a lot of literature on how to figure these things out uh I'll let it up to you to kind of Google these things but I think that's my big rant about these kind of problems uh I'm gonna take a peek to see if it was this one yeah that's why I got uh huh that's weird I mean I think I don't know if this is true but I think I probably got it right during the contest and then they rejudged it or something um if I have to guess and then I just submitted the week after maybe uh yeah I mean I guess I kind of cheated but right now but I mean I didn't look at it I just kind of looked at the input but yeah so as you can see there were a lot of controversy about it mostly because uh all the a lot of the things that I talked about here um and that is to say um that is not to say you know I mean everything with a lot of things where you kind of you know um engage with the margin of error and stuff like this right um like at most two deaths more two digits after the decimal point is not even like precise right and technically speaking it's not even super possible unless you happen to have like power of halves right so um which is basically not true for and you know anything not a quarter or a fourth sound but in any case yeah um that said I don't want to scare anyone about or away from using floating points in the normal things um it's just that you know like in physics and another um disciplines there are these things with like margin of error and then you calculate your air resources and then you calculate how this error accumulated with each operation and then just try to do all these things to kind of make sure they're within bounds of what you expect the errors to be right um in this particular case there's no Nuance with stuff like that so uh and in fact they did the opposite in that there's like random binary e you know round up around down given though it could depend on your order of operation with respect to you know um I don't have one of my head and you know these days I used to kind of have all these examples to kind of because we used to when I was younger on ACM and stuff there used to be way more of these floating Point things but there are things where like if you add like they're like just like all these arbitrary rules like oh you should add before you divide or the other way around I don't even remember I think you're supposed to add before you divide but stuff like that where it's just from years of experience of known to kind of minimize the error and knowing which order of operation will minimize the error and then kind of look through it that way right um and you kind of you know uh like I said right like you know one plus one over dream uh is not the same as one over three plus one over three uh in terms of what you get and if you're gonna ranked up around them um you know that is not gonna be uh you know um but that said like I said this is not a problem with floating points it's a problem with knowing your tools and using them right if you know that you have to be precise then you don't use floating points so you don't blame it on floating points use factions or something like this uh and yeah and if you do use floating points and if you specify the problem such that it should be exact but you use voting points well you know that's on the prom Center anyway all right I spent 12 minutes renting about uh floating points hopefully uh hopefully this is kind of interesting at least or if not you fast forward to the point that you kind of want to solve the problem and uh yeah let's actually get started right so we they say that it's not going to be 10 greater than ten over seven I don't know how many errors I'm gonna get but basically this is as I said binary search so we start at the slowest speed which is maybe um let's just say one over ten to the seven why not but foreign because you shouldn't divide by zero that's why so I think this you may still get infinity I don't even remember anymore but yeah let's just say like and then now we can do um you know uh this kind of arithmetic uh and in by in floating points binary search is the same idea but there are minor differences with respect to the inclusive exclusive um as you can imagine because of um because like I said uh with respect to the floating point it doesn't really matter you know you do less than or less than equal to because four purposes is you know if your marginal error is smaller than you know whatever the bouncer then you need to do something more specific anyway right and same idea is that you don't really and in that way it is a lot easier um but you know yeah so anyway so if good of mid um and here good what's good I mean I name things good a lot but good it means that we can get to the office on time so if we could get out to office in time we want to try a slowest speed right um so we want to try a slow speed we want to move things by chopping off the faster half so we can do right is equal to Mid otherwise left is equal to Mid note that you don't have to do like a plus one type thing because for most purposes they are gonna you know after and there's another thing that you can do if you worry about stuff or I don't know about worrying but just like another hack that sometimes I do um because I don't know some maybe this can infinitely Loop if you're doing something really silly like it never converges so another thing that I would consider doing is actually just running it um like some oops some amount of times right uh and why does this work well I don't even know I mean you could even do a little bit bigger maybe if you really want to have a use of mine but um if you use 100 elevation that means that we have the distance a hundred times which will fit for everything up to two to the 100th um of course it's not quite that because you're not starting from one or you're not selling the two to 100 and you're going down to one you're starting to from uh 1d7 to some like small fraction but that's where you have to do some maths about how to get a precise number if you want for my rule I've done 50 100 is big enough for most cases um but like I said it depends on the actual problem and in this one I wouldn't worry about it that much right um but yeah and probably like the last like 50 Innovations don't do anything really but you know it usually doesn't matter that much with in competition time uh and of course maybe on interviews you should discuss that a little bit but yeah and then otherwise and then we return to speed okay uh yeah so uh so in this case afterwards left is going to be you go to write roughly speaking minus rounding out or whatever so um so yeah so then we can just return left uh unless that you say left is greater than oops 1g7 then we return negative one because this is just impossible let me just we just keep on going to the right we just keep on trying to get a faster speed and they tell you that it cannot be over 10 to the seven right so yeah write the good function uh yeah so the current Target um and this is the pro that hopefully we don't have to spend too long on but yeah let's actually rename the speed and then okay so for D and distance um so the current time as you go to zero upon zero I suppose um yeah so the current time we have to actually seal it um because this isn't the last stop right and then we add uh d over the speed of a distance or distance of his feet man I am very bad so if you have 60 miles and you're going 30 miles per hour that's 60 over 30 for two hours right so this is the uh okay uh yeah speed right and yeah and then now we just return with current is less than or equal to hour um I mean you can do some like Airway margin is stuff here but okay what are we doing here is this actual wrong answer or what like I think I probably submitted not knowing whether this is going to be right well or whatever I mean you could even make a thousand if you want I don't think that changes anything though see it's just maybe a couple a little bit but like that's not going to converge anymore um what do they want us to do like is that an actual wrong answer or is it just like the because I don't know that this is the server telling you is wrong answer or the server is just returning things and then it's come doing a comparison right it's hard to tell I don't remember how they implement it but let me give a submit and then see if that works and then we'll um you know we'll gauge from that it's gonna be too slow because I did a hundred that would be a little weird we don't really do anything else yeah okay so it does give me the wrong answer uh on the I guess this is the input um we're supposed to return the phone oh no reason we're turning ends I think I lied then did I lie on this one I don't be supposed to return ends on this and also like if we're supposed to return ends integers field okay I missed the integer part uh so okay so I lied about a bunch of stuff but okay I mean that's not terrible we'll figure it out I mean I guess then now we have to kind of keep uh right in the drill version this is very awkward though I did misread this uh but still right uh what am I doing oh yeah all right um then now we have to be a little bit careful with this um but hopefully that was a learning thing I think I just I mean I definitely misread it obviously because I returned a different data type but hopefully that still makes sense so we could get into the office and time damage that mid is good the mid is good then we run this to be mid and then otherwise mid is no good so we want this so this should be Gucci um this isn't enough I know I'm just going to run it real quick to see yeah please they tell you that sometimes and I'm like this is the fifth time of me seeing it I don't need that okay um okay so basically it's because of this CEO now that we changed it right so now we want to do uh we have to convert this to um how do we do a rounding but only on the last Focus I think I just try to you know not uh we'll just take the last one and then here we do uh so do we round up here except for the last one so then now current um plus float of uh the last element um vote of speed yes just an hour and you can kind of uh it's a little bit and by a little bit I mean a lot yucky but we'll see how this goes uh oh did I not return it oh I guess I use the same thing that's why so it should be um but yeah all right let's try again we'll see if that's a little bit better I mean it should be better because we're now integer and looks like this time we're good um how did I don't know if they re-changed how did I don't know if they re-changed how did I don't know if they re-changed the thingies so I don't know how I got it one last time what did I do uh yeah I mean I guess this time I did okay but what's the wrong answer one so this is the wrong answer one right and I can't even you know like how what did I change to uh I guess we did some maths but like it's weird that this is not accepted and this would actually be accepted because it's the same formula right except for that I actually I don't know I just kind of moved to data by speed to the other side so that's kind of very sad actually uh and during the contest seems like during the contest I did the same thing so um I don't know very weird I don't know what to tell you all about this but hopefully my rent on voting points and stuff like this makes sense uh and hopefully we all learned something uh I learned that I'm an idiot but yeah um anyway that's all I have for this one let me know what you think stay good stay healthy to good mental health I'll see how late and take care bye
|
Minimum Speed to Arrive on Time
|
minimum-speed-to-arrive-on-time
|
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride.
Each train can only depart at an integer hour, so you may need to wait in between each train ride.
* For example, if the `1st` train ride takes `1.5` hours, you must wait for an additional `0.5` hours before you can depart on the `2nd` train ride at the 2 hour mark.
Return _the **minimum positive integer** speed **(in kilometers per hour)** that all the trains must travel at for you to reach the office on time, or_ `-1` _if it is impossible to be on time_.
Tests are generated such that the answer will not exceed `107` and `hour` will have **at most two digits after the decimal point**.
**Example 1:**
**Input:** dist = \[1,3,2\], hour = 6
**Output:** 1
**Explanation:** At speed 1:
- The first train ride takes 1/1 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.
- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.
- You will arrive at exactly the 6 hour mark.
**Example 2:**
**Input:** dist = \[1,3,2\], hour = 2.7
**Output:** 3
**Explanation:** At speed 3:
- The first train ride takes 1/3 = 0.33333 hours.
- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.
- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.
- You will arrive at the 2.66667 hour mark.
**Example 3:**
**Input:** dist = \[1,3,2\], hour = 1.9
**Output:** -1
**Explanation:** It is impossible because the earliest the third train can depart is at the 2 hour mark.
**Constraints:**
* `n == dist.length`
* `1 <= n <= 105`
* `1 <= dist[i] <= 105`
* `1 <= hour <= 109`
* There will be at most two digits after the decimal point in `hour`.
| null | null |
Medium
| null |
7 |
so uh we are going to uh understand one interesting question if you have given one integer suppose if you have given one integer one two three and you have to reverse it how you can do that or suppose you have a minus number suppose minus 3 4 2. so you should make it the two four three so this is the problems how you are going to solve that so before that you should know the concept in Java or any other language what is the modulo or you can also say what is the remainder foreign so suppose if you divide 5 divided by two so you will get the answer 1 as an integer right because uh this one ah it will uh it will divide the five by two so you will get the 2.5 and if you take so you will get the 2.5 and if you take so you will get the 2.5 and if you take the integer it is a 2 right but if you take the modulus of 5 by 2 it will become the one right so this is called the division and this is called the modulus means after division what is the remaining is there that is the decimal right so for the better industry let me do that if you find modulus G or become so if you divide by 5 by 3 so you remember we get the two right this is the two so this is how the model S is work right so suppose you have the number uh 15. when you're giving the modulus 2. so obviously we become the one right because by saver it will deduct to 40 any mining is the one and suppose if you have the number 50 and if you give the modulus by 10. so of course 10 in the Mater 1 10 and then 15 remaining is the 5 right so suppose if you have the number of the two seven six and modulus 10. what you will get 270 deduct and you will get the six suppose you have this number modulus 10 you will get the 9. so you can see that after modulus by 9 after modulus by 10 you are getting the last digit number right this number is this number here so any number suppose 4 5 3 7 if you given the modulus button you will get the last number so with the help of the modulus 10 you can easily get the large digit so this Funda we are going to use here right this is the one concept and second things let me just do that for the 123 then I will I can explain you here this very easy one but we have some 80 bit complexity that I will explain you so suppose you have one two three so what you have to do suppose this is the n right one two three so what you have to do you have to check modulus n by 10 you will get the 3 right and then you take one variable suppose this is the return variable or reverse variable anything you have to make this number right but for the time being you got the 3 now you do n into n by 10. so when you do the n by 10 so what happened 123 by 10 you will get the 12 in the integer format right so now you have the both you have this large digit also and the remaining number also right so now easy you can do that so what happened that you take one integer reverse and make the reverse starting time zero so 0 into 10 0 and add this modulus value so what is the modulus value right now 3 so in the reverse you will get the 3. right again you do the same operation so now this time n become the 12 so 12 more 10 you will get the 2. and N by n ten now it will become the 12 by 10 it become the one right now again do that now this time this is the one modulus 10 is become the one and came here 32 into 10 320 first modulus 1 you become the t21 and N by n10 1 by 10 it become the zero and you got your reverse number right so you have to run this Loop until your number is not zero right then what you have to do you have to make the model as m is equal to this one and then you have to divide n by 10 so next time please you can do this operation and whatever the reverse is go to there so reverse into 10 plus M and this is the complete code by that you can get the numbers so let me see in the code then I will show where is the complexity I will explain the code because when you do the big integer number then might be this logic could not work so if you first show in the code then again I will come and explain what is the solution that so let me see that so whatever do first will you take what is the return of the reverse and take the zero and as we discuss above X oh in ah why would I use the N right so use the same n here we have to end till that n become the zero right so you have to do that and then very simple take the ah reminder or the modulus value that is n modulus 10. and then n divided by the 10 for the next timer and reverse is equal to reverse into 10 and add the M that is The Code by sample code so and we turn the M let me run this code so let me put one use case one two three right so it even it so it should work because this will be simple code and beta not return them return with those reverse because we are making all the data in the reverse right so if you see that is working I gave the one two three it become the one three two one even if you give the minus so minus will also work so if you give the minus four five something it should also work so you can see it is coming minus yeah input was a three four seven eight output is the eight seven four three that is working but problem is that suppose I want to give this number you give this number this one big number right and then to have to run it so according to I should get the nine six four six three two four three five one but see what it is coming here it is saying the wrong number why because if you see the output it is not the correct and expecting the zero because that number goes beyond the integer value so how you can solve that right so let us go to the Whiteboard so you've seen that in the code when you're using this number integer max value or the big number it was not giving digit right as per the use case as per the problem statement if you have this kind of problems or this kind of number you should return the jio but you have might have seen that you are getting the sub negative number that is not making the sense so why it is happening because what happen when this is the problem here so when you doing the reverse is equal to 10 and after multiplying by 10 if it is hitting more than the integer max value then it is giving the negative number so you have to something do here to fix the problem so suppose if I will check if I want to check that if reverse into 10 greater than and equal integer max value then we turn zero will it work it will not work because the moment you will again multiply it will go more than the integer so you have to find out a point before multiplying the 10 whether it is going beyond the integer max value or not so for that what you have to do don't these things means do not do this completion reverse into max is equal to integer max value don't configure this one instead of that you check reverse this time you make it here so if this 10 is this reverse number is greater than equal in pizza max value by 10 you should check these conditions then your code will work right so because the problem is that when you do the multi pattern it is already going beyond the integer Maxwell right so you have to give this conditions here so if this is greater or equal then by 10 then it should return the zero and same thing you have to check for the mean value also that will be seeing the code number so you have to just add one conditions here so reverse if it is greater than in a whiteboard I use the gate and equal but you have to use only the greater integer max value and one more condition if reverse is less than integer mean value if this is the case then we term 0 that's it so you have to divide it by 10 here that I forgot to write so you have to divide it by 10 and here also divided by 10. now than it truth is accepted right it is output is zero and respecting the output zero let us commit the code and see it is accepting or not he should accept because I have already tested it accepted right its accepted if you go move it you can see that is accepted ah thank you very much
|
Reverse Integer
|
reverse-integer
|
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`.
**Assume the environment does not allow you to store 64-bit integers (signed or unsigned).**
**Example 1:**
**Input:** x = 123
**Output:** 321
**Example 2:**
**Input:** x = -123
**Output:** -321
**Example 3:**
**Input:** x = 120
**Output:** 21
**Constraints:**
* `-231 <= x <= 231 - 1`
| null |
Math
|
Medium
|
8,190,2238
|
658 |
hey hello there so today we have another binary search question 658 e to find K closest islands we have a sorted array ARR and two integer values K and X we want to find the K closest elements to this X reference number the value X may or may not be in this array we don't really care the usage of X is to use it as a reference for us to calculate that different than the distance between elements inside the array with that reference line and we want to basically find that the K elements that has the smallest distance the result has been sorted order and if there is a time meaning we have two elements for a sorted array that has the same distance with this reference number X if we do have that kind of a tie and we also have to make a choice between those two numbers we would choose the smaller elements so that's sort of like on the two kind of extreme sites and if we have time we want to pick the smaller one as an example we have one two three four five the reference number is three and K is four so obviously since that the number is inside the array we would want to choose it because by choosing it the distance is going to be zero it's the smallest as possible and then looking at the two numbers on this side we have two and four both will have the distance one that's the second smallest possible distance within this array will definitely pick those two numbers so together we have already picked the tops we are missing one looking at the remainder numbers we have one outside both one and five you have a distance two with this reference number and the sense we do have a tie we want to choose one over five because one is smaller than five so as a result we will return one two three four that's the first example the second example the reference number is smaller than the smallest so it's just to show though that the reference number can be outside their rate then we choose the floor number that's as small as possible since that axis smaller than the smallest we just want to perform so the poor for solution is basically just write a code that's sort of like a translation of what this question is asking we sort the elements inside the array based on their distance with X if we do have a tie we then sort on the erase values of the elements part of itself so just throwing a customised comparator to first sort by the distance after that we sort by the array elements value then just using that doing ones source and sorting and take the top four we pretty much done with that so it's a n log in time and the other kind of situation the other solution that we do is to pretty much buy if we look at the example that we work so we first the thing we want to do is to try to find a number that's a smallest that's closest to this reference number and then we do find some kind of symmetry around that number and so the thing that we would do is to do binary search to find this number that's closest to the reference and then have a window that's rather wide with two K elements K for a left and K for right and half of that 2k plus 1 maybe kind of a window and try to shrink about window down to talk a we can you know iteratively looking at that the leftmost and rightmost inside the window and decide which way we shrink the window to be as tight as possible with exactly K numbers that if after that procedure we will end up with the K smallest air caicos assignments to this reference so apply binary search find the closest toilet inside array then form a window of size you know 2 k plus 1 ok on either side expanded to k on either side or maybe actually 2 K minus 1 since that we are sure this number is we only need K minus 1 so we can have K minus 1 expand k minus 1 on two sides and try to shrink that to K minus 1 window to be exactly K so that would be log n plus K those two are not optimal because it's only looking after the problem at a sort of a like a local level of the property so we wanted to have some kind of bigger picture about this question so there's no better way and sort of a thinking about making a plot of the array against the you know the distance of this array elements with this reference number against the index so let's say that we have a function that's just going to be the absolute difference between the array element I and X and if we plot this against I let's just make a sketch plot here so you would look like something else is starting to decrease maybe going up to even further and you know that's the case when X is within the lower bound and upper bound the minimum and maximum number inside the Ray will definitely see this kind of turning point the FI values will decrease and then increase as another example when we calculate the FI would be 2 1 0 1 2 so it's exactly the v-shape with the three here up in the v-shape with the three here up in the v-shape with the three here up in the kind of the point where we can flip to have a perfect symmetry it was the same for example here we have a slightly different one because we're kind of out having skippin numbers and stuff so let's say that we want to find K equals 3 was this problem here where the since the fi is already been plotted if we want to just take the sweet and the K dots that's as low as possible if we work on the example with K equals 3 we just take this three numbers it's a continuous sub or a continuous window inside that the original rate we just take the sweet if we want a four we move the line a little bit higher to include the one extra asterisk on the right hand side and that would be solution to k equal to 4 in which disappointment if we want to do k equal to 5 we have to make a choice between this the left hand side 1 and the right hand side 1 there they are pi in terms of Fi and since that for the questions papers we want the elements that's on the smaller side we will pick the one on the left so that's the kind of the thing so if we look at it let's say go back to the window of size three we do see that it's kind of a symmetry and we also notice the elements if we compare the elements in that sorry that's the first end we compare the first two elements inside the array and the first elements outside the array on the right hand side the this one that there is a smaller than or smaller than kind of a relationship compared to that one if we want a window of size four we moved what's right and the first time went inside this window is still smaller than the first elements that's outside the window the you know the returning substring us sub-array that's returning substring us sub-array that's returning substring us sub-array that's because if on the contrary the first time and that's outside window it's actually smaller than this one we're definitely gonna swap that by shifting the whole window towards right the by one so it's guaranteed that the first element inside the window is kind of smaller than the first element on the outside window just looking at this current example if we try to have a window that's sy1 one size larger will actually choose this one choose to expand the window towards left if I want to include this one because at this case when we looking at the first elements inside window and the first elements as outside window its equal when we have equal we want the stuff on that on the smaller side so a little bit formally if we define this kind of a relationship as a function G I which is going to be the FI its larger is smaller than or equal to F by plus K just when you look at this if we looking at the window size of 1 2 3 4 5 k equal to Phi in this problem here the GI values will be the first one would be 0 the first asterisk if we choose this to be the initial element inside the window you will be 0 we call the GI then will be 1 all the way how many elements we have towards right it will be how many ones here if we have some asterisks that's actually even higher than a dual just generating another 0 on the left hand side so this GI it's actually a sorted sequence so we can apply binary search on the GI value to find the I which is the starting location starting index for the window of size K so bye-bye-bye-bye after observing this we can just apply binary search to solve this problem entirely without any kind of a window shrinking or you know it's also much better than the you know sorting naive sorting so yeah it's just kind of after this analysis just gonna cut this off its gonna be log n minus K because the window size has to be at least the K so the upper bond is a slightly tighter but avoids login lower bond and upper bond to be array size subtracted by okay we got em value this n value is going to be the function as the I here is going to be the starting index for the window I'm just gonna put a little over here I'm gonna put that inside the binary search then we just got our compare that the mass is Fi which is the distance from the x2 array of I is smaller than or equal to we want to find the one so we're going to compare the opposite and try to bump up I so that's gonna be X subtractive fi arr and it's if it's larger than M plus K subtracted by X if this is the case that means we're looking at this two zeros here we want to increment and lower bound to be one larger otherwise we want to the upper bound to be smaller and we just return a slice of this array its vector integer from begin + l starting from L and from begin + l starting from L and from begin + l starting from L and expand words right by K positions so that's the code that try runs for some examples yeah that's a it's working and pretty fast so that's the binary search solution to this question yeah that's it
|
Find K Closest Elements
|
find-k-closest-elements
|
Given a **sorted** integer array `arr`, two integers `k` and `x`, return the `k` closest integers to `x` in the array. The result should also be sorted in ascending order.
An integer `a` is closer to `x` than an integer `b` if:
* `|a - x| < |b - x|`, or
* `|a - x| == |b - x|` and `a < b`
**Example 1:**
**Input:** arr = \[1,2,3,4,5\], k = 4, x = 3
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** arr = \[1,2,3,4,5\], k = 4, x = -1
**Output:** \[1,2,3,4\]
**Constraints:**
* `1 <= k <= arr.length`
* `1 <= arr.length <= 104`
* `arr` is sorted in **ascending** order.
* `-104 <= arr[i], x <= 104`
| null |
Array,Two Pointers,Binary Search,Sorting,Heap (Priority Queue)
|
Medium
|
374,375,719
|
35 |
Salaam Welcome, so today we have come with a new video, search insert po que, let's code it, what will be your code, first of all, you will have to declare low one webble, right from zero, after that you will have to int high equal to numbers dot length which Length is your number's ok, minus and ok, after that now here you have to run loop one, you have to give condition in it, lo one if y then lo, we have written lo if smaller or equal yes then ok then what did you do. is int mid po ay but we are finding its formula kho plus here you will give high minus low a minus low and after that here divide by y given the formula to find our mud po after that in the condition of I will give equal target mid is exactly equal if target's gut is equal then what to do return mid do ok return mid do else wise else according to the condition what do you have to do else if numbers of target are bigger than target if numbers of mid are Is bigger than the target Here we have to give all three conditions If the numers of mid is equal to the target then return mid If the numers of mid is equal to the target If the target is bigger than the mid is bigger than the target then return one minus the mid If the target is smaller than the middle, then there should be a plus in the middle. Okay, so here we will give it with a look of complexity, so here we will have to give all the three conditions for the target. What condition will we give here, which is high, it is ours, high is equal. To mid minus high which was our position there, by taking one minus from mid there, that value there is assigned to high, after that we will give the condition of else, what we are doing here is that low is equal to mid psv if our The second wise which is our second last condition is low mid plus one, if our answer is coming in low, our answer is coming here, then here the last condition is we are giving low mid plus and mid to mid plus one. Let it be done because we have given two conditions, now the last condition is what is left for us, lo mid plus one, after that now what we have to do here is that we have to give our return statement, return lo, if we do not get any of our value. If we are not able to find the index then we will return it to Lo. Okay, let's run it and see. This is your run. Lo has been compiled, it has been accepted. What was our input? Our target was five and our output was two. Expected. If it was too, then we will submit it here. If it has been submitted, then for such videos, for such solutions, subscribe our channel and definitely press the bell icon.
|
Search Insert Position
|
search-insert-position
|
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[1,3,5,6\], target = 5
**Output:** 2
**Example 2:**
**Input:** nums = \[1,3,5,6\], target = 2
**Output:** 1
**Example 3:**
**Input:** nums = \[1,3,5,6\], target = 7
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` contains **distinct** values sorted in **ascending** order.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Easy
|
278
|
1,636 |
Hello friends welcome to my channel let's have a look at problem 1636 sought a read by increasing frequency in this video we are going to share two formats of solutions based on the method of using sorting key first I'll read through the problem statement and then we do the coding at the in between which we explain the code first let's look at the problem statement given an array of integers columns short story in increasing order based on the frequency of the values if multiple values have the same frequency sort them in decreasing order so we are required to return the sorted array so here are three examples let's look at example one so in example one three appears once and one appears twice and 2 appears three times so we should have three first and then two runs first and two are lost so this is the output for this example so you can interpret the other two examples similarly so before we do the coding let's look at the constraints so the length of this nums list is small right so it's bonded above by the hundred and the elements in the list are bounded in between negative 100 and positive by hundred so still a small range so with that said we are ready to do the coding so first I'm going to write a solution by defining a callable so the starting key first I'm going to get the frequencies of the unique numbers in this list so it's collections counter so nums so for this cont dictionary the case will be the unique numbers in nam's list and the values will be the frequencies and then we can Define the Sorting K so sorting k so let's say notice that we are going to start according to the increasing a frequency so this frequency will be basically can't get item to zero so actually you can directly call cont atom so if the item is not in the cons it's going to the default to be zero and also we want to sort the numbers in decreasing order if there is a tie so we're going to use negative item so this will be the pupil let me add a parenthesis so this is the starting key so now we can call the Sorting key right I'm going to use the sort method so it's okay will be the Sorting key right now directly pass the callable to the argument right and then we are ready to return the num list so here we are doing the Sorting in place so up to now we are ready to do a check so let's first do the check it passes the first example now let's look at the generic case yeah it passes the generic cases so now let's look at another version so I'm going to copy this first two line the function signature is the dictionary and then I'm going to mark this one as we want so here in this version I'm going to directly called the sort method of the list so Norms thoughts but I put the Sorting key in the format of a Lambda function so Lambda so the atom will mapped to be uh can't get atom zero and then we have a negative atom so this is essentially the same solution as the version one but the format of calling according to function method sort is slightly different so here we put a Lambda function to the argument so now we are ready to do the return so returns nums so let's also do a check first yeah it passes the first example now let's look at generic case yeah it passes all the generic cases so I guess that's about it for this specific problem and in this video we shared two formats of solutions based on either first Define a sorting K and then called the Sorting kit and or we put a Lambda function to the argument and do the return so we does that I guess that's about it for this video thank you
|
Sort Array by Increasing Frequency
|
number-of-substrings-with-only-1s
|
Given an array of integers `nums`, sort the array in **increasing** order based on the frequency of the values. If multiple values have the same frequency, sort them in **decreasing** order.
Return the _sorted array_.
**Example 1:**
**Input:** nums = \[1,1,2,2,2,3\]
**Output:** \[3,1,1,2,2,2\]
**Explanation:** '3' has a frequency of 1, '1' has a frequency of 2, and '2' has a frequency of 3.
**Example 2:**
**Input:** nums = \[2,3,1,3,2\]
**Output:** \[1,3,3,2,2\]
**Explanation:** '2' and '3' both have a frequency of 2, so they are sorted in decreasing order.
**Example 3:**
**Input:** nums = \[-1,1,-6,4,5,-6,1,4,1\]
**Output:** \[5,-1,4,4,-6,-6,1,1,1\]
**Constraints:**
* `1 <= nums.length <= 100`
* `-100 <= nums[i] <= 100`
|
Count number of 1s in each consecutive-1 group. For a group with n consecutive 1s, the total contribution of it to the final answer is (n + 1) * n // 2.
|
Math,String
|
Medium
|
1885,2186
|
951 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem flip equivalent binary trees so we have a definition of a flip operation for a binary tree a flip operation is defined as choosing any single node in the tree and then taking the left and right subtrees of that node and then swapping them together so swapping the entire left and right child sub trees and a binary tree x is defined as being flip equivalent to a second binary tree y if and only if x can be turned into the tree y after some number of flip operations so that's what we have to determine is it possible to make these two trees equal with some number of flip operations if it is possible given the root of two trees we can return true if it's not possible then we can return false so in this first example we're given two trees tree one tree two and we returned true in this case because these true these two trees are flip equivalent why is that the case let's start at the root of both trees okay one and by the way they mentioned this uh down below in the description but basically for each value in both of the trees is always going to be unique we're never going to have any duplicate values and that's actually going to be important for us and i'll explain why in a second but for now you can see that the roots are exactly equal right which is important right because this is a root we can't flip the root we can flip the left subtree or the right subtree or anything but we can't flip the root so these two roots have to be equal so it's a good thing that they are equal so let's cross these out because we don't have to look at it anymore but now let's take a look at the left subtree of each of these nodes now the simplest case would be if the left and right sub if the left sub trees of both of these were exactly equal because technically two trees that are the exact same do count as being flip equivalent it just means that we don't perform any flips we perform zero flips and then the trees are still equal but in this case we are going to need to perform some flips because let's uh take a look at the left sub trees right we need these two subtrees to match up but they don't just look at the root value we have a two on the left and in the other tree we have a three so they're not equal okay so then we can say okay we're going to perform a flip right how do we perform the flip basically the easy way we don't actually have to modify the tree or anything but we just take the left subtree of the first tree and the right subtree of the second tree and we're actually now going to compare these two trees we can make that decision to choose these two trees and compare them right and now when we look at the values of both of these two and two they are equal right so since two and two are equal we can be done with them and now look at let's say the left subtree of both of these nodes now when we look at the left we see that they're both four that's very good because this is the case where the sub trees are exactly equal right that's the easy case we don't have to perform any flips right they're exactly equal we don't do anything they're the same and it's basically the base case right because this 4 does not have any children right so let's get rid of this we're done with this and now let's compare the right subtree and five exactly equal so that's the good thing right they're equal we can cross them out uh we continue we don't have to do a flip now you can see that seven and eight they are in uh the opposite order right so these children are going to need to be swapped right because when you look at the left side 7 and then an 8 on the left side of this tree uh they're not equal right so we have we let's try the opposite case let's try the flip case let's compare this seven to the right child over here and they're both seven so they're exactly equal so uh we did find a match right so by flipping these two sub trees they were equal and then we look at the eight and the eight these are also equal as well so we can be done with that as well basically what we have determined so far right we were we started at the root of both trees right we were trying to determine is the entire left tree flip equivalent to the entire right tree right so far we haven't determined that yet but what we have determined is the sub problem notice how we determined that this entire sub tree is flip equivalent to this entire sub true we solved that problem right we solved the entire sub problem and the reason is because this whole flip equivalent idea is a recursive definition we solved the sub problem before we solved the entire problem right so you can tell that this problem is going to be solved with recursion that's how we're going to code this up but now the question we have to answer is this subtree flip equivalent to this subtree as well if that's true then we can return true if it's not true then we have to return false right because we're asking is this entire tree flip equivalent to this entire tree so let's determine that as always we start with the root right are these two values equal three are eq three and three is equal so we can continue right we don't have to do any flips and now we look at the left child of this tree and we can look at the left child of this tree right this is null right so six and null that's not equal right so let's try the opposite case let's compare the left child of this to the right child of the six and six these are both exactly equal right and compare the right child of this one to the left child of this one these two are both null right so these are equal as well so in this case we find that these two trees are flip equivalent we just have to make one flip so then we basically determine true for the entire problem right so i hope you kind of understand the logic that we're following i didn't really talk about how we're going to code this up but i did mention that we are going to use recursion and basically we're going to use the exact same idea that i just showed you and the code is going to be pretty easy because we are leveraging that recursion okay so let's write the code one thing i just want to quickly mention before we do we were passed in two root nodes root one and root two i change the variable names to r one and r two just because it's going to make a little bit easier for us to type this out so we know that this is gonna be recursive right so what is the base case gonna be for recursion basically if one of the values is null right either of the root nodes could be null so if not root one or not root two so if either of the root nodes is null what do we want to return well if they're both null we can return true because that means they're equal if one of them is null then we return false an easy way to code that up is basically to say not r one or not r two or rather not or and not r two because if both of these are null then this is gonna evaluate to true and then we're gonna return true if only one of them is null that means that they're not equal that means this expression is gonna be false so we're going to return false you can code this up with two if statements i think if you want but i prefer just to keep it nice and short so now we know that both if this doesn't execute that means we know that both of the nodes is not null so if they're both not null what do we have to check next we have to check that both of them have the exact same value right so if the value is unequal between the two nodes then we can go ahead and return false if they are equal then we can continue that means both of the root nodes are equal so now how do we know if both of these trees are flip equivalent well now we have to check the sub trees right this is the recursive part now this is kind of the main bulk of the algorithm so how did we kind of do it at the beginning remember when i was going through the drawing explanation how did we do it well we asked ourselves right remember recursively we're doing this recursively this is the recursive step so let's call the recursive function self.flip equivalent what are we going self.flip equivalent what are we going self.flip equivalent what are we going to pass in remember the first thing i did is i compared the left tree of the left subtree of both of the nodes so root one dot left and root two dot left right i compared both of these so we wanna ask ourselves is the left sub tree are the left sub trees of both of the trees equal and are the right subtrees of both of the trees equal right if that's the case then we can return true remember basically if both of the trees are exactly equal then of course that means that we have a true right that means both of the trees are flip equivalent so i'm going to store the result of this in a variable a temporary variable basically called a so this is one right so if this is true we can immediately return true but if it's false then we're basically going to try flipping them right first we check without flipping the trees are they equal if not now we're actually going to flip them what do we mean by flip basically i'm going to call this exact same line of code i'm going to copy and paste it just flipping the sub trees around so we have root dot one from the first tree we have the left sub tree so let's now compare it from the second tree the right subtree of the second tree right we're flipping these right comparing left and right sub trees similarly let's do the same thing so if here we have root first tree the right tree from the second tree let's get the left tree so let's change this to left so basically we swapped these around now what are we going to do we want to know if either this line of code is true or the second line of code is true so basically let's return a or this right because we stored the first line in a variable called a so let's return a or this basically is it possible to make these two trees r1 and r2 equal either by not performing a flip which is the first line or by performing a flip which is the second line so i hope that this makes sense because the code is short but it's not necessarily easy to understand as you can see on the left side though this is efficient so i hope that this was helpful if it was please like and subscribe it supports channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Flip Equivalent Binary Trees
|
partition-array-into-disjoint-intervals
|
For a binary tree **T**, we can define a **flip operation** as follows: choose any node, and swap the left and right child subtrees.
A binary tree **X** is _flip equivalent_ to a binary tree **Y** if and only if we can make **X** equal to **Y** after some number of flip operations.
Given the roots of two binary trees `root1` and `root2`, return `true` if the two trees are flip equivalent or `false` otherwise.
**Example 1:**
**Input:** root1 = \[1,2,3,4,5,6,null,null,null,7,8\], root2 = \[1,3,2,null,6,4,5,null,null,null,null,8,7\]
**Output:** true
**Explanation:** We flipped at nodes with values 1, 3, and 5.
**Example 2:**
**Input:** root1 = \[\], root2 = \[\]
**Output:** true
**Example 3:**
**Input:** root1 = \[\], root2 = \[1\]
**Output:** false
**Constraints:**
* The number of nodes in each tree is in the range `[0, 100]`.
* Each tree will have **unique node values** in the range `[0, 99]`.
| null |
Array
|
Medium
|
2138
|
64 |
hello viewers welcome back to my channel i hope you are enjoying all the videos if you have not subscribed yet please subscribe to my channel and here among other friends i am back with another dynamic programming problem from lead code today it is uh the minimum path sum we are given with m y and grid filled with non-negative m y and grid filled with non-negative m y and grid filled with non-negative numbers find a path from top left to the bottom right which minimizes the sum of all numbers along its path there is a note here you can only move either down or right any at any point in time so you are only allowed to move either down or right so there are only two ways that can move so the other two possible options the left and up are not there right in the typical grid so let's go look at the example uh this is a three by three uh array so even though the description says m by n right so m and so number of rows and number of columns need not be same but in this particular example what is shown on the screen it has three rows and three columns right so as the description says we have to start the path at the top left so typically that cell is called zero cell zero throw zeroth column right and we have to reach to the bottom right so that will be the last row and last column typically right so in an m by n grid that will be called as m minus 1 and n minus 1 cell basically right so this since it is a 3 by 3 grid here so it is from 0 to 2 the cell will be 2 right so zero through first row and second row zero through first one second zero column first column and second column so zero 2 that is a cell that we have to ah find out the path and we have to minimize the sum so there are many paths possible right so but we need to find the path with minimum sum so we have to return only the sum in this case so we don't need to return the path specifically but all we need to do is just written the sum here right that's what the question asked here so ah let's try to uh solve this with the dynamic pro programming paradigm right so ah for m by and array as we talked the there are several paths possible from 0 to m minus 1 and n minus 1. so this is the top left corner cell and this is the uh bottom right corner cell so our goal is to find out the minimum sum path right so let's examine um various sizes of the grids right so if there is only one by one grid obviously there is only one thing which is starting and ending and the cell whatever the content it has that is the answer just go look at the two by two array so one three one five right so in this case there are two parts possible you can go obviously we start from the top left corner that is zero and then we go either down or right only two parts right so uh there are two possible paths one three five and one five right so uh if you add up these numbers right it will be 9 here and it will be 7 here so the answer that we are going to written is the minimum sum that will be 7 in that particular case so ah to solve this in a dynamic programming way right so we want to keep track of the sum at uh i jth cell so starting from 0 to i j cell what is the minimum sum possible from 0 to i jth cell so to keep track of the sum ending at i j itself so we will have m by and array so which is equal to the array or the grid that is given to us right so initialize ah first initialize is first row sum and first column sum basically the first row and first column we will have to initialize with their respective sums and then um starting from the cell one right uh if at all the m and n are greater than one right if it is less than one we are done ah right here right but if it is greater than 1 right then we will start with the cell 1 and you can reach 1 either from 0 1 or 1 0 right so one is typically in our example where the number five is there so you can go to five from this one or from this three right so what you need to do is you need to make the minimum whatever that is happening through those two different sides right so you need to choose the minimum of two choices here so once you choose the minimum of two choices there right so that is a minimum that is possible so finally you will continue that logic until you move uh to the m minus 1 and n minus 1 index so whatever the minimum that comes at m minus 1 and n minus 1 index that will be the solution right so let's try to follow these steps right let's try to follow these steps and for this matrix right so initially we said we are going to declare an array which is equal to m by n right in case two by two so we initialize all of them to zero zeros ah and then now we are saying uh we should fill the first one first column sum right so first row so one so that is the first element we will fill with one and then three so the sum will be if it has to reach from this to this right the sum will be four so the sum will be four and for the first column sum right 1 and this will be 1 plus 1 2 so that's what it is so we at by this point in time we filled the first row and first column sum right so now we need to fill the ah the remaining cell that is at 1 cell right here so you could come from 1 plus 2 plus whatever it is there that is 5 or 1 plus 4 plus 5 right so that 2 possible things that are 2 possible paths are there so minimum is 1 is 9 1 is 7 right 1 is nine and one is seven whatever the content that is there here plus the current cell right four plus five is nine and two plus five is seven so we will put seven as a minimum here right so this is the answer that we need to return for this array so the minimum possible path sum is 7. so let's go uh implement this idea as a full set of code right so first things we are going to initialize the sum array which is equal to the m by n grid right so we are getting the m by n m and n values and declaring the m by and array so ah we have to initialize the first cell which is equal to the grid of whatever the input grid and we initialized with that sum because that is the minimum possible for the first cell right and then we have to initialize the column sum and we have to initialize the row samples right first column and first row sum so typically you add up the values and put in the first column and you add up the values and put in the sec first row so and then we will go from the cell one right typically if you see in this three by three ah matrix right so we have filled this one three one that row and one four this is the first row and first column right that will fit so we will start the processing from this five right so that is what we are going to do so in order to calculate the minimum sum there what we are going to do is the minimum of sum of i j minus 1 plus grid of i j or sum of i minus 1 j plus grid of i j whichever is the minimum so whatever the sum obtained from here or here you add those this sum to 5 and this sum to 5 whichever is the minimum that will go in here so that is the logic that we are using sum of i j is equal to math dot minimum of ah sum of i j minus 1 plus grade of i j or sum of i minus 1 j plus grid of h any of them whatever the sum the minimum right we are going to take that and put into sum of i j so this will be executed from cell 1 to m minus 1 and n minus 1 cell so finally whatever you the sum that we obtained at the m minus 1 and n minus 1 cell you are going to written it so let us go look at the time complexity for this algorithm right so here this for loop is going to take ah order of m and this also is going to take order of m so order of m plus order of m so it will be still order of m so this will be order of n so order of m plus order of n here right and this one we will be executing these two this loop is order of m minus 1 into order of n minus 1 so ah since we are just trying to subtract minus 1 from m and minus 1 for n right when n m and n are typically large m minus 1 into n minus 1 it will be equal to m and n m into n right so we would say the complexity for this ah code is order of m n so overall if you add up order of m plus order of n plus order of m into n right so it which will be equal to order of m into n as the total worth case complexity right that is the time complexity uh let's go look at the space complexity for this so space complexity is also equal to the order of m n because we are using the sum array to calculate the minimum path sum right so we are declaring the sum array to be equal to the order of m by n so this space complexity and time complexity both are equal to order of m into n hope that clarified all the questions that you might have if you still have any more questions please uh put them in the comment section uh i will respond back thank you for watching please subscribe to my channel if you haven't done please click the bell icon so that you will be notified with all my future videos also share among your friends thanks for watching i will be back with another video very soon till then good bye
|
Minimum Path Sum
|
minimum-path-sum
|
Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
**Note:** You can only move either down or right at any point in time.
**Example 1:**
**Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\]
**Output:** 7
**Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum.
**Example 2:**
**Input:** grid = \[\[1,2,3\],\[4,5,6\]\]
**Output:** 12
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 200`
* `0 <= grid[i][j] <= 100`
| null |
Array,Dynamic Programming,Matrix
|
Medium
|
62,174,741,2067,2192
|
1,460 |
in this video we will solve lead code 1460 it says that you are given two arrays one is target and second one is some other array and your task is to convert this arr to target and what you can do you are allowed to select a sub array out of this and then reverse that sub array and you can do that multiple times so can you convert this to this arr to target so you have to return true or false so let's see how we can solve that so first of all uh what is the condition we need in order to convert this to this so the condition will be that the elements should be same if here we have 1 2 3 and here we have 10 20 30 then no matter how many uh reverse operations we make we can never reach this so the condition is that all the elements should be same now the second thing is that so that is the first condition element should be same second condition is that if elements are same can we always convert them by reversing to this so how we will convert this error to this let's see so here we can convert swap this 2 4 one so if we reverse this sub array we will get one four two and three is not part of this then we swap these two not swap but reverse the entire sub array so one two four and three remains here then you take this sub array and reverse it so you get one two three four so you are allowed to reverse the server here we took three length here we took two length as per the requirement so second thing is that if elements are same can we always reverse so i will prove that yes we can so let's say we have some two arrays a1 and a2 this is the target so it will remain fixed it has some elements and here we have the other array which we will reverse both have to have same length and let's say till this position till k position they are same that is we don't need to change them this k can be zero as well that is none of the arrays are in none of the elements are in correct position from the beginning but let us say this first k elements are same so we are bothered only about this part so whatever is the here at the k plus 1 position let's call it t k plus 1 so it will lie somewhere here the same element so what we can do we can take this sub array this entire sub array and reverse it so what will happen in reversing so take t k plus 1 as the last element starting from here before which everything is at correct position so just reverse this part so what will happen this k will remain same k elements and this t k plus 1 will come here since we will simply reverse the entire sub array and there will be some more elements the remaining elements so we see that now we have k plus 1 elements in the correct position tk plus 1 was required here and it has come here so now we will do the same thing for this remaining part so we can do this reverse one at a time and we can keep increasing the length of the elements which are in correct position so we can always convert arr to target if we have same elements by just selecting one sub array out of this and reversing that entire sub array so let's write the code for this in c plus for java and python so here simply we need to check that all the elements will be same that's it these are already of same length so we can do multiple things here one you can do sorting so sort this and compare element wise so if they have same elements then after sorting at first position both will have same element at second position also both will have same so that will take in log n time second approach can be that we iterate through the elements of this target and keep the count of elements in a map so one has occurred one times since numbers can occur multiple times as well two has occurred one times here all are unique so that count is not important but in some problem it may be so this is the map of element and their counts and then again we iterate this arr and for each element we check the map whether it exists in the map or not if it exists we will decrement its count and look at next element so at the end of this iteration every element should be found in this map if every element is formed and so at any point of time if count becomes zero we will remove that or we can keep that and we will see that count is greater than zero then we will know that both have same elements so let's uh look at this hashmap based solution so here first value is the actual number in target and the second one is the count both are integers so if it's already present then just increment the count else insert it with a count of one since this is occurring for the first time and now this map contains all the elements and their counts let's do the same thing for arr and if map dot find a not equal to map dot end and map a should be greater than 0 it's if its count is 0 and we have arrived we have found another instance of a but its count has already become zero then that means there are on unequal number of uh that element in target and error so we will return false but if that is not the case what we will do we will decrement its count else either it's not found or if it's found but its count is now zero then return false if none of this occurs finally we return true and let's try and it works for this case let's see a tricky case where some algorithms may fail so some algorithms may be thinking that uh take the xor of both the sets and we know that xor of two same elements is zero and they will take the xr of both and finally they will check if the result is 0 or not but let's say each element occurs twice in the set in both the sets but they are not same let's say here it's five six so this would return false if you uh take a x or simple xor based solution this would fail but here it should work sorting will also work if you sort these two will have exactly same elements at the same position if the conversion is possible now let's submit and this solution is accepted in c plus and it's not that bad it's about 75 in terms of runtime and 100 in terms of memory now let's do the same thing in java so here we will use hash map we can get ah then increment its count and put but if the element does not exist then we should get the count as zero so there is a built-in function for that so there is a built-in function for that so there is a built-in function for that get or default that is if it's found get its value the value stored for this key if it's not found then take some default value and that default value will be zero since it's not it has not occurred so it's count to zero and then map dot put t comma count plus 1 and here if map not contains a and map dot get is greater than zero then map dot put a map not get a -1 else return false and the solution is accepted in java as well and here it's better than 100 of the submissions in terms of memory and runtime finally we will do the same thing in python 3. so this is the map for t in target if t in map then increment its count else we put one so we have created the map now we will do the same thing for arr and the python solution is also accepted and it's better than 75 percent submissions in terms of runtime and 100 in terms of memory
|
Make Two Arrays Equal by Reversing Subarrays
|
number-of-substrings-containing-all-three-characters
|
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps.
Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_.
**Example 1:**
**Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\]
**Output:** true
**Explanation:** You can follow the next steps to convert arr to target:
1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\]
2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\]
3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\]
There are multiple ways to convert arr to target, this is not the only way to do so.
**Example 2:**
**Input:** target = \[7\], arr = \[7\]
**Output:** true
**Explanation:** arr is equal to target without any reverses.
**Example 3:**
**Input:** target = \[3,7,9\], arr = \[3,7,11\]
**Output:** false
**Explanation:** arr does not have value 9 and it can never be converted to target.
**Constraints:**
* `target.length == arr.length`
* `1 <= target.length <= 1000`
* `1 <= target[i] <= 1000`
* `1 <= arr[i] <= 1000`
|
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
|
Hash Table,String,Sliding Window
|
Medium
|
2187
|
985 |
here I present solution to day 21st of September lead code challenge the problem that we have in today is some of NE even numbers after queries so I'll be explaining you this question as well as the algorithm by the presentation so let's quickly hop on to it now let's try and understand the question by an example here you are given an ARA of integers where the integers can be negative as well as positive along with this you are also told that you need to run queries on these numbers and after running these queries what do you need to count the sum of even numbers that exist in your updated nums array so the first query says that you need to add one value at the zeroth index so the updated array becomes 2 3 4 so you have added one over here and after the update what would be the even elements present in the array it is 2 4 and these sum up till 8 so the answer corresponding to the zth query turns out to be8 let's proceed ahead with the next query next we have minus 3 should be added at the first index so if we add minus 3 over here then what do we get 2 - 1 3 4 what are the even elements get 2 - 1 3 4 what are the even elements get 2 - 1 3 4 what are the even elements over here 2 and six the total sum becomes six let's proceed ahead next we have Min -4 should be added at the have Min -4 should be added at the have Min -4 should be added at the zeroth index so let's add Min -4 over zeroth index so let's add Min -4 over zeroth index so let's add Min -4 over here what do we get min -2 -1 3 here what do we get min -2 -1 3 here what do we get min -2 -1 3 and 4 what are the even elements -2 and 4 what are the even elements -2 and 4 what are the even elements -2 and 4 there some turns out to be two which is in sync with our expectation let's proceed ahead next the query says you need to update value two at the third index so what is the third index 0 1 2 3 this is the third index so let's go ahead and add two over here what is the updated are - 2 -1 3 and 6 and here updated are - 2 -1 3 and 6 and here updated are - 2 -1 3 and 6 and here there are only two even elements Min -2 there are only two even elements Min -2 there are only two even elements Min -2 and six there sum turns up to be four in nature the answer corresponding to this query is four let's proceed ahead the next query that we have is update the first index with value two so let's update the first index which is this one with value two so what do we get 2 - 1 is + one so this do we get 2 - 1 is + one so this do we get 2 - 1 is + one so this would be + one and how many even numbers would be + one and how many even numbers would be + one and how many even numbers do we have in this array there are two even numbers minus 2 and six they sum up till four so the answer corresponding to this becomes four the knive approach that comes to everybody's mind after reading this question is to identify the sum of even elements after running each and every query so let's assume there are K queries and we need to identify the sum of even elements after running each query the time complexity of this approach would be equal to K into order of n where n signifies the L the length of numar this is quite expensive in nature can we optimize this up the answer is yes how can we do that let's try and understand it up the first thing that I'm going to do is to identify the sum of even elements that exist in this array what are the even elements that exist in the array it is 2 and four so let's create the sum of even elements and it turns out to be six I have iterated over the entire array I check whether the current element is even in nature or not if it is even then I add it to my even sum variable so let's call it even sum variable let's write it over here now what I'm going to do I'm going to walk through the queries and the query says first query says update the value at the zeroth index with one so what do we go and check what is the value at the zeroth index the value at the current value at the zeroth index happens to be one it is odd in nature that means it's not contributing to the even sum variable so far so good now let's update the value to uh whatever is stated in the query so it tells me to add one to it so let's add one to it what do I get two is it even in nature yes it is even in nature so what I'm going to do I'm going to update my even sub variable with this value so let's add two over here and even some variable gets updated to eight this is in sync with our expectation the answer for this s query turns out to be8 the next query that we have is -3a 1 that means you that we have is -3a 1 that means you that we have is -3a 1 that means you need to add minus 3 at the first index so let's check what value is held at the first index has the value two is even in nature that means this has already contributed to even sum variable so what we are going to do the first thing that we are going to do is to subtract two from the even sum variable so let's subtract two and what do we get the value gets updated to six now even some variable hold six what we are going to do next we'll update this variable with minus 3 value We'll add minus 3 to it so what do we get 2 - 3 is min-1 is minus one get we get 2 - 3 is min-1 is minus one get we get 2 - 3 is min-1 is minus one the updated value at this particular index is it even in nature no it's not even in nature that means we are not going to update our even sum variable had it been even in nature we would have updated it over here the answer value corresponding to this query gets updated to six which is in sync with our expectation let's proceed ahead the next query that we have is -4a 0 that means query that we have is -4a 0 that means query that we have is -4a 0 that means we need to add -4 value at the zeroth we need to add -4 value at the zeroth we need to add -4 value at the zeroth index what value is it held at the Zer index it we have two right now so we check whether two is even in nature or not since two is even in nature that means it has already contributed to even some variable what we are going to do we'll subtract two from even some variable so even some variable gets updated to four now what we are going to do we will update the zero index and add Min - 4 to it so 2 - 4 what does it give Min - 4 to it so 2 - 4 what does it give Min - 4 to it so 2 - 4 what does it give you it gives you - 2 and since again you it gives you - 2 and since again you it gives you - 2 and since again minus 2 is even in nature we'll be updating our even sum variable with minus 2 so let's add minus 2 to even some variable 4 Min - 2 gives you two so some variable 4 Min - 2 gives you two so some variable 4 Min - 2 gives you two so the answer gets updated to 2 this is again in sync with our expectation the next query that we have is 2 comma 3 that means we need to add two value at the third index so what do we check what is the value held at the third index it is four is even in nature the first thing that I'm going to do is to subtract four from the even sum variable since it's even in nature so the updated even sum value is min-2 so the updated even sum value is min-2 so the updated even sum value is min-2 now I'm going to update the third index with value two let's add four uh and two together we get six so the value gets updated to six since again it's even in nature we will be updating the even sum variable 6 minus 2 gets updated to four and this becomes our answer and the value of even Su variable again in sync with our expectation let's proceed ahead next it says update the value or add two at the first index so what is the current value at the first index is minus1 we have to add two to it since minus one is odd in nature that means even some variable will not be updated and no value needs to be subtracted from it uh as a result of which let's proceed ahead and add two to it -1 + 2 gives you plus uh + one and to it -1 + 2 gives you plus uh + one and to it -1 + 2 gives you plus uh + one and since again it's even in it's not even in nature it's odd in nature we will not be updating the even some variable what is the value held at the even sub variable it is four and this again is in sync with our expectation the time complexity of this approach is simply order of n plus order of K and this is much more optimized than the previous solution that we thought of let's quickly walk through the coding section and conclude it up the first thing that I have done here is to create an even Su variable I iterate over the input array and I check if my current element is even in nature I update my even Su variable moving ahead I've have created my answer array and the size of this array is n because there will be n queries uh and let's proceed here let's start the iteration what do we extract the new updated value that should be added to the current value or the additive value uh we extract the index where this manipulation has to be done we extract the old value held at the current variable in number s and if my old value happens to be even in nature what do we subtract it from the even sum variable as I did in the presentation as well so instead I should write here old value is even nature and let's proceed ahead I simply update my nums at the idx index with the new value so new value gets added to it and we again check if the new value is at the idx index is even in nature then we update our even some variable once the final updates have been made whatever value is held in even sum get set as part of the answer at the is index let's try this up time complexity of this approach is order of n plus order of number of queries that we have queries. length 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
|
Sum of Even Numbers After Queries
|
bag-of-tokens
|
You are given an integer array `nums` and an array `queries` where `queries[i] = [vali, indexi]`.
For each query `i`, first, apply `nums[indexi] = nums[indexi] + vali`, then print the sum of the even values of `nums`.
Return _an integer array_ `answer` _where_ `answer[i]` _is the answer to the_ `ith` _query_.
**Example 1:**
**Input:** nums = \[1,2,3,4\], queries = \[\[1,0\],\[-3,1\],\[-4,0\],\[2,3\]\]
**Output:** \[8,6,2,4\]
**Explanation:** At the beginning, the array is \[1,2,3,4\].
After adding 1 to nums\[0\], the array is \[2,2,3,4\], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to nums\[1\], the array is \[2,-1,3,4\], and the sum of even values is 2 + 4 = 6.
After adding -4 to nums\[0\], the array is \[-2,-1,3,4\], and the sum of even values is -2 + 4 = 2.
After adding 2 to nums\[3\], the array is \[-2,-1,3,6\], and the sum of even values is -2 + 6 = 4.
**Example 2:**
**Input:** nums = \[1\], queries = \[\[4,0\]\]
**Output:** \[0\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `1 <= queries.length <= 104`
* `-104 <= vali <= 104`
* `0 <= indexi < nums.length`
| null |
Array,Two Pointers,Greedy,Sorting
|
Medium
| null |
96 |
hey everybody this is Larry this is day 24 of the decode June daily challenge I don't like button to subscribe button join it this quote for chat and let's get started unique binary search tree given n how many structurally unique binary search trees that stores values 1 2 n given 3 years 5 okay so this is a very famous sequence it is called a current sequence I put it here but and there a couple of ways to do it some with comet Oryx and stuff like that but the way that I've remembered to how to solve this is by just divide and conquer so the way that I have it is that okay for each node on top right there only how many ways are there to put notes on the left and how many ways are there to put notes on the right well for in this case for any see good way there you can either put 0 node on the left two nodes on the right one notes on the net left one notes on the right and I forget which way I went but two nodes on the left and what 0 notes on the right so you can't do that for every and then that is your recurrence and then you can implement that similar to Fibonacci or something like that it's pretty straightforward once you kind of get to divide and conquer but it is a good practice in just thinking about how to break a problem down and you can do it a couple of ways like I said it's really similar to Fibonacci pan and there's actually a lot of math behind this if you really want to get to know it there are a lot of different problems that for this sequence that comes up is one of my favorite sequences to be honest because it comes up randomly all the place yeah but you can implement in a few ways I'm gonna do a recursively with memorization you could again because as I mentioned earlier you start with kind of similar to Fibonacci and you know and then you could easily convert that to bottoms up dynamic programming out the link below so that you can maybe figure out how to work that conversion and yeah let's get started on the code so let's just say def of C of X so what's that so you need use one node to use one note for the root right so then now you just have to figure out how many Sun the left and how many is on the right so let's have a flow left in range let's see X should be okay because this is exclusive so you would never use X node on the left you'll always be just X minus one at most because again one node to node is root and then right as you go to X - laughs - one yeah and now so you to X - laughs - one yeah and now so you to X - laughs - one yeah and now so you have a todo so then the total number of Clow is just the sum of all these possibilities right because it what we said was all the possibilities that you can do to enumerate it and then just do a recursively so total is you go see what's that times see right and then that's pretty much it and of course it's not actually it but it's pretty much it and then now you ask yourself what's the base case well edge cases 0 you have 1 return 1 and yeah and I think that's all you need and now you can just return C of n now sometimes I think I may be out by one but yeah oka and then now we could also just try out bigger numbers and I also know that just you know we didn't do the memorization part but that's okay for now this made time out probably more time I'll be scanner numbers to go pretty quickly but yeah but it looks like we're heading in the right direction and now we just have to add memorization some of you at home I know that Python the libraries to help you possession I'm just going to put it in a way he's to facilitate that let's just go okay cash is you go to doesn't matter that just say negative one times and plus one why do I have M plus one is because we want to store the value from 0 to n inclusive and this n plus 1 numbers between 0 and n inclusive is calculated say this equal to force times also n plus 1 for the same reason and then now we can do if is calculated of X then we turn cash of X and the way and we just make sure that we cash it some cash of X is equal to total and it is calculated X is equal to 12 and that's pretty much all you need and now hopefully this should be blazingly fast okay well maybe the test case is too big apparently it didn't give me two constraints I didn't know but you can also see that it gave me a huge number which I calculated very quickly anyway well I don't know it goes pretty quickly as you can imagine as a car number is bad on how fast okay so even to hundreds to break up so okay I just wanted to try something like a big-ish number so that something like a big-ish number so that something like a big-ish number so that we can see where correct okay well apparently we could have done we could have given hard-coded the answer we knew have given hard-coded the answer we knew have given hard-coded the answer we knew that it was gonna be only less than 2000 understand that okay well okay so it looks okay so I'm gonna submit may be civil but I think that's just the one case cool and of course another and I yeah another technique that I would kind of talk about and think about is that especially on a competitive programming because on in a in an interview you can't really do this but I would just actually if for whatever reason this one's too slowly and in this case it wound everyone's too slowly I would just print out all the answers and then put it in an array and then just put it out with like a neck statement or something like that kind of thing but yeah anyway funny interview this is divide and conquer and just pretty basic pretty much so I would definitely be familiar this and calendar numbers is something that I'm a fan or so definitely just you know be familiar with it and this recurrence also comes up a lot in dynamic programming problems so not necessarily this answer but this sort of divide and conquer where okay you now divide the left and then you divide the right and then you try to figure out how to kind of fit it in this happens in dynamic programming a lot so definitely practice it and get to be familiar bit in terms of in done a competitive program this is pretty straightforward so yeah I would definitely recommend studying up on this anyway yeah that's why I have for this problem I think if you still have trouble with this definitely destroy doubt and visualize but basically the short thing is with these dynamic programming specialists these karma talks and sequence try to figure out how you can represent a sequence by a smaller version of itself which is easier said than done I understand but without let you kind of visualize it in this case we just start up okay we have n nodes in this cases let's just say well five nodes where then we could enumerate well one know has to be on top to have four nodes to be on the left and the right and that means that there's still notes on the left for a four on the right and then just you know keep on going down because they to some to four notes right someone like that mr. thing that you keep in mind in Destin Marian if you want to call it that but yeah that try for today hit the like button to subscribe and join the discord and hang out and I will see you tomorrow bye
|
Unique Binary Search Trees
|
unique-binary-search-trees
|
Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`.
**Example 1:**
**Input:** n = 3
**Output:** 5
**Example 2:**
**Input:** n = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 19`
| null |
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
|
Medium
|
95
|
1,770 |
so hey there everyone welcome back so let's solve this today's problem of the day name is maximum score from performing multiplication operations so let's read the problem uh so we are given two integer arrays nums and multipliers of size n and M respectively where n is greater than or equal to M so the arrays are one based indexing right so we begin with a score of zero initially our score is zero so we want to perform exactly M operations on the iot operation what we can do is we can choose one integer X from either the start or from the end of the array nums and we can add current and we are traversing on the multipliers of multipliers so we can add multiplies of I multiply X to our score and we can remove X from the array nums so we have to return the maximum we have to run the maximum score after performing M operations right so here are our arrays given so nums is 1 2 and 3 so multiplies let's say I'm donating it denoting it by m so it's three to one so initially our score is zero so we need maximum scores so how we how will multiply the values so in each operation what we can do is and uh so we want to perform exactly M operations right so on the ith operation and it's a one based indexing so we can choose integer X either from the start or from the end of the array nums right so we need maximum some now so if we sort them in decreasing order right this is also in decreasing order right so we have nums as three to one right this is nums multipliers are already three to one right so we have to perform exactly M operations means three operations m is the size of the multipliers right so what we'll do is in each operation we'll keep multiplying all the values right in that way we'll get the maximum value obviously right 3 cross 3 plus 2 cross 2 plus 1 cross 1 our answer will be 14. right so we are using like a greedy approach right so we'll need maximum sum so we'll get maximum element from here and maximum from here will multiply them right so it will not always help in all the test cases in the case so if we have negative numbers also so how will handle this approach so right so here is our second test case so first we'll choose this element and this so if you choose like minus 3 and minus 10 so our negative becomes positive after multiplying but minus 3 and minus 10 will give some as 30 right but minus 5 and minus 10 will give also 50 right so we'll multiply these numbers right so minus 5 multiply minus 10 right so further we'll multiply minus 3 and minus 5 will multiply minus 3 and minus 5 right these numbers we are adding in our variable score right which we have to return so now we have these four elements left in our nums and three elements in our multiplies but we are allowed to perform exactly M operations m is the size of multiplies right so further we can take three elements from this three from this now we have to perform optimally right we have to go optimally to get the maximum sum so from this which number we will choose so first we will choose first we'll multiply 7 and 6 because they will give the maximum number right so we'll choose seven and six so okay we can go from we can choose start over from end so you can say let's say so here at this step we'll follow greedy approach so we'll choose one and four instead of 1 and 6 because we'll Reserve over 6 to multiply with 7 so okay let's say we are multiplying one with six so this will give the number only six so if you multiply 6 with 7 then it will give 42 so you can see the difference we need the maximum scores so we'll multiply 6 with 7 not with one so and we will multiply one with four right so we are adding in our scores one with four and seven with six right so we are made with one operation right so we are made with these two numbers minus three and minus 2 from the array nums and we are remained with one number in multipliers which is three so now which number we will choose so this is a negative number this is positive so positive plus negative a positive when we multiply positive with the negative it will give the number as a negative right and then when we will add that negative number into our sum variable then it will decrease the uh our sum right our total scores so which number will choose to multiply with the 3 because we can't avoid these three number we have to perform exactly amperage M operations means all the operations we have to perform the operations are ah number of elements in our multipliers so we'll choose minus 2 instead of minus 3 why because minus 2 multiply 3 will give us minus 6 but if we do minus 3 multiply 3 it will give minus 9 right so we need maximum scores so which number will add obviously minus 6 because we need a maximum scores so it will uh means it will affect our total sum less than minus 9 right so our total sum in this case will be your total scores will be 1 0 2 right so in that way we'll perform our operations in which we are getting the maximum scores right so it's our DP problem right because we are again and again searching for the optimal sum at our present we are traversing right so we have to choose one operation out of two so the tricky part here is we have to handle three strings right so first will be the starting point of our nums and the ending point of nums and the current pointer of multipliers right starting and ending of nums and current pointer of our multiplies so if but if you go for a 3D DP solution it will give us tle right according to the given constraints it will give us really right so now we'll reduce it to our 2D solution right so the ending point we are considering here will try to remove that will only keep uh starting point and the pointer to our multipliers right to get the maximum at the current point means we are going to use only one pointer to track both our starting point and the ending point in our nums right so let's say we have a j pointer let's say uh I am taking zero based indexing but we'll convert later to a one based indexing by adding plus one right so let's say our pointer is at J in our multiplier array this is a multiplier array right so the J pointer currently is at Index Fund so what it indicates that so we'll originally it is at J plus 1 because it's a one based indexing so let me write one based indexing so here 2 is indicating that we had multiplied two elements of the multiply multipliers array already right it means that we have multiplied J plus 1 elements already in our multiplier array with the in the nums right so if our starting point is at an index I let's say it's a zero based indexing so the ending point will be at ending will be at n minus J plus 1 plus I right so ending will be at ending point will be at n minus 1 minus J plus I simply right so now let's say we have DP of i j we are taking DPO 5j it's the maximum score right I is the pointer at our nums array J is at in our multiplier array right so base case will be whenever J reaches the end of our multiplier right then we'll return 0 means we have done exactly M operations right so that will be our base case so when J is equal to multiply Dot size right then we'll return 0. so if our DPO Phi J has been calculated before right we have already multiplier multiplied two numbers one from let's say one from nums one from multiply will return it immediately right means we have calculated them already will not calculate again and again otherwise our solution will get recursively otherwise our complexity will be exponential right so we are doing a memoization so if it's already calculated we'll return it immediately otherwise if it is not calculated we have two options now we have two options so if we pick from the left in our nums if we pick from the left and in multiplier also so we'll get we'll got multiplier of J multiply of nums of I Plus let's say I'm I will make depth first search function DFS so in this we'll call nums multiply and will increment both the pointers I plus 1 and J plus 1 right if we are picking from the left if we are picking from left right so second option will be if we pick from right means we are picking this from starting this we are picking from ending so in that case it will be multiplier of J plus uh sorry multiply nums of so ending pointer we already have calculated in that case our ending point will be this right so it will be n minus 1 minus J plus I plus t f s nums multiplier I so and J Plus 1. right so we'll only increment our pointer in our multiplier array right this is the ending point in our nums array that's it so we'll perform these two operations right if the value is not calculated already right if it is called calculated already will return immediately that's it and after that we'll take maximum of these two will take maximum of these two right one from picking from left one from picking from right so in the when we'll get maximum value we'll add that value in our score because we need maximum scores so let's drag around these two steps so let's say let's take one two three to one as for stretch case given right so now uh let's I am considering zero based indexing right so we have added one two three right we have converted one based indexing in our steps so right so let's say we have zero based indexing zero one two right so now first we'll try first step we'll pick from left we'll pick this one and this one right means our nums of J which is 0 multiply in terms of I which is 0 and later will call our DFS to later Parts I plus 1 and J plus 1 so in this case our answer will be 1 multiply three it's three tight so if we pick from right so our nums of our multi multiplier of J it is 0 Plus nums of so ending point in our nums is now we have calculated n minus 1 minus J plus I right it would be n is 3 size of nums n is 3 minus 1 minus J our J pointer is at our index is 0 Plus sorry I had written 0 based indexing here also it's a one based indexing here in our I so we have converted uh it's also a one based indexing given in the problem but we have converted zero based indexing later in the uh later in the we have converted this to one base how by doing J plus 1 right we have already discussed this so plus I our I is at initially at our index 1. right so in this case our answer will be it is Multiplied here so multiply of 0 which is 3 multiply our nums of 3 minus 1 is 2 plus 1 3. right it will be 3 multiply nums of three is the last index element which is three it is 9. so when we are picking from left we are getting the value 3 when we are picking from right in our nums we are getting nine so we'll take maximum of these two right we'll take nine instead of three so in this way we'll keep calling our function at last we'll get our maximum score as 14 in this first test case right so let's see its code it would be very simple so here let me take DP of size so constraints given are so it would be terrific 3 so it will be enough and I'm taking two pointers I and J right so let's make a function called DFS so what parameters will pass one is our nums and another over multiply a vector given uh multiplier um right and we'll pass our pointers I and G right I that I will Traverse over nums array nums factor and J will be at our multiplier Vector so now base case would be if our When J is equal to m is the size of the multiplier Vector so in that case will return 0. it means that we have possessed all the ammo operations means pointer J reaches the end of the multiplier will return 0 right and if we have calculated our DPO 5j we have we has been calculated it so we'll return the result if DP of i j is not equal to minus 1 will return DPO 5j if it is not calculated yet will that it calculate it and will take maximum of the two steps we had seen so one will be when we are picking from left multiplier of J multiplying nums of I we are picking from left and we are calling DFS to further elements I plus 1 and J Plus 1. right and when we are picking from like a right this is we are picking from left this in this case we are picking from right so in that case we are will be multiply of J nums of ending point will be n minus 1 minus J plus I right plus DFS it will be numbers here nums of multi multiplier I and will increment J Plus 1. right so we'll take maximum of these two and we'll store in our i j after calculating will store in our IED uh right so in our main function just we have to call the function we have made so let's calculate sizes first so size would be uh num stored size m is multipliers dot size multiply stored size and we're using memset you can also use a two Master Loops two to initialize the value in our DPO 5j with -1 value in our DPO 5j with -1 value in our DPO 5j with -1 so or you can directly call our memsat function in build size of DP and will call this function and return it nums multi plus initially our IE and gr at 0. right so that's it just a second or it should be M and N here so you have taken I and J by mistake so MN and here should be so yeah accept it so let's try to run it submit it sorry tle uh just a second so here uh we are getting tle because here you can see constraints of numbers and multipliers of I it's from minus thousand two thousand so our answer can be minus one so right so we can't write here minus 1 because if in the case uh we got answer as minus 1 then it will keep returning over that again and again right that's why we are getting tle so instead of here so we can write int main here right instead of minus 1 we'll write int main uh let's take a vector instead of array also it would be safe so let me write Vector of type vector and name is DP right so here uh we'll use DP dot resize size M plus 1 and Vector end M plus 1 and intermin right so now uh it should be right so let's try to run it for this test case where we were getting tle so yeah now it's getting accepted so let's try to submit it
|
Maximum Score from Performing Multiplication Operations
|
minimum-deletions-to-make-character-frequencies-unique
|
You are given two **0-indexed** integer arrays `nums` and `multipliers` of size `n` and `m` respectively, where `n >= m`.
You begin with a score of `0`. You want to perform **exactly** `m` operations. On the `ith` operation (**0-indexed**) you will:
* Choose one integer `x` from **either the start or the end** of the array `nums`.
* Add `multipliers[i] * x` to your score.
* Note that `multipliers[0]` corresponds to the first operation, `multipliers[1]` to the second operation, and so on.
* Remove `x` from `nums`.
Return _the **maximum** score after performing_ `m` _operations._
**Example 1:**
**Input:** nums = \[1,2,3\], multipliers = \[3,2,1\]
**Output:** 14
**Explanation:** An optimal solution is as follows:
- Choose from the end, \[1,2,**3**\], adding 3 \* 3 = 9 to the score.
- Choose from the end, \[1,**2**\], adding 2 \* 2 = 4 to the score.
- Choose from the end, \[**1**\], adding 1 \* 1 = 1 to the score.
The total score is 9 + 4 + 1 = 14.
**Example 2:**
**Input:** nums = \[-5,-3,-3,-2,7,1\], multipliers = \[-10,-5,3,4,6\]
**Output:** 102
**Explanation:** An optimal solution is as follows:
- Choose from the start, \[**\-5**,-3,-3,-2,7,1\], adding -5 \* -10 = 50 to the score.
- Choose from the start, \[**\-3**,-3,-2,7,1\], adding -3 \* -5 = 15 to the score.
- Choose from the start, \[**\-3**,-2,7,1\], adding -3 \* 3 = -9 to the score.
- Choose from the end, \[-2,7,**1**\], adding 1 \* 4 = 4 to the score.
- Choose from the end, \[-2,**7**\], adding 7 \* 6 = 42 to the score.
The total score is 50 + 15 - 9 + 4 + 42 = 102.
**Constraints:**
* `n == nums.length`
* `m == multipliers.length`
* `1 <= m <= 300`
* `m <= n <= 105`
* `-1000 <= nums[i], multipliers[i] <= 1000`
|
As we can only delete characters, if we have multiple characters having the same frequency, we must decrease all the frequencies of them, except one. Sort the alphabet characters by their frequencies non-increasingly. Iterate on the alphabet characters, keep decreasing the frequency of the current character until it reaches a value that has not appeared before.
|
String,Greedy,Sorting
|
Medium
|
1355,2212
|
371 |
hello everyone and welcome to my next self-study session today we're going to self-study session today we're going to self-study session today we're going to be looking at equal number 371 the sum of two integers and so basically with this problem we're given two numbers and we're required to add them together without the use of arithmetic operators like plus minus and so this adds a bit of challenge and given this restriction one of the ways to solve this problem is by the use of binary numbers and we know with binary numbers there are two numbers zero and one whenever adding binary numbers there are a few rules we need to keep in mind and we're going to look at them here in this table so let's say we have operands a and b they're both zero then their sum will be zero and they carry zero if a is zero and b is one the sum is one and carry is zero so what is carry is simply um the left shifting of the leading digit over to the next column and most of us i believe all of us would be familiar with carry operations from elementary school edition yeah so let's look at the next rule when a is one b is zero then the sum is one the calorie is zero however if both a and b are one then the sum is zero and carrying is one so what do we notice about this well we you may have noticed that the sum is simply bitwise exclusive or operation and carry is bitwise and operation so exclusive or results in one only when one of the operands is one zero otherwise and we see that here in the last row when both of the operands are one the sum is zero and the carry is one however if either one of the operands is one then the sum is one and the carry is zero on the other hand we may be more familiar with the and the um bit wise and operation um it's only when both operands are one we get a result of one zero otherwise and we see that in the last row both operands were one so the carry was one right so let's move on let's look at you know some ordinary column addition method and to you know further familiarize ourselves or realize how we can go about solving this problem programmatically right okay so let's say we have the numbers five and four five in binary is 101 and four in binary is um one zero and so we have these numbers here in a table um a is five and b is four so when we add um these operands we have a carry of zero here and you can see that it's um kind of like grayed out because it's always going to be zero because it's the start right so we add these two all the exclusive for them and we get a result of one sum of one and a quarry of zero they're all now zero so obviously the sum is going to be zero and a carry of zero however we have two operands that are r1 so the sum is going to be zero and we carry is gonna be one so now when we exclusive or all of these we have a carry which is one and um the others are zero so it's going to result in one and that's what we're used to write when we do regular base 10 addition it's pretty much the same process so if we look at the number 122 and we add 49 to it um if we add 9 and 2 we get 11 we bring down the one and we carry over the one we add these numbers together we get a 7 and we get a carry of zero we add them together and we simply bring down the one and so the result is 171. so looking at these operations it kind of gives us some hints on what on how we may need to write our algorithm so we see that we are using bitwise exclusive or and bitwise and so we're gonna need those in our algorithm additionally we are continuously or repeatedly carrying over a value so this tells us we need some sort of loop to look at each um each cycle of the process and how do we carry over the number to the next column well um programmatically we do that with the left shift operator and so let's look at the code and see what that's going to look like okay so here we have the code and we see that we have the two parameters um we represent the operands we have a variable for our temporarily storing the and operation for the carry over we have our loop and the loop will be terminated whenever a is equal to zero okay so looking at line number 16 we see that we are performing the bitwise and operation the carry operation and on line 17 we are actually doing the exclusive or operation we are doing the sum here and we store it in b so on net moving on to line number 18 we see that we are left shifting by one to move over to the next column now if a ever results in zero then it means we have completed our addition process and we can exit the loop and just return whatever we have as the sum which we stored in b and that is pretty much it for this um algorithm and if we run it three seven one we get nine or one zero one and isn't that what we arrived at when we added five plus four we get nine so that's pretty much it for this um this session if it was helpful to you at all please let me know if i missed anything please let me know in the comments below like and subscribe thank you so much for joining me and i'll see you next time ciao
|
Sum of Two Integers
|
sum-of-two-integers
|
Given two integers `a` and `b`, return _the sum of the two integers without using the operators_ `+` _and_ `-`.
**Example 1:**
**Input:** a = 1, b = 2
**Output:** 3
**Example 2:**
**Input:** a = 2, b = 3
**Output:** 5
**Constraints:**
* `-1000 <= a, b <= 1000`
| null |
Math,Bit Manipulation
|
Medium
|
2
|
821 |
Jhaal Hello Guys Welcome to Your Consideration subscribe and subscribe the Channel Please subscribe and subscribe the Distance from Character subscribe and subscribe this Video subscribe Kare Tak Apni To Point Jadi Services subscribe and subscribe the Video then subscribe to the Page Candidates Right Inside Birthday Arjun That Left Side With No How To Calculate The Electronic Subscribe The Channel Please subscribe and subscribe the and Swasth Discuss Mitthu First Novel In Axis Of The Character Of Womanhood Pregnant Industry Involved With U In Novel ADD THE MOST NEGATIVE VALUE IN TO-DO LIST GET AWAY WITH THE PROBLEM THE WILL OOO DO HU TO-DO LIST GET AWAY WITH THE PROBLEM THE WILL OOO DO HU IS THE CURRENT EASY TO PURIFY GHEE ARRANGEMENT BILL HALF INDEX IN TO-DO LIST AFTER ALL THE HALF INDEX IN TO-DO LIST AFTER ALL THE HALF INDEX IN TO-DO LIST AFTER ALL THE BEST POSITIVITY IN 2ND YEAR RESULT DATE A Man will again loop on the length of train om navanita value sadf that person second value will take to variable value day middle aged person to that inductive one that and will have and index to interest between thursday the subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to The Amazing Liquid Ki Reddy And Which Implies Return The Result Of Displaced Part Plus Code Picture And How To Edit Submitted Successfully Explain Space Complexity And Approach To Find Time For Watching And Videos You In Next Month MP4
|
Shortest Distance to a Character
|
bricks-falling-when-hit
|
Given a string `s` and a character `c` that occurs in `s`, return _an array of integers_ `answer` _where_ `answer.length == s.length` _and_ `answer[i]` _is the **distance** from index_ `i` _to the **closest** occurrence of character_ `c` _in_ `s`.
The **distance** between two indices `i` and `j` is `abs(i - j)`, where `abs` is the absolute value function.
**Example 1:**
**Input:** s = "loveleetcode ", c = "e "
**Output:** \[3,2,1,0,1,0,0,1,2,2,1,0\]
**Explanation:** The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).
The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.
The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.
For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.
The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.
**Example 2:**
**Input:** s = "aaab ", c = "b "
**Output:** \[3,2,1,0\]
**Constraints:**
* `1 <= s.length <= 104`
* `s[i]` and `c` are lowercase English letters.
* It is guaranteed that `c` occurs at least once in `s`.
| null |
Array,Union Find,Matrix
|
Hard
|
2101,2322
|
152 |
hello and welcome today we're doing a question from Le code called a maximum product subray it's a medium we're going to jump right into it given an integer array nums find a subarray that has the largest product and return the product example one we have 2 3 -24 and 23 would example one we have 2 3 -24 and 23 would example one we have 2 3 -24 and 23 would give us the max product of six so that is what we output and example two we have -2 have -2 have -2 01 here we output zero we can't put -2 01 here we output zero we can't put -2 01 here we output zero we can't put -2 and negative - 1 as a subray because and negative - 1 as a subray because and negative - 1 as a subray because they're not connected we have the zero in the middle so that's not a valid subarray and we have some constraints down here okay so this is actually a pretty fun problem we want to find a subay with the max product and return that subray before jumping in what is a subay is a contiguous part of an array so we can't take chunks from different parts of an array and put it together it has to be connected and out of all the possible subarrays we want to find the one with the maximum product now we've done a maximum subarray before and I've linked that down below if you want to give that a quick watch and try this again it's very similar logic but here we want to find the one with the maximum product so how are you going to do that well say I have the following example 2 3 -24 this is the same as example 2 3 -24 this is the same as example 2 3 -24 this is the same as example one over here one way to approach this would be to just brute force it so I would make all possible subarrays and see which one would give me the maximum product so if I were to make all possible subarrays I would have the following the one with just two then at three I expand the one from before or start over and at -2 I do the same I start over and at -2 I do the same I start over and at -2 I do the same I expand the previous one start over and same with four so these are all my possible subarrays and once calculating the product I would find that 2 three would give me the max of six now when solving for the maximum product subarray what's stopping us from including every single number the more numbers I have the bigger my product right that's not always going to be true our product would actually go down if we run into negatives or zeros so instead what I'm going to do is at every single index see if the maximum product I can make is either expanding my previous subarray or starting over at my own index what I mean by that at the first index the maximum product I can make is two so right now my Max product is two now once I get to three is it better for me to start over a new subarray or is it better for me to expand from my previous one it's better for me to expand from my previous one so adding three to my two because this way my Max product becomes six once I get to -2 what's the max six once I get to -2 what's the max six once I get to -2 what's the max product I can make here if I were to expand the one from previously I would have 2 3 -2 which would give me -12 it's have 2 3 -2 which would give me -12 it's have 2 3 -2 which would give me -12 it's better for me to start over at -2 and once I get to four is it better -2 and once I get to four is it better -2 and once I get to four is it better for me to continue the one from before or start over and again we can only look at the previous index we can't put together things on the other ends right so is it better for me to continue here or start over it would be better for me to start over at 4 and once I go through I can see my Max product was six but what if I had the following input what if I had -5 at the very end input what if I had -5 at the very end input what if I had -5 at the very end of my array well now I have two negatives and my Max product would actually be this array over here 2 3 -2 4 this array over here 2 3 -2 4 this array over here 2 3 -2 4 and5 giving me an output of 240 which is of course bigger than six but if I apply that same logic once I got to -5 I would see it's better for I got to -5 I would see it's better for I got to -5 I would see it's better for me to start over for the max product at this index and I would never actually get to this 240 so instead what I'm going to do is not only keep track of my maximum product I'm also going to keep track of my minimum product and that's because if I have a bigger negative once I multiply that with a negative number I'll get a bigger positive right so I want to keep track of both my maximum and my minimum so if I were to do that at the first index my maximum would be two and my minimum would also be two once I get to three at this index what subarray would give me the maximum and minimum the maximum here would be of course to continue from before so 2 and 3 and the minimum would be to start over at 3 now once I get to -2 the maximum subay 3 now once I get to -2 the maximum subay 3 now once I get to -2 the maximum subay I can make would be -2 and the minimum I can make would be -2 and the minimum I can make would be -2 and the minimum here would be to take my previous 23 and expand that to include -2 to get the expand that to include -2 to get the expand that to include -2 to get the product of 6 * -2 which would be -12 so product of 6 * -2 which would be -12 so product of 6 * -2 which would be -12 so here I would do 2 3 -2 this is my here I would do 2 3 -2 this is my here I would do 2 3 -2 this is my minimum product I can make at this index once I get to four the maximum product would still be four I can't expand either of these two the max or Min from before to get a bigger maximum than just starting over but my minimum would be greater if I added a four to this subarray so two 3 -2 and subarray so two 3 -2 and subarray so two 3 -2 and 4 now once I get to -5 the maximum product would be to take -5 the maximum product would be to take -5 the maximum product would be to take this previous minimum array and expand that by including A5 so 2 3 -2 4 -5 this that by including A5 so 2 3 -2 4 -5 this that by including A5 so 2 3 -2 4 -5 this would be my Max product at 240 and the minimum here it would actually be better for me to expand four so it be 4 -5 to for me to expand four so it be 4 -5 to for me to expand four so it be 4 -5 to give me -20 as opposed to starting over give me -20 as opposed to starting over give me -20 as opposed to starting over just at5 so what we're doing is dynamic programming but we're keeping track of both our maximum and minimum values because we're dealing with negatives so if we keep track of both of these we would eventually find the maximum product we're going to get it either by starting over and making a new subate at the index we on or continuing from either our previous Max or our previous Min subay so let's write this out and then run through a couple examples okay to code this up I'm going to start off with my minimum and maximum products at every single index so our main product and our Max product are going to be that very first number we have so it's going to be nums of zero and our overall maximum product that we're going to return at the end is going to be that first number as well so max P right here now we want to iterate through the rest of our array so four num in nums and I'm going to continue after that first index we've just covered we want to check what the Min and Max at each index is going to be so at this number that I am on the minimum product is going to be the minimum of starting over at the number I'm on or the number I'm on time the previous minimum or maximum so number time Min P or number * Max p and that's going to be or number * Max p and that's going to be or number * Max p and that's going to be our new minimum and we want to do the same for the max product is going to be the max between starting over or expanding either our previous Min or our previous Max so num times Min p and we've actually Rewritten the value of Min P here so I'm going to store the original Min P value in a temporary variable so minimum product so I'm going to reuse temporary in here or the num times maximum p and if the maximum product is greater than the maximum product we're holding so far overall I'm just going to go ahead and make an update so maximum product would be the max of the max we're getting at this index versus what we have been storing so far so maximum product and in the end all we have to do is return maximum product so let's go ahead and run this code runtime error oh I forgot to set these all equal to each other okay this should work accepted and now we can go ahead and submit this and it is accepted as well so before leaving let's just run through a super quick example okay say I had the following example as my input nums -2 -124 and 20 going through this nums -2 -124 and 20 going through this nums -2 -124 and 20 going through this just line by line we have the minimum product set to that first number same with maximum product and our overall maximum product is set to the same as well now we're going to be iterating through so our nums starts after that first index and we're going to store in temp our current minimum which is -2 now our new minimum value is going to -2 now our new minimum value is going to -2 now our new minimum value is going to be the minimum of the number that we are on right now so it's going to be -12 on right now so it's going to be -12 on right now so it's going to be -12 versus our number times the Min or the max so -12 * -2 is 24 and -2 * -2 is max so -12 * -2 is 24 and -2 * -2 is max so -12 * -2 is 24 and -2 * -2 is still 24 and our minimum here would be to start over at the subarray so it's going to be -12 and our Max P we're doing basically -12 and our Max P we're doing basically -12 and our Max P we're doing basically the same thing we're comparing our numbers but now we want to find the max between these numbers and the max is going to be 24 so we're going to go ahead and update the maximum product right now because x p is greater than what we have in maximum product right now so updating this we have 24 as our maximum product so far we go back in this Loop and we're at -4 now so we this Loop and we're at -4 now so we this Loop and we're at -4 now so we store our minimum value in temporary so this is going to be -12 and now we want this is going to be -12 and now we want this is going to be -12 and now we want to compare between our current number so -4 and our current number times the -4 and our current number times the -4 and our current number times the minimum and maximum so the minimum is -12 so 48 and -4 * our current Max which -12 so 48 and -4 * our current Max which -12 so 48 and -4 * our current Max which is96 so what is the minimum over here that's going to be 96 and what is the maximum over here going to be again we're just comparing the same values so the max here is going to be 48 and we would go ahead and update this maximum product 48 as my maximum product over here and this is going to be this subray right here and we're going to be going back into this Loop so now the first thing we are going to do is store minimum value in Temps and we make the checks again so now we're comparing 20 we're comparing our number times the minimum we've stored so 20 * 96 I should have chosen stored so 20 * 96 I should have chosen stored so 20 * 96 I should have chosen smaller numbers but this is going to be 1,920 and 48 * 20 so that's going to be 1,920 and 48 * 20 so that's going to be 1,920 and 48 * 20 so that's going to be 960 okay the minimum here is of course 1,920 the max is 960 and we would update 1,920 the max is 960 and we would update 1,920 the max is 960 and we would update the maximum product again to be 96 zero so that is what we would end up outputting it's going to be this subarray right here for our answer now talking about space and time complexity for time we're just going through our entire array one so that's a linear scan o of N and for space we only keep track of two variables so that's going to be constant o of one for space so we just went ahead and solved maximum product subarray if you have any questions at all let me know down below otherwise if you like this video like And subscribe and as always I will see you in the next one
|
Maximum Product Subarray
|
maximum-product-subarray
|
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_.
The test cases are generated so that the answer will fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[2,3,-2,4\]
**Output:** 6
**Explanation:** \[2,3\] has the largest product 6.
**Example 2:**
**Input:** nums = \[-2,0,-1\]
**Output:** 0
**Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-10 <= nums[i] <= 10`
* The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
| null |
Array,Dynamic Programming
|
Medium
|
53,198,238,628,713
|
8 |
Hello Hi Guys Welcome Back To The Video In Today's Video Will Be Looking At Another Question No Strings Winters And Into A Question That Is Implemented By Which Converts 2000 Function First Discards I Added White Space Character Accessory For Not Want Peace Character Is Mom Dad Starting From This Character Taken After Initial Plus And Minus Sign Followed By Admin In Its Possible Interprets Puberty Is Shruti Door To Examples For Example Pet String For Truth And Corresponding And Gifted Individual Album Now Electronics Voice Messages And Paay - Now Electronics Voice Messages And Paay - Now Electronics Voice Messages And Paay - 0522 Kar Spotting And Notice - 4a 0522 Kar Spotting And Notice - 4a 0522 Kar Spotting And Notice - 4a Which Example Three And Four Quite Similar On Exam Calculus Lift Person Time And Minimum Balance And Non-numeric Minimum Balance And Non-numeric Minimum Balance And Non-numeric Famous Example Fourth Starting Voucher Nurses Interesting And Which Animal Welfare That Give Example Free TV Consider Only On Reaching A Lesson And Worked For 193 Virus In Case Of Example 14.07 Counter Virus In Case Of Example 14.07 Counter Virus In Case Of Example 14.07 Counter non-numeric Valuable Than Enough Strength at non-numeric Valuable Than Enough Strength at non-numeric Valuable Than Enough Strength at Last The Consider Example Five Vinod Reduces Individual Services Citizen and Value Based on the Minimum Intervention that Should be Considered Examples Given in Question Difficult as Simple as Residents in Numerical Belgium and Output Spotted in Example2 Way Have placid in white space characters for love affair - white space characters for love affair - white space characters for love affair - st is that point cat negative and positive to example screen detail tha conversion by converting the details for 198 how to enter conversion stops and digits that in example for the post character is wb system nickel value Date 420 Returns 0 The Inner Last Example The Number Is Not Inside Inch Of 32bit Sign In Teacher Rich And Sons Number Is Negative Return Minimum Of India Volume Should Consider Second Example With String Is Wife Is And Paaye - Sexual Medical String Is Wife Is And Paaye - Sexual Medical String Is Wife Is And Paaye - Sexual Medical Balance Superstring Edison Initially Also Easy Sa Into One In This Life What Is Us 200 Golden Steps Follow Us Switch On Android Thursday i10 Mode Turn Off Director Iss Wale Piece Previous Song A Slight Character Skill Wife Burman 559 Points - WB Suvichar Vishyaksha Points - WB Suvichar Vishyaksha Points - WB Suvichar Vishyaksha Distic Of Director Iss - More Subscribe Distic Of Director Iss - More Subscribe Distic Of Director Iss - More Subscribe - 40 - 40 - 40 Ko Increment came na between weather fourth characters lies within reach of zero and know it surya the character pimp character is the 15-minute officer multiply foot by 20 15-minute officer multiply foot by 20 15-minute officer multiply foot by 20 in the middle of director to the value of root of sport notification 8.22 lies root of sport notification 8.22 lies root of sport notification 8.22 lies within 30 grams multiply at Integral Part Of Two Hindi Science Book Of Science 2002 In That Infertile Negative Then Me Multiply Out By - 1the Value Of Root Is Minus Point By - 1the Value Of Root Is Minus Point By - 1the Value Of Root Is Minus Point To And Will Return Gift That Clutch Considered For Example Three And Behave Time Medical Research Scholar found alphabets su of the length of steam and images of science and out in and there respectful lip sweep in the traveling on string in so I point to 4 slice Vidyadhar from this zoom applied art button and delivery of toot increment came the loot sports Meet again perform simmer operations and you will find I absolutely character suggestion leaf spot to a similar loot will be forces that by now obligation increment may or may not come point to point space character in this epic character slot salt prudence and press login return for 1938 That Election Vikram Thakur Initially Bin Incomplete Is MP And Not Difficult Return 0 That Means Some Detail Dating Learning Teacher Variable And Definition Of A Z Ultra Thin The Strength That Should Declare Other Entries Available Science Institute 251 Numerical Value Is Positive Or Negative And Posting Minute Tourist Weather String Contains Electricity In White Space Characters That Situation Removes 200 Abs Characters For The Best Villain Middle-aged Loop Characters For The Best Villain Middle-aged Loop Characters For The Best Villain Middle-aged Loop District Director Is Points 208 That Is Condition Ho Suggested Increment You 2.26 Characters After Completing The Wild 2.26 Characters After Completing The Wild 2.26 Characters After Completing The Wild Life Itself Is Equal To Land In The String Contains Only White Dress Characters End With Returns Us Me Safe Minute Weather String Content Intestine Characters Plus And Minus B Ajay Ko On Karo Hai That Fitting Characters And Distances - That Fitting Characters And Distances - That Fitting Characters And Distances - Jannat Me Gya Final Swaroop Intimate Aaye Ek Guest More Content Se Left Side Characters Din Bay Considered S Positive String In Some Cases In The Streets Positive Ajay Ko Mein Pain Like Increment File Main Kal Na Aa Ki A Ki Election Mein Declare In Long In Trouble You Want To See The Phone Mister Return Value Not To Convert String To Enter Cancer Divine Character First Winters Light Vijendra 029 Pass Loot Lo Mera Tab Kithar Actor Wali On Life In Their Think Oo Bhi Multiply How To Write In The Lord And Win 8.1 Of The Character 2.2 And Win 8.1 Of The Character 2.2 And Win 8.1 Of The Character 2.2 Ajay Ko Hua Hai Ajay Ko Loot Ki Infrared Increment Aaye The Handed Over But Everyone Picture Brother Anil Tablecloth Negative And Not Forget You Can That Wearable Activity Avoid Negative Album Play List - Birth Play List - Birth Play List - Birth Is Next 9 News Check Weather Dobaara Lift One Services 32bit Sign In Teacher Inch Thee Cartoon Political Structure Of This Placement Minimum Winters Value Images In Me Tips and Twitter The Amazing Is The Last Liquid Brother Diwali Gift Exceeded The Maximum Temperature Rise In This Vital Religious And Intermediate Physics And Maths Is A Reminder Like And The Following Conditions Or Falls And Beaten Up And Semen Becomes A Minute To Account For Elts Institute Of medical and examined that inflict vijendra nakur a that this record from answer because field picture sweaters were value of not exceed 32bit scientist settings show option that cancer debit statement in the blue v chakradhar that of worse interrupt your website images drawing on a Hindi Fiction Body Opposite Follow Us On Main Sumit Aggarwal And This Time Akouta Accepted Suvidha And Press Enter Mita Kund Ki A Ko Report Submitted Successfully Show Defined S Video Helpful Do It Like Button and subscribe To My YouTube Channel for More All Coming Videos Thank You to Ajay
|
String to Integer (atoi)
|
string-to-integer-atoi
|
Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi` function).
The algorithm for `myAtoi(string s)` is as follows:
1. Read in and ignore any leading whitespace.
2. Check if the next character (if not already at the end of the string) is `'-'` or `'+'`. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
4. Convert these digits into an integer (i.e. `"123 " -> 123`, `"0032 " -> 32`). If no digits were read, then the integer is `0`. Change the sign as necessary (from step 2).
5. If the integer is out of the 32-bit signed integer range `[-231, 231 - 1]`, then clamp the integer so that it remains in the range. Specifically, integers less than `-231` should be clamped to `-231`, and integers greater than `231 - 1` should be clamped to `231 - 1`.
6. Return the integer as the final result.
**Note:**
* Only the space character `' '` is considered a whitespace character.
* **Do not ignore** any characters other than the leading whitespace or the rest of the string after the digits.
**Example 1:**
**Input:** s = "42 "
**Output:** 42
**Explanation:** The underlined characters are what is read in, the caret is the current reader position.
Step 1: "42 " (no characters read because there is no leading whitespace)
^
Step 2: "42 " (no characters read because there is neither a '-' nor '+')
^
Step 3: "42 " ( "42 " is read in)
^
The parsed integer is 42.
Since 42 is in the range \[-231, 231 - 1\], the final result is 42.
**Example 2:**
**Input:** s = " -42 "
**Output:** -42
**Explanation:**
Step 1: " \-42 " (leading whitespace is read and ignored)
^
Step 2: " \-42 " ('-' is read, so the result should be negative)
^
Step 3: " -42 " ( "42 " is read in)
^
The parsed integer is -42.
Since -42 is in the range \[-231, 231 - 1\], the final result is -42.
**Example 3:**
**Input:** s = "4193 with words "
**Output:** 4193
**Explanation:**
Step 1: "4193 with words " (no characters read because there is no leading whitespace)
^
Step 2: "4193 with words " (no characters read because there is neither a '-' nor '+')
^
Step 3: "4193 with words " ( "4193 " is read in; reading stops because the next character is a non-digit)
^
The parsed integer is 4193.
Since 4193 is in the range \[-231, 231 - 1\], the final result is 4193.
**Constraints:**
* `0 <= s.length <= 200`
* `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`.
| null |
String
|
Medium
|
7,65,2168
|
334 |
hey everyone uh so today we'll be dealing with this problem it's a very good problem increasing crypto subsequence basically in this problem we have to find three elements the third element should be greater than the second element and the second element should be strictly greater than the first element so uh that is our problem so like one two three four five one two is greater than one and three is greater than two so we are getting uh this result so we will return true similarly in two one five zero four six we are getting one five and then six here or we are getting 0 4 6 here they are strictly increasing one five six is strictly increasing and zero four six data it is also strictly increasing right so uh first intuition is good Force which will be like taking three Loops the third Loop element should be greater than strictly greater than the second Loop element and the second Loop element should be strictly greater than the first Loop element right so that can be the solution but it will take a lot of time and Q we are going to solve it in o n times objectity and o1 space complexity we are just going to take two variables and our logic will be very simple like we take two one five zero four six as the uh you know activity two variables versus Min and the second is s Min right so uh basically uh manually with the smallest element the second s Min will be the uh second smallest element right so uh s Min should be created then Min and if we get the third variable which is greater than S Min then that will be the answer then we'll stop there and you know it will return to like here it will be the main has uh until here it's the smallest and one is smaller than two one is smaller than Min to be honest so here we'll write we will change the main to S uh I mean we'll change domain from two to one we'll move to five which is the second smallest as it is greater than Min and it is after Mill so we'll change it to S min we come to 0 then what will happen is 0 is smaller than the initial min right our initial mean is one so we are gonna change them into from 1 to 0. now you will be thinking that s minus uh before I mean it should not be correct but that is also correct I'll say I'll tell you why because uh s minus 5 right so anything greater than 5 which is 6 here that can be also the answer because 1 5 6 so anything greater than S Min at present will be the answer right so 156 can also be the answer if 0 and 4 were not there instead of 0 4 9 or something greater than the main initial menu which is one they were there then naturally 156 would have been the answer s Min would have been here and 6 at 6 it would have returned two right but if 0 is here we'll change it to Min and if it and if any number like 4 is here it comes which is smaller than S Min right then we will change it to S Min so s Min basically changes one into two cases right once one case number one is when the Min has changed previously just now right so mean has changed and then s min should be greater than the Min present Min and it should be listed then the initial menu right so that is why we have changed to assume uh to four so now if 6 comes then it is greater than the S Min then that will be the answer that is only one condition to be the answer then you should be greater than decimal then that will naturally be the answer so 0 4 6 is the element which will be the answer right If instead of 0 4 something greater than the initial menu were there like nine then one five six would have been the answer it says uh six would have been greater than S Min as when would have been five only it would not have been changed have changed to four so one five six would have been the answer soon so it has changed since 0 is here and we have also got 4 here which can be the S Min as it is lesser than 5 so main changes to zero as mean changes to 4 and F6 also comes which is greater than S Min and that is the answer so for answer again it should be the next element should be just created in an estimate then that will be the answer it will return true let's go to the code we will initialize also with the same right because for finding the Min sorry not Max it should be estimate for finding an even value we have to assign it to integer.max Value regular it to integer.max Value regular it to integer.max Value regular so we'll scan it we'll scan the whole level so n is left to else if as an estimate all right one thing to note here is we will take n less than min sorry will not take any less than men you will take n less than equal to 1 will take n less than equal to S1 the reason is that if any element comes here like one is assigned to Min earlier then again any one comes then it should not be you know s min right because s Min cannot be equal to Min s Min has to be greater than Min and therefore it will be Min only it will change to main only right if any number comes which is greater than one then that will be as well right so that is why we'll have less than equal to if it is less than equal to so it is equal to here so it will change to min so main was earlier this element now it will changed the menu will change here to this one otherwise if we had not changed this then it would have become s Min which is wrong right so just a simple approach will run this uh it's getting accepted we'll submit this code it's running right so 100 time complex it is speeding so yeah time complexity is here o n because only one the whole worst case scenario the whole Loop will be traversed and the space complexity is one because only two variables we are taking so that's all uh regarding this video please like share and subscribe and please comment down if you have any doubt or any better approach you have uh thank you once again 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
|
876 |
okay welcome back to argojs today's question is going to be the code 876 middle of linked list so given the head of the singly linked list return the middle node of the linked list if there are two middle nodes return the second middle node so pretty straightforward question it's just asking for us to return the middle node so in the first example we have one through to five and we need to return three and second example we have one through six and we need to return the right most value of the middle values it's a pretty straightforward question we've linked lists especially finding the middle value we use a two pointer technique so we have a left and right pointer starting at the initial position so head and we move the left pointer across one and we move the right pointer across two so the right pointer moves twice as fast and the understanding is that if the right pointer moves twice as fast when the right pointer reaches the end the left pointer will be halfway across so the right pointer will go here initially the left point will go here then the right pointer will be at the end and the left pointer will be at three and then we can just return the left pointer there let's see if it works with the second example that was given in the question so left and right pointer moves here left pointer moves here right pointer will then be out of bound to right pointer will move there and left pointer will be here time complexity is going to be on where n is the length of the linked list and space is going to be a1 so when writing this out rather than using left and right pointer what we'll do is we'll update it to slow and fast pointer so with the while loop we need to state with a fast and fast dot next i'll not null because remember the fast pointer is moving two places at a time so we need to check fast and fast dot next and then we just update fast to fast dot next slow equals slow dot next and then we can return slow let's give that a go let's submit it and there you go
|
Middle of the Linked List
|
hand-of-straights
|
Given the `head` of a singly linked list, return _the middle node of the linked list_.
If there are two middle nodes, return **the second middle** node.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[3,4,5\]
**Explanation:** The middle node of the list is node 3.
**Example 2:**
**Input:** head = \[1,2,3,4,5,6\]
**Output:** \[4,5,6\]
**Explanation:** Since the list has two middle nodes with values 3 and 4, we return the second one.
**Constraints:**
* The number of nodes in the list is in the range `[1, 100]`.
* `1 <= Node.val <= 100`
| null |
Array,Hash Table,Greedy,Sorting
|
Medium
| null |
1,686 |
hey everybody this is larry this is me going over uh lead code contest by weekly 41 q3 stone game six so this is a tricky problem so hit the like button to subscribe and join me in discord before i forget um but the cool part about this is going to be greedy um kind of so i think the thing that i've read from people solving is that they just sort by the sum um in a greedy way we take the pile uh that or the stone that has the highest sum for each um yeah we just saw them by the sum of the values and then grouped them that way uh and then people i don't know i feel like hand wave a little bit with respect to like they're like ooh this is greedy and this is why and i don't really think that's a great explanation for learning i actually made some mistakes during the contest as you saw i end up taking 24 minutes because i did a shortcut in my head that turned out to be wrong and you could watch me celebrate live during the contest but if i went back to first principles how do we derive this well how do you convince yourself that you know choosing the sum of the stone values is good enough well it is something basically a classic sorting trick if you will which is the assignment or yeah the simon exchange argument uh which is that uh basically you have two stones right um and you're trying to maximize your score and minimize bob's score so basically you have two stone let's say stone a and stone b right so i'm gonna short-handed stone b right so i'm gonna short-handed stone b right so i'm gonna short-handed by saying a or b um well you may ask yourself which one is more valuable right so let's say we have let's just have a compare function that compares a to b to figure out which one is more valuable well in this case um the value of the stone is just you go to uh alice's maybe i should use okay let's use x and y because alice and bob is confusing the a's and b's so yeah so that means that uh you know the delta of the scores matter right so basically what it means to is that um okay i will pick x oops pick x if you know this is just me looking i prefer uh okay also i am alice let's just say though actually this uh turns out to be symmetric but i'll pick x if um x sub a minus uh y sub b is greater than x sub b minus y sub a right um and what does that mean right in english right i mean that's a formula and you know you're happy about seeing that but what that means in is english in english is that if i have if i pick the stone a that then uh the other person will take the stone b right so we want to choose this if let me rephrase that if i choose the strong x i get the value of a and the other person will get the value of b right and from that well do we want to pick x would we pick x this is the score that we get for x right if we pick x over y sorry that i'm exploring this account a little bit terribly but we pick x over y we will get the score x sub a and the other person will get the score y sub b if right the score difference is x sub a minus y sub b right and if you pick y over x then the square difference is y sub a minus x sub p right so then you have this formula that we talked about before which is something like this and we want to see whether they're bigger than each other right and well if you manipulate the formulas a little bit then you get something like this what x sub a plus x sub b we compare that to y sub a plus y sub b right uh and this is just you know we add x sub b on both sides and we add x sub uh y sub b on both sides and this is what we end up with right and make this one bigger so that's basically the idea behind this algorithm is that okay between and you can also see uh make the similar argument for b now right where okay this is if i'm alice uh if i'm bob you know you have the same thing except for the formula's a little bit different uh you know you have b's here and a is here and similarly you're saying if i'm bob i pick x over y that means that the score difference is going to be you know i get the b x score x of b score uh alice gets the y sub a score and the reason why we care about the difference is that we only care about the um the difference that we get right so basically if i'm bob this is also the case and if you kind of put it together then you have x sub b minus y and if you do the same math you also get x sub b plus x uh sub a you know something like this right which coincidentally if you look at this it's symmetric it's the same ev every so uh so they both basically have the same function that they're optimizing for right um so that in a greedy way alice will always to have these kind of ordering and bob as well actually and i don't know if that's a coincidence maybe if you're better at maps you could prove that uh that there's a reason why this is the case uh but for me i just kind of this is how i got about it right and then now notice that on this side for each stone the value is just the sum of the alice value plus the sum uh yeah the sum of the added value plus the bar value and you don't even need to compare anything else and that's basically the proof of everything else um or everything else follows because now uh we sorted i have a negative thing here because um i wanted to sort by biggest number so you could actually just remove it and do you know reversed and that's fine because now you're getting bigger numbers in the front and because they have the same formula you're gonna they're gonna both pick in the same way so now what's remaining is that we calculate um we calculate one at a time um the total value of this the score difference right um so basically uh yeah if because alice goes first if the index is mod to zero then this is alice getting uh to add a score otherwise bob gets the score and we subtract it and if and the delta is basically alice uh delta score so if alice has higher score than bob then we return one and if alice has less score than bob reads a negative one otherwise we return zero uh because they're the same so that's basically how you would solve this problem and i know that if you read tutorial editorials and tutorials and stuff like that they just mention stuff about greedy but i think this is the better way to kind of think about how to solve this problem because this is the way that you were able to prove to yourself that is correct and generalize it uh in the future as well um and actually if you um if you watch me stop this during the contest i do a variation of this where i do a actual compar i wrote a comparison function and i didn't prove that these two are correct or i didn't prove that these two were the same initially so i um i had to do a little bit more uh agreeable to get that right um but yeah that's all i have for this problem let me know what you think uh and i oh and you can watch me stop during the contest now that's hard so you okay so the first interesting oh my god hmm you that's not bad so you foreign wow this is hard um uh take a look at this one i don't know you okay you um so all right mess that up whoops you oops uh and off by one because i'm silly so this is right i watched it but uh hmm well i really have no idea what it is up you yeah that doesn't make sense okay you okay um hmm this makes sense hmm i don't know anymore all right maybe that's right i left that print statement in the max uh hey thanks for watching the explanation i this was a little bit of a tough contest for me uh let me know what you think hit the like button to subscribe and join me on discord and i will talk to y'all uh later bye
|
Stone Game VI
|
fix-product-name-format
|
Alice and Bob take turns playing a game, with Alice starting first.
There are `n` stones in a pile. On each player's turn, they can **remove** a stone from the pile and receive points based on the stone's value. Alice and Bob may **value the stones differently**.
You are given two integer arrays of length `n`, `aliceValues` and `bobValues`. Each `aliceValues[i]` and `bobValues[i]` represents how Alice and Bob, respectively, value the `ith` stone.
The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play **optimally**. Both players know the other's values.
Determine the result of the game, and:
* If Alice wins, return `1`.
* If Bob wins, return `-1`.
* If the game results in a draw, return `0`.
**Example 1:**
**Input:** aliceValues = \[1,3\], bobValues = \[2,1\]
**Output:** 1
**Explanation:**
If Alice takes stone 1 (0-indexed) first, Alice will receive 3 points.
Bob can only choose stone 0, and will only receive 2 points.
Alice wins.
**Example 2:**
**Input:** aliceValues = \[1,2\], bobValues = \[3,1\]
**Output:** 0
**Explanation:**
If Alice takes stone 0, and Bob takes stone 1, they will both have 1 point.
Draw.
**Example 3:**
**Input:** aliceValues = \[2,4,3\], bobValues = \[1,6,7\]
**Output:** -1
**Explanation:**
Regardless of how Alice plays, Bob will be able to have more points than Alice.
For example, if Alice takes stone 1, Bob can take stone 2, and Alice takes stone 0, Alice will have 6 points to Bob's 7.
Bob wins.
**Constraints:**
* `n == aliceValues.length == bobValues.length`
* `1 <= n <= 105`
* `1 <= aliceValues[i], bobValues[i] <= 100`
| null |
Database
|
Easy
| null |
1,283 |
hello so continuing on this weekly contest 166 the third problem which is problem number 100 1283 find the smallest divas are given a threshold so the problem says we get an array of integers and numbers nums and then integer threshold and we will choose a positive integer divisor and divide all the array by that divisor essentially and then take the sum after dividing and what we want is to find the smallest divisor such that when we do this division and get the sum is less than or equal to threshold and we run around the for the division we run around to the nearest integer greater than or equal to that element right so on around kind of farm down I would say so maybe it's math singing or something and yeah so that's pretty much this problem so one two five if we look at the example one two five nine threshold is six if we divide we can try first like divide by one we will get seventeen divided by four we'll get some 7 which is bigger than threshold but when we get to six sorry to 5 and divide by 5 we'll get five right which is smaller than threshold so this is the smallest division that gives us the result that we want and for this example here it's three but if we look at the constant here you can see the array can be up to 50,000 numbers and the threshold can be 50,000 numbers and the threshold can be 50,000 numbers and the threshold can be up to 10 to the power of six so right away you could see here that binary search would be very useful for this because first the order here doesn't matter we just need to divide and get the sum so that means we can sort the array the problem doesn't specify the subject that sorted but I think when I tried it without sorting it work it so I think it kind of they just didn't setup sample test cases with an unsorted array but we can anyway just source it even that won't be too big because it would be n lie again so it would be still 10 to the power of 4 multiplied by a log of that so it's not too big but for binary search though we need to define a couple of things we need to define what is the function that we are going to test or the property and then we need to define what is the range that we are going to run our binary search on yeah so that's let's see how we can do that so let's see how we can solve this problem so essentially with binary search that isn't the normal or the usual one where we are just searching for a value in an array what we need to do is we kind of need to define a couple of things we need to find our function right so and we need to define like the test that we are going to do so maybe this is equal to some value maybe this is bigger than some value maybe something like it just is good whether this is valid on it will give us true or not and then what we need is we need to find out something about this function which is that it's or about this test here right let's call it test we need to find that maybe we get false and then false the test will keep giving us false and then it will start giving us true or a didn't first maybe the test will keep giving us to true and then it would give us false but essentially when we can't run binary search if it's like this true and then false and then it becomes true this we can't because we can't know at which point whether going left is the right answer or go right is the right ends right so this is um so this is what we need to find some property like this and so here in our case here what are we looking for we are looking for so what we are looking for is what needs to be here because that's what we will get the mid for in that world we will return at the end when we are done right so here our axis needs to be the Divis are right the dues are that we are going to test and the problem says that the threshold is we need the sum after dividing right after dividing to be less than or equal to threshold right and so what we can do is we know that threshold is 10 to the power of 6 right and the divisor cannot be this definitely cannot be bigger than threshold because then this sum would be necessarily then yeah then this would be true anyway so what we need to do is take the divisor range so for binary search we need to find the function and the range of the solution over the possible solution right so that's what I'm trying to find out here so the range here we can just take from 1 because dividing with 0 will give us something that doesn't work so we don't we shouldn't do that and we can go to 10 to the power of 6 the other alternative is just going to the max of the array because if we divide everything by the max of the array we won't get either one for each position I will get 0 and that will be necessarily will definitely be less than the threshold because the problem says that the length of nums is less than or equal to threshold so the other solution is just to do this and this will be faster because step to the power of 6 is because the numbers can go all the way up until but which is less than or equal to ^ 6 so the max even if it's the biggest ^ 6 so the max even if it's the biggest ^ 6 so the max even if it's the biggest number possible it will still be small alright so we could just take the maximums right and now what is the function so the function that we need to do we just need to find the problem says that the sum after dividing needs to be less than or equal to threshold so that's exactly what we are going to use so what we need is our function needs to be less than or equal to threshold and then our function would be f of X is just the sum after dividing so it's just X is the Divis all right so maybe let's just make this more expressive and give this D and so this would be for every element in the array we will take according to the problem it asks us to do so we'll just use pythons math.ceil do so we'll just use pythons math.ceil do so we'll just use pythons math.ceil and we'll take every number in the array divided by D take the ceiling and then take the sum of this right because that's what we want at the end to be less than or equal to threshold so we take the sum of that and if it's less than the threshold what should happen so let's say we have a divisor so the divisor will go from 1 to max of nums as we said right so what is the pattern so we are looking for one of these right so if it's small so when we increase the devisor right that means that the number when you divide the number it would be smaller right and so that means that if it was smaller for some number and then you increase the devisor it will still be smaller right and so as we increase when we find a place where it's smaller than the divisor and we find it sure if we increase the devisor that will just so if we have let's say X 1 a 2 a 3 a 4 say divisor was two right and then we had some s for that some value right if we increase user to 3 that means all the numbers will become smaller right so this is s 1 this is d 1 so that means that s1 because dg2 is bigger than t1 that means that while s2 will definitely be smaller than as one because this means that the numbers will be smaller which means the sum would be smaller right so that means that if this value with d1 was smaller than threshold if we take bigger values they will still be smaller than threshold right so we would have once we get true or keep getting true but if for some value it was let's say here it was bigger than threshold right so maybe if we increase it's still not that small so maybe we'll have something like this so this is entirely possible but once we get true we will never get force again right because we'll keep increasing the divisor and the sum will keep getting smaller right and so in this problem we want the smallest divisor and since we're starting from one to the max that means that what we are looking for is the smallest divisor so we are looking for that first true value looking for the first true value which is basically the smallest divisor and this is the 4-valent binary search and this is the 4-valent binary search and this is the 4-valent binary search to work here we will need to the problem needs to be asking for either the first true value or the last false value right or if we have something like this it needs to be asking for the first false value or the last true value otherwise we won't be able to solve it using binary search here and so here we have everything set up for us we know the function 1 we know the range that we are searching in and we know the function that we'll use right and so right now we could just do binary search basically saying the lower value setting the lower value to 1 setting the higher value to max of numbers and then checking if the mid value is less than or equal to the threshold then we need to go where we need to go right because if we go right sorry we'll need to go left because ok let me write it that would be easier so let's try to our binary search here so we would have low and high value would be 0 and then length of and then the max number as we said right so max of nums and we'll start doing our binary search right so binary search here while they haven't met will compute the mid and then we'll check if F admit so f of mid is this entire thing actually I'm going to change this a little bit so I'm going to say this is good or maybe you know let's just do F of mid it's less than or equal to threshold right so what this would mean is that maybe we are here but maybe also we are here right we don't know which true is it there is no need to go right because if we go right we will keep getting bigger will keep we will get only bigger divisions right but we are looking for it's the first value so either here which means we are we will we need to stay at mid all or here and that means we will to go left which means here what we need to do is go left but stay at MIT because maybe the solution is MIT right so that would mean what we need to do is we will need to say our lower value to go left you need to set higher value right so in it set higher value to mid right why we usually we don't meet minus one but here because maybe this is the actual first show that we are looking for so that's why we are doing that and then otherwise that means it's a false so maybe you are here but maybe we're also here but in any case if we are here or here we have to move right to get a true value right so that means here we have to go right so we need low to be equal to mid plus one to go right and then at the end when both meet we can just return high because that's the one that we set to a mid and when we are done that means they met somewhere here on the first true value and so we need to return although for that matter because they will be equal right and affirm it would be just as we said here is the sum of methacel of a / said here is the sum of methacel of a / said here is the sum of methacel of a / D for alien in there right and that's pretty much it for this binary search and so yeah the takeaway here is that think of a property that has this attribute of being false and then becoming true or the reverse being true and then becoming false and then think about the range of your x value and then think about the function that you all use and pretty much once that is done you could solve it so the already doesn't even have to be sorted you just need to find a pattern like this where it's false and then it's true or it's true and then it's false yeah so let's type this in too late code and make sure it passes this cases okay so I just type it what we saw in the overview so this is the function it's the sum of dividing every element by X taking the ceiling of that and we let me just make this return so that we match the this is much less than threshold much the overview and then if it is we go left because that means it's a true value so either it's the value are at or maybe something with that to the left of that there are some true value of the still otherwise it's a false so we have to go right to find the true value and when both meet that means we find the solution and that's pretty much it so let's run okay I submit so yeah that passes cases in terms of time complexity you can see here we are the upper loop here this is of lag of max of the numbers right so which can get at most two to ten to the power of six and then we are calculating this function aside which is the sum so it's of n which is and the length of the array so it's kind of off lag of max numbers right multiplied by M yeah so that's the time complexity there in terms of space complexity we are not really using it so all one essentially yeah so just a different way we could calculate this for the ceiling if we don't want to use a library we could just do essentially a so reduce a to a minus one and then divide by sorry and then divide by X and then add 1 divided by X this way and then add one so just to do what the problem says which is take the nearest integer greater than or equal to the element so in the nearest integer greater or equal to it / twin subtract greater or equal to it / twin subtract greater or equal to it / twin subtract one so that we can get a number smaller a little bit maybe by zero point something and then we add one yeah so that's pretty much it for this problem please like and subscribe and thanks for watching and see you
|
Find the Smallest Divisor Given a Threshold
|
reformat-date
|
Given an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`.
Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: `7/3 = 3` and `10/2 = 5`).
The test cases are generated so that there will be an answer.
**Example 1:**
**Input:** nums = \[1,2,5,9\], threshold = 6
**Output:** 5
**Explanation:** We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
**Example 2:**
**Input:** nums = \[44,22,33,11,1\], threshold = 5
**Output:** 44
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `1 <= nums[i] <= 106`
* `nums.length <= threshold <= 106`
|
Handle the conversions of day, month and year separately. Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number.
|
String
|
Easy
| null |
1,535 |
hello hi guys good morning welcome back to the new video as you can see the background is changed I am at my home um so that's reason my video is coming a bit late but yeah no worries uh so basically this question we have uh 1535 find the winner of an AR game it has been asked by spinny and reti now the problem statement is actually pretty simple it's just that how we try to approach it or and how we try to find the trick inside that is actually the main crust cool so the says that um we have to find the winner of an aray game now that AR game okay we have an integer AR and distinct integers and an integer K ARR has distinct integers that's one thing and we have one VAR ASC a game is played between two elements and we are seeing they're only playing between the zero index and the first index which means only zero index element and the first index element will participate in this part particular game and how the game will happen when these two elements will participate what will happen is the larger ones wins and the one who wins will actually stay at the position zero and the smaller one will actually go at the end of the AR I'll show you by replicating the same example now the question what they are asking for us is the game ends when an integer wins K consecutive rounds so my ultimate aim is that the person who is winning which means the person who is winning will for sure stay at the location zero so the person is staying at the location zero for two consecutive rounds or maybe he's or like just you can say he's winning for two consecutive rounds so ultimately we have to return the integer which actually will win the game again winning the game is winning for K consecutive rounds first one first the game ends when an integer any integer who for sure came in first and like won the K consecutive rounds he is the winner it is guaranteed that the answer will always be there now let's just dry this entire example no worries on okay we have this input I took the exact same input K is just saying if anyone who is winning for two consecutive round states he is the winner so I will have the same input again I can only make the first and the second person participate in my game for sure who is more will actually stay at the zero index two was more will stay at the zero index which is actually itself one will actually go to the end cool so two stayed one went in the end now again I have to stop the game when anyone who is winning for two consecutive times now let's see the next game happens two and three again two and three will actually start seeing but three is more so three will win three will come at the Zer index and the two will actually go in the end okay so you saw two was winning two win two won one game but now three won one game so basically the two's winning kind of it has gone to drain because I want consecutive cave Innings okay cool three and five will be compared five is more five will stay at this location great um five won five loc five St at this location and then three gone to the end five and four again four is less five is more five stayed here four went to the end you saw here also five won five score was one right again five score increased to two five won for two con times so I can easily say that my five is the winner and that's the output itself but let's say the game would have continued and I would have asked you okay let me give like give me who is winning three two times I can ask you anything right so the game will keep on continuing so one thing from now it is so far obvious for you is that you will just try to keep on repeating this process until you will get K consecutive wins and that is problem is saying okay it's always possible to get the K cons wins but if you just look at the constraints K is actually very large so you can't just keep on iterating and making all these pairs again and again so if we just go back uh and continue to see what was happen happening was five and six being compared 6 won cool uh six came at this location five went to the end six and seven now being compared cool again six could not win seven being more one and land on to this location six went to the end seven and one being compared again uh my seven will win one will go to the end again two the two will go to the end three will go to the end five will go to the end and this process will keep on repeating so one thing for sure if I just ask you who won three consecutive times so you can just say Okay six 51 2 three times but then six starts winning but then the seven starts winning again the 71 so I can just say that 71 three con times so I am one thing for sure I will not iterate on this entire K that's not possible so I have to find some trick whatsoever that I can just actually find because it is feasible AR SI I can iterate on it but I cannot iterate on all the case so can anywh I can get this formula or anything like that what's the pattern like what's happening because if you just closely look at what was happening here was you were comparing these two elements and whosoever was small was going somewhere which means it was no longer here now you were comparing two and three okay whosoever smaller was uh going now you comparing three and five whoever smaller was so you saw I'm just kind of moving on to the next element comparing with the previous maximum element that is what I was doing right if I just go back I had from here to here let's say if I start it is my previous maximum element is two compared with the current element it's more yeah it is more so now my maximum element is two again previous maximum is still at two current element is three so for sure now my previous maximum element is three now I'm add this index who is the maximim element five so I'll just say previous maximum element is five and again go on to next index with this again previous maximum element is five again cool go on to next index but five will remain as it is again maximum element is six so previous maximum element will actually become six it will go on next index maximum element is seven it will simply keep on going I will actually hear this maximum element is seven so you saw that don't have to worry about moving it to the end just keep track of what is the current maximum element which I am having and for sure if I am having current maximum element as you saw I was comparing two and three okay earlier the two was maximum but now the three has become maximum so three is time has started up time start but then five became maximum so five time has started which means cons number of times how many times five has been coming it has coming for one time five again G so five time has increased now as soon as anyone times increase by that amount K I'm just very well sure I will get the answer so we can get one thing for sure I can just simply keep on iterating on my nums I know one thing that this replication of comparing two elements moving an element to end is just that getting the maximum element at each step and I as soon as I upate my maximum number which means if any number is becoming maximum so I just say okay now your consecutive iteration starts which means number of times you actually come consecutively I'll just increase your count okay cool I'll increase your count oh another element come another element came so I'll just say reset the count back and then keep on increasing count now six was here again new element become became a higher element reset account and then started again for this number seven again my seven was there cool increase account but Aran uh here itself I just ended and iterated on ultimately all of my elements here itself I ended my entire array now you're actually going on again which means are you saying to actually trade more than n times with the previous concept which you showed I'm just actually trading on it trating nend times on my entire array by just comparing every element and just keeping track of okay that element has been maximum for how many consecutive number of times but do I need to actually go on further also no why as soon as you will have landed onto the entire array you would have got one element as maximum so after my end tries for sure the maximum element would have reached the starting and it will always remain in the starting because it is a maximum element so even if I compare with any element of this entire array still the seven will remain intact as it is and that's entire gra as soon as the element ends still if let's say I was not able to complete my K consecutive turns my maximum which is actually a number seven will always be the answer and that's ultimately what we have to do for this problem just keep on tracking um what is the maximum Max imum number you have got so far and as soon as you update maximum number just reset the consecutive count um back to zero and then keep on increasing consecutive count as you keep on maintaining that maximum number whatsoever you had ultimately you are just iterating on the entire are once time is O of n nothing extra space used space is of n o of one let's quickly code this up so um like as you saw that what we ultimately need is the answer which is the element which was like coming K consecutive times so for sure um we will just say initially our answer can be Z index element now consecutive times that is the Crux of this question that how many consu number of times that element came for us so initially I can just say that my consecutive is zero I have not got in because I not compared anything right now so I'll just start off with the first index itself so I'll just say um I'll just go on to my entire um array starting from index one now for sure um if I just say okay if my current element if it's actually more than and for sure it is always more than it is never equal to because I have distinct elements if it's actually more than my answer which means I have got a new higher value so please make consecutive uh back to a zero because I've got a new higher value and you know I got a new higher value so it's make it Con back to zero if or like even if it is back to zero or not if it is back to zero which means I have to for sure if I get if I have got a new higher value compared to a previous value which means I have got one of the uh you know that K round like one round was completed right in here so for sure any way what ever consecutive um you can just say just increase that consecutive count because for sure if it comes here which means my answer which means consecutive became zero I've got a new higher value simply okay you have got a new higher value which means you have done one round for sure you can just increase that what if RN it did not go here which means I don't encounter a higher value I encounter a slow lower value still if you're encounter a lower value which means you're actually using that earlier previous higher value which means my high value is consecutively occurring and as soon as it's occurring again so just increase the consu count and as soon as this consecutive count it reaches a oh God I have reached my answer and my answer is nothing but this answer itself as simple as that and ultimately even if my K is very large it never goes to this condition still as soon as my entire array ends my answer will keep track of the maximum number and that maximum will always be the answer so let's quickly submit this and that should actually work yeah that's pretty much it thank you so much for watching see you in next again goodbye take care bye-bye
|
Find the Winner of an Array Game
|
build-array-where-you-can-find-the-maximum-exactly-k-comparisons
|
Given an integer array `arr` of **distinct** integers and an integer `k`.
A game will be played between the first two elements of the array (i.e. `arr[0]` and `arr[1]`). In each round of the game, we compare `arr[0]` with `arr[1]`, the larger integer wins and remains at position `0`, and the smaller integer moves to the end of the array. The game ends when an integer wins `k` consecutive rounds.
Return _the integer which will win the game_.
It is **guaranteed** that there will be a winner of the game.
**Example 1:**
**Input:** arr = \[2,1,3,5,4,6,7\], k = 2
**Output:** 5
**Explanation:** Let's see the rounds of the game:
Round | arr | winner | win\_count
1 | \[2,1,3,5,4,6,7\] | 2 | 1
2 | \[2,3,5,4,6,7,1\] | 3 | 1
3 | \[3,5,4,6,7,1,2\] | 5 | 1
4 | \[5,4,6,7,1,2,3\] | 5 | 2
So we can see that 4 rounds will be played and 5 is the winner because it wins 2 consecutive games.
**Example 2:**
**Input:** arr = \[3,2,1\], k = 10
**Output:** 3
**Explanation:** 3 will win the first 10 rounds consecutively.
**Constraints:**
* `2 <= arr.length <= 105`
* `1 <= arr[i] <= 106`
* `arr` contains **distinct** integers.
* `1 <= k <= 109`
|
Use dynamic programming approach. Build dp table where dp[a][b][c] is the number of ways you can start building the array starting from index a where the search_cost = c and the maximum used integer was b. Recursively, solve the small sub-problems first. Optimize your answer by stopping the search if you exceeded k changes.
|
Dynamic Programming
|
Hard
| null |
718 |
hello everyone welcome to cse land i am nishanth let's solve the another lead code problem maximum length of repeated sub body we have to find the length of repeated survey like here one two three and in that three to one okay here three two one is there okay and here three to one is there so length is three this will be the maximum and sub array means it should be in continuous not like one is here one is there no it should be in continuous three to one see here zero and here also zero so length is five so we can solve it by so many method but we are going to solve by dynamic programming okay so let's see these are the method so what we will do we will traverse from the last okay we will traverse from the last we will take the dp one uh one array we will take 2d array and that name is dp okay and length of the dp will be length of this plus one while like this i will explain c come here what we do actually we have to increase the uh num if value is repeated in both order then we will increase it here okay see here we will go we will check here no it's not same it's same so this value is same so what we will do it's 4 as 2 so let's go 4 and 2 here we will increase by 1 and before it nothing is there right but as we know this array when we will initialize it when we will declare it whole value will be 0 right so what we do like dp i say is equal to dp i plus 1 j plus 1 so i plus 1 and j plus 1 dpi plus 1 j plus 1 how much when you will go i plus 1 means 5 okay j plus 1 means 3 it's 0 so 0 plus 1 means 1 all right ok now go to this so that's the reason we are taking length plus one okay for dp now go to this value two if you go here it's same so three and one you got three and one here what we are doing like three plus one so uh dp three and dp one uh dp 3 plus 1 is 4 and 1 plus 1 means 1 plus 1 is 2 so 4 and 2 we have seen here right we have seen here 2 and four okay so here four plus two uh four and two how much value is one so one plus one is two right so three and one it will be two now come to this we will check nothing is there here it's there so 2 and 0 here okay so dp uh dp2 and dp0 dp3 dp1 plus 1 now dp3 plus one how much this value is two so two plus one is three so here we will update three and we will just reverse uh we will just return it are getting my point so it worked like this so basically what we are doing we are one two three two one four one we are checking that if uh value shame if value is same and when we will go to next value and the previous value is uh if previous value is same then it will be a one if not then zero so previous value is same so it's one previous value is same so it's two previous values same so it's three okay so likewise it's working so let's go to the coding part let me make it a it's big so b okay all right so what we do in max length is equal to starting 0 int dp is equal to new int a dot length plus one b dot length plus one okay you got it like y plus one right okay four into i is equal to a dot length minus 1 because we are uh traversing from last okay i is greater than equal to 0 and i minus 4 in z is equal to b dot length minus 1 okay z is equal to greater than or equal to 0 and j minus ms okay what we do we'll check that we will just we will check that if a i is equal to b z if it is equal then what we do dp i d p j d p i plus 1 j plus 1 ok now check if d max length we have to take the maximum length right if maximum length is smaller than dp value current then what we do we will just update it you want uh code your solution then in comment you can find the link of the github link you can find for sure listen you can see from there with comment okay so let me submit it yeah all right network issue okay so it's taking time all right let me submit it if you're lagging in uh developing the logic building and all just subscribe my channel press the bell icon i'm going to start the other series from scratch there i will talk about how to build logic and all everything so just subscribe the channel thanks for watching see you soon bye
|
Maximum Length of Repeated Subarray
|
maximum-length-of-repeated-subarray
|
Given two integer arrays `nums1` and `nums2`, return _the maximum length of a subarray that appears in **both** arrays_.
**Example 1:**
**Input:** nums1 = \[1,2,3,2,1\], nums2 = \[3,2,1,4,7\]
**Output:** 3
**Explanation:** The repeated subarray with maximum length is \[3,2,1\].
**Example 2:**
**Input:** nums1 = \[0,0,0,0,0\], nums2 = \[0,0,0,0,0\]
**Output:** 5
**Explanation:** The repeated subarray with maximum length is \[0,0,0,0,0\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 100`
|
Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:].
|
Array,Binary Search,Dynamic Programming,Sliding Window,Rolling Hash,Hash Function
|
Medium
|
209,2051
|
1,004 |
welcome guys let's solve maximum consecutive ones version three given a binary ARs and an integer K written the maximum number of consecutive ones in the ARA if you can flip at most K zeros so let's have the first example as you can see in the first example so the first example the number of um varos we can flip is going to be two and the answer is going to be the maximum number of consecuted ones is going to be this one the last um the last one right it's going to be six so let's take an example right or own example let's say I have one here and let's say I'm going to have two zeros and the last is going to be one and let's say I'm going to have K is going to be two so um the maximum number of zeros we can f is going is two right so let's have two pointers let's say I have the right pointer and the left pointer right so the right pointer moves whenever the number it points is going if it is one right so the right as you can see right is pointing to one right we will move it to this position so as this position also is one right so we can move it to this position and this also the same one right we can move to this position as you can see in this position the right pointer is going to have zero right so we are going to ask can we flip can I flip this zero to a one yes right because the number of case we can flip is two right so I going to flip this one to if it's going to be flip it's going to flip to one and the number of case we are going to flip is decrement to one then we move our right poter to this position meaning like we don't need to change this B to A1 but we can just moving one step to the right means we can flip the previous zero right so at this position we are going to ask can we flip this zero to a one yes right because the number of flips we have is one right is greater than zero so we can move our right point to this position so as you can see the number of case the number of zeros we can flip is zero at this position this when where right pointer is here so the right pointer is now at the end right and it's pointing to one so the difference so we are going to calculate the difference between since out of since R right is going to be out of the bound so we just calculate the difference between the right and the left so it's going to be six right so Left Right minus left plus one is going to be six so the maximum number of consecutive ones is going to be um six for this case but what if we have um a different scenario like the number of case we are going flip is one what if it is one as this case let's say start our left is going to be here and our right is going to be in the first Index right so we will move our right pointer as much as we can um if it is point if it is pointing a one right let's move it to this position so we'll move it to here right is going to be here and as this POS as this position we're going to ask if this can we flip this Z to A one yes right because the number of case we can flip is um one right so we will move right to this position so the number of case we flip is zero at this position right so we will ask can we flip this zero to a one no right because the number of case we can flip is um since the number of case we Zer we can be zero so we will take the difference between the left and the right is going to be for in this case right so then we will move our left pointer to this position right so since the left pointer is pointing to one the number of keys with number of zeros we are going to flip so when we remove from our window we are going to remove this one right so but if it was Zero we can just increment the number of zeros we can flip by one right but this is one right so we are not going to add this K right so still the right pointer is um not going to move to the right so we will move the left to this position and we will remove this to or from window right then we will ask can we add the number of can we add K by one no right because it is one and we will left to this position then that means we are removing it from the window right so when we remove one from the window can we ask is it zero no right so K is not going to be increment so at this position we will ask is it zero yes so we can add one to our K right it's going to be one because we are removing this Zero from our window so then now R can move right because we can flip this Z to one and R is going to be at this position then since R is at the end of from since R is going to be out of bound we can take that difference between the left and the right it's going to be two so the maximum so far is the maximum is going to be four right our answer is going to be four so something this way the time comp place is going to be of the space is going to be all one so it's go to the implementation so we need to have a left before we need to know the length of nums right then for this iterate and we can just say let have right is zero while right is less than n we are going to ask if the number which the right pointer is one if it is one we just move the right by one step to the right so if it is zero if the number which is the right pointer currently pointing is if is zero we need to ask if K is greater than zero right if it is greater than zero we can move the right we can say like we can flip the current zero to one so we can move the right pointer then we decrement K by one but if all of them are not if all of them are false we can just say Max con we need to have Max con if Max conc is just initially zero then we are going to maximize between Max itself and the difference between right and left right so uh just we will maximize then we will ask if the number in the left we're removing the number we are remove from the window f z we can just say we can um K by one and left is move one step from left to right then we have to return what if all the numbers are one right if all the numbers are one in the array just this is going to um this is not going to this is never executed right this part of the code is never going to execute right so we have to just say we have to return the Max of Max con and um the difference between right and left right so um let's see if this works for so as I said the time is going to be uh off in and the space is going to be off on so let's see if it works for the test case as pass for all of them for and let's see so um as you can see it passed for all of them so guys if you like this video please subscribe
|
Max Consecutive Ones III
|
least-operators-to-express-number
|
Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s.
**Example 1:**
**Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2
**Output:** 6
**Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Example 2:**
**Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3
**Output:** 10
**Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
* `0 <= k <= nums.length`
| null |
Math,Dynamic Programming
|
Hard
| null |
166 |
given to two integers representing the numerator denominator fraction return the fraction in a string format if the fraction part is repeating and close the repeating part in parenthesis okay you have the numerator and denominator and you basically divide it and if you have uh like a repeating decimal you have to put that in the parenthesis something like this okay in order for you to do this i think you need to know some basic math right you can't technically uh one option is to like basically just convert to a string and then try to find repeating one using a string but that would be a bit not that uh optimal to do so the best way to probably solve this is basically have to um just uh use some math here how do you basically divide the number and then store that modulo in the store that remainder in the hashmap so if you found a particular um repetition in our remainder in the hashmap it basically has uh you basically have a repeating one so like i could probably take this as an example so i have a sketch pad here so usually you have like in this one you have three four okay so three you divided by four and then so initially it's 40 got a zero and you have four zero and drop zero four hundred you put one three then you've got a 7 67 for the zero here you got two and then uh basically this is six and uh six so you got four okay so this is where the repeating comes in so you see that there's a four here and there's a four here so you if you put a zero here then you repeat the same pattern so you got a zero so this one will become zero and then you basically have the same pattern all over again 400 here so you get a one here and then you got a two and so on so you need to put a parenthesis on this part right so basically the idea here is to store all of this remainder this one all the remainder in the hash map so when you see a four and then you see that this already exists in the four you basically just have to like check the hashgraph it's already there if it's already there then put a parenthesis and then close it yeah so basically that's the basic way of uh the way to solve this problem okay so yeah we can probably start coding um right uh so you need a string to store your all right that's some storing this is empty and then then you have the numerator which probably just make it n and d so basically you have to append it okay you need to convert it to a stream you just see our convey i by the way guys let's convert this thing i need toy yeah it's so wide so it's all you know how you pronounce this but it's quite a popular package in c uh okay this is the whole part and then you have the remainder part which is uh remainder part is and is mod equals to denominator and this is the remainder and then you have the fraction so you have to append a dot here so this is where uh we go with our um so from this example you got basically the whole fraction is zero which is which we divide then we have the remainder which is this right so we're gonna get into the loop until it begin it's uh zero or you found the repetition so your x condition is like while um and it's not equal to zero and you need the hash map so create the hashmap here store the ins looking something like this that's how you initialize hashmap call that right then uh if check basically if uh remainder which is n if it's in dash map is not equal to zero put an else here basically store that remainder okay what do we store we'd start a position where we want to insert the parenthesis so uh in this case it's the length of the string right because basically you start off from here in the you want to insert from there so basically it's the length land of s okay so let's check it out let's say uh you got four bro so what are we storing here basically it's like the division right so this is 400 divided by 3333 so you basically divide that um so that's the division here so you store the result to the division which is uh and divided by d okay and uh and after you divide it like this so basically you got a reminder which is four and then you add a zero right you always add a zero at the back if you can't divide it which means you always have to multiply in this case uh n times equal 10. and then you try to divide it in this case divided by zero you got a 40 you 40 divided by three to three uh it's impossible to divide it so you put a zero here you gotta see here right yeah and then you need to do a mod actually right 40 mod 0 will give you 40 back here yeah you need to do a mod so uh so in here you have to n mod equals t okay you should probably put it here and then okay let's say you found it you found a hash map if you found it in the hashmap like for example this one like you found a four here all we really need to do is just put a parenthesis and then exit out of the condition so we set n to zero so we can exit out of condition and then basically from our string basically string is equal to uh let me put this in a variable let's say entire to from starting 0 until i you append a parenthesis and then starting i until the end then you add the closing parenthesis you return this okay this one you need to again convert the you can simply add that to a string okay will this work i probably have some problem but let's try it out okay you don't have a while it's a four okay this is not the way to do it you go so far okay it works actually for 0.5 okay it works actually for 0.5 okay it works actually for 0.5 then let's try the other cases like two maybe this one and you put it like that and you need to take note of the negative number as well right okay this one okay you basically don't want to append if n is equal to zero this is the only time you append so you do want to take care of negative values like um if and is less than zero or d is greater than zero and basically a be an end right then or and it's greater than zero d is less than zero then you append uh s you take s with the dash sign so it's assigning it as negative okay let's try it out probably miss a few more okay let's try this for the value of five okay it's working seems to be working i submit it okay now we have a problem okay there's a multiple dash i think we need to do an absolute here for n so that we don't get into this problem so yeah we can do uh math that abs but this one is a float so this problem with the garland it doesn't have like a function to then you do an interior similarities with the d so negative 50 divided by 8. that's just to prevent all the okay seems to be working uh what if we just remove this and let them do the negation well the problem is you don't know if it's a negative number or you can add a negative at the bottom yeah because you're building the string you need to know if it's a negative number or not okay it works so i guess that's it yeah we got it working yeah um yeah so the other um so basically you need to know some mathematical formula here else uh you won't really be able to solve this and basically if you know the pattern of like how the division of refraction and repeating decimal works you should be able to make it work yeah we're basically top 100 percent here okay i think that's it um yeah thank you for uh for watching that's a quick one it's going to end this soon yeah let's see what's the quality of this after
|
Fraction to Recurring Decimal
|
fraction-to-recurring-decimal
|
Given two integers representing the `numerator` and `denominator` of a fraction, return _the fraction in string format_.
If the fractional part is repeating, enclose the repeating part in parentheses.
If multiple answers are possible, return **any of them**.
It is **guaranteed** that the length of the answer string is less than `104` for all the given inputs.
**Example 1:**
**Input:** numerator = 1, denominator = 2
**Output:** "0.5 "
**Example 2:**
**Input:** numerator = 2, denominator = 1
**Output:** "2 "
**Example 3:**
**Input:** numerator = 4, denominator = 333
**Output:** "0.(012) "
**Constraints:**
* `-231 <= numerator, denominator <= 231 - 1`
* `denominator != 0`
|
No scary math, just apply elementary math knowledge. Still remember how to perform a long division? Try a long division on 4/9, the repeating part is obvious. Now try 4/333. Do you see a pattern? Notice that once the remainder starts repeating, so does the divided result. Be wary of edge cases! List out as many test cases as you can think of and test your code thoroughly.
|
Hash Table,Math,String
|
Medium
| null |
1,329 |
hello guys welcome to algorithms made easy today we will be discussing the question sort the matrix diagonally in this question we are given a matrix of m cross and size and we need to sort each matrix diagram in ascending order and return the resulting matrix as given in the first example we can see that we need to sort every diagonal present in this matrix and the result will be the matrix of this kind there are given constraints with the problem the value in each cell will be between 1 to 100 this will be useful to us the first hint given in the problem states that we use a data structure to store all the values of each diagram the second hint states that we need to find how to index the data structure with the id of the diagonal and the third hint states that all the cells in the same diagonals have the same different so we can get the diagonal of a cell using the difference of i minus j so effectively the hint are telling us that we need to iterate over the matrix in a diagonal fashion that is going through every diagonal one at a time and then sorting it and updating the matrix as the start of the diagonal is from row 0 or column 0 we need to iterate first from all the way from 0th column till column number n and then we trade from first row till the m row for each diagonal the sorting will be the same hence we can have our sorting logic in a method and reuse it for both zeroth row and zeroth column let's first see this diagonal 3 2 1 so in this diagonal what we need to do is the i will be 0 and j will also be 0 then the i will be 1 and j will be 1 i will be 2 j will be 2. that means both the row and the column in a diagonal will keep on incrementing the same till they reach the boundary of the matrix we need to take all these values sort them up and then again go back to the first cell and start putting them till we reach the end of the matrix so let's see how we can code this and we will also discuss how this value of 1 200 is useful to us in this matrix we need not to check for zero column or zero row as the constraint clearly states that the number of row and column will be at least one so we will directly start off with taking row and column two variable m and n now as we discussed we need to first iterate over the zeroth row for all the columns starting from zeroth column till column number n so we will have this loop wherein we iterate from zeroth column till the nth column this loop is for all the diagonals starting from row equals to zero and similarly we will have another loop wherein we'll loop from first row to m with row and all this for column zero we're starting from row one because we have already took care of the diagonal starting from row zero and column zero in the first loop as we will be updating in the same array we will return it now the sorting logic will reside in between these loops so let's first see the sorting logic and then we can put that method in between the for loops so we will have the method sort it will have the matrix it will have the starting row and column position from where the diagonal is starting and for simplicity we will also pass the number of rows and number of columns in the matrix so first we need to hold all the values that are present in the diagonal we will see two approaches on how to implement this sort method first we will see the simpler method wherein we will be using the inbuilt sort functionalities so we will have a list to hold the value that are present in this diagonal we will take this row and column values into a variable because as discussed we will need these values again when we will start putting the sorted values so we will take them into a variable called r and c we discuss that till the two values reach the boundary we will be increment them now we will take the value present at this particular row and column and put that into our values list then we will use the inbuilt collections dot sort to sort this list now we will again start putting these values into the matrix and the same loop will work as we need an index to fetch the values we will take the index as starting from 0. so at row and column we will get the value of index and then we post increment it doing the same for row and column so that will do we need to call these method from in here the initial matrix will be the same then row in this case will be 0 column will be column and this and similarly here only the row will be changing and the column will remain zero when we run this code we get the right result let's submit this so it got submitted successfully we can further optimize this code as we see that the value in the matrix will go up to 100 only so rather than using a list to hold the values and also collection dot sort to sort the values in the list we can use count sort in this case so in order to implement the count sort we'll comment it out we'll take a array the same name values of length one zero one now instead of adding the values in this increment the values at the index in the values array we don't need the collection.sort and we don't need the collection.sort and we don't need the collection.sort and we don't need this index as well for now as we know the value will go from all the way from 1 till 1 0 1 if the number of values at this index is greater than 0 we'll take that count into a variable and now we loop till the count is greater than 0 and also decrementing it with each step that we put that in now at this position r comma c will put the value on the index incrementing the row and column like we were doing in this while loop now we don't need this while loop so let's run this so it also runs successfully let's submit this as well so it also got submitted successfully we can clearly see the time difference when we were using the collection.sort when we were using the collection.sort when we were using the collection.sort and when we were using count sort to sort the values the time complexity in the previous approach become m plus n into k log k where k is the minimum of m and n well the space complexity is of k in the second approach the time complexity is m plus n and the space complexity is off one thanks for watching the video see you in the next one
|
Sort the Matrix Diagonally
|
minimum-cost-to-move-chips-to-the-same-position
|
A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the **matrix diagonal** starting from `mat[2][0]`, where `mat` is a `6 x 3` matrix, includes cells `mat[2][0]`, `mat[3][1]`, and `mat[4][2]`.
Given an `m x n` matrix `mat` of integers, sort each **matrix diagonal** in ascending order and return _the resulting matrix_.
**Example 1:**
**Input:** mat = \[\[3,3,1,1\],\[2,2,1,2\],\[1,1,1,2\]\]
**Output:** \[\[1,1,1,1\],\[1,2,2,2\],\[1,2,3,3\]\]
**Example 2:**
**Input:** mat = \[\[11,25,66,1,69,7\],\[23,55,17,45,15,52\],\[75,31,36,44,58,8\],\[22,27,33,25,68,4\],\[84,28,14,11,5,50\]\]
**Output:** \[\[5,17,4,1,52,7\],\[11,11,25,45,8,69\],\[14,23,25,44,58,15\],\[22,27,31,36,50,66\],\[84,28,75,33,55,68\]\]
**Constraints:**
* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 100`
* `1 <= mat[i][j] <= 100`
|
The first move keeps the parity of the element as it is. The second move changes the parity of the element. Since the first move is free, if all the numbers have the same parity, the answer would be zero. Find the minimum cost to make all the numbers have the same parity.
|
Array,Math,Greedy
|
Easy
|
1895
|
1,388 |
Do that Anuj, rather the driver reached the hotel. A very classical attempt on mode 121. You must have seen this many times in contests on simple lead. Let's use the name of the question is Pizza Bread 3m Slices. You have a pizza of three slices. Ok buy pizza. Bread slice of wearing size different size An you and your friends will take life is in it and Mendis like this Pizza eater like this I can pack any cheese slice I can pack whatever speed I do in its anti clockwise election whoever is first in it Who will he take, she will take Alice, and the alarms that I clicked, the same clockwise correction, whatever decision will be changed, it will change, for example, if I took the form for, then add woman will take it and she will take the hit with five, like I take that in the electrolyte for both of them. He is hungry and we have to repeat all this until there is no slice left in your interior register license valley which shows what is the size of this price, what is the size of that size and in which order the reservation is taken clockwise. Center gave return, give you maximum possible time, give you maximum possible handle, how to pick up the pizza spices, whether maximum possible relationship will go or simple efficient tasks and is it people, you guys asked the question a few days ago to you in the starting, so in this third and fourth lecturers K Deputy's okay, where we talked about house property, house, job light or other questions, what happened to you, we said house, sorry question, you are definitely a Rover, believe me, people, this is some planet, stay for a moment, Gariya. Stay poor, stay poor, have a house, here's your Rover, if he steals in this, he ca n't steal in this edition, if he steals in this, he can't steal in this future, if he widens in this, he can't steal in this one here I was not able to hear. I have a similar question to you that if I ate this slice of pizza, I would not be able to get this light and I would have gone to this chemical fertilizer and because this is the yoga of the side and this place, this would happen now. Where is the same type of portion? Try it in Media 2019. Try to serve. There is less questioning here. How will we eat it by dividing it between two. We should face the attacks inside the Amla so that the goods are such that we are here like this. What did I do that if I stole in this house, what would I do in this house, this dough, this one used to be made like this, now if I steal in this house, then what? If I didn't like what he said, then this bag had said like this, from here to such and such house, you have made such and such relation by adding relations, now you will not be able to do this also, that is, if you have stolen in your first house, then you cannot steal in the last house. You will be able to turn off the torch light that when Bigg Boss is not there to take, then where will you put this recording, you will go inside this mountain, you can start it, you will not agree, I will not forget when you get angry or what will happen to someone else. That is, suppose I have stolen in the last house, now if I have stolen in the last house, then he can do joint because if I understand the matter and steal then this one and this fast, I should steal, power neither that's why Yudhishthir will be imposed, then it will be imposed here. In this way, he is solid and thinks of him by making him a Singh Advocate. In the same way, I gave an example regarding this please like question. So you said that what kind of license do you have in the input. If anyone has not seen the question of House from Rewa, then I will give them an example. Look at the message, the quality of you is something like this, forgive one command 2 command 1 and put our stuff on Kumar, add here sir 5pro fish is like this, ok now I said what did I say now I said you think carefully If there are three and slices of cream, then you must have thought something about it. Come on friends, if this is the tree and slide and there are three people eating, if the notes were slices and you three people are going to eat, then by loving you on your part, I am part of the era. How many feet will I go, people will not come because if I do too much, if real life is the end, then we will talk obscenely about this glass, this U, this B, this one will get it and we do n't even believe in the command to get it, whether you believe it or not. When I talked to him, I either said, if I eat total and slices, I will die, I will correct inches item line, so what is my golf, my pill is that I eat total advice, there is only one total enterprise and that is to Maximum Cyrus who That he told me that I should make it for Tibet Liberation Day Religious Affairs soon in front of you, I know after how many meals, I said this in a complete way, hr, so many times I have made it here as if I Come to eat battery size, think carefully, what is vacation called, it is a simple thing that you are talking about it, first of all it is life 45 If it takes away the breath, then I said that if you are doing this, then subscribe to know how much truth I have I am going to proceed by keeping this above so that the matter is understood, as the matter is understood, you will make it famous as-which-kiss you will make it famous as-which-kiss you will make it famous as-which-kiss play, if I am of gas to you, then you will make it famous, then I will remove the last one and If there is a second question, then you will do this process, remember that you have postponed every question, whichever of the two you have, people of Surya, you will return whatever maximum answer you get in both, whether you believe this or not. Do you agree or not, if you have to include it, if you have to fold it, then you have to remember the answer of so many lessons because it will be netted in the same type, so I have to fold it, how many lessons have you memorized that Why am I going to be late? Because this license is arranged clockwise. If I go to the razor feather in the circle then I will be able to do the teaching work. If I go to magic then I will be able to become one and I will not be able to get a five. This is the logic if you come by deception and end up. Here I said that the price of milk will increase, first of all, I have taken out the K from here, I said that I have taken out this, life is that science, okay, it means that in the case of nature, when I say the first slice, then the second one. If I do n't eat the first side, then it goes to 13351, that is, when I am eating the first side, that is, in this case, my index of the rest is zero and I have sex and I and how many sizes of people are coming after you, this is the total. Great, what do you make, tasty, did I do it first, if I don't do this, then in the side of setting show option to set tax rate, paste solution of, great, we folded, solved this here, I passed that I am standing on this and this is what I did here. But let me pass this to the total absence of you are going to eat, we will sell it, we had said 20 of wishing that suppose you have ND, who knows about the fact that you cannot eat any more for the whiteness of you. So go back, you have returned the file, this amazing phone seconds of the item, the NDA by the owners, the index again, that is magic, that Bhardwaj has tied it, the ghagras have been worn with Suvarchla, it is such that ahead of working in the office, it is in one side. Its size has been added and I take it, subscribe and the leftover induction stove starts coming, make recording call, collect one tax, okay, passed the slices here and I have eaten one, so I have to remind that I have started eating, okay, its notification should come 9 taxi 9 If you are not eating the sign, then please click on the like button. Okay, so I am here otherwise I cannot proceed further. Call me and subscribe. So in this way and what you used to do is that this chapter is done, we have really submitted it, this is our body, today's our romance, why Narayan, then why have you killed us brother, why have you given this wrong answer and this is the house. Prakriti Ishara 32 OK, we took out this OK that Shamsher Alam, 21 years old, here we took 200 index, if I send it in the pendant here, if I indicate here, then I gave the end content here and in this sentence I here We will apply one ax and one ax. If you have moved ahead then returned it. If it is not for consideration, then think carefully. You have the goods to process this. You said this way, you said that like this solution, this way. If I take the first one, which is 12345, then I know that I don't want to spoil it, then I started doing friend or waste, if it was the total length and end, then this MS Word got angry with them, that is, inside behind the rock, I got enema. I have to do restaurants i.e. let's assume restaurants i.e. let's assume restaurants i.e. let's assume that Taimur is a miracle, here I will start from one, I have taken this one, what is the next case, I have taken the last one, that if I put this one in me, don't take me, you will talk. So here I am, now I have tried it, where is the phone, where is it is disgusting to index, now run it, very good, I have submitted, this is the quick decision taken for today, after this type, now you are here But there is Meghnad in it, he tells you to subscribe to the channel, if my channel is broken, then what did I do, I went here and I said, let's start, okay, I said, the first thing I have to do is that audio alarm. If you have to set then the first thing is to dighat I said Sector-22 B so matter of a matter of Sector-22 B so matter of a matter of Sector-22 B so matter of a matter of paint that BP of which size of this size if we look carefully for the index of the size and take it out you have to make intake and If you have to make this for them, then if it is considered to be an indication, from the roots till the tip till the end and if we talk about this soldier, then it gets tired in your body, then creating your confusion, rule fairness first in the hospital. Was it a person or a society? Okay, I welcome all four children. Okay, after doing these three, I took it like this and after turning it on, it became now I made two kiss calls here, collapsed kiss, which alarm is the first case. Is this one of yours, I am international, for the second one, this one is good, okay, I have passed intermediate, a person who gives solution, ground coriander, fennel, minimization, less accidents, okay, how much work has been done, why does cancer happen, then it is called Madikeri Smart. I was India, changed it here, made the video believe, now passed it here too and this is the one with DP, passed you yesterday in the upbringing of college, today I have made a commitment, then snatched it. Now after this, they set this here and soft doctors in the dark, there is an atmosphere of lady sp of index at the medical store that this year's auspicious and second thing, where the atmosphere is over and there is a difficult place to take the wicket. The answer is, his problem is that the dead body of Kala Difficult Words From is lying, so do the computer work alone from here, now I have called him and let's check whether it works or not, then he said, what is this, I said sorry, guys, sorry. Very very sorry, now run the attack, leave it and submit it, brother, include everything in quantity, you people of Sarabjit, this is not crores of rupees, where did you make a mistake, we said, this is a chapter, this DP has been made, this is that the master is going till here. It is going to come to this Vansh's return, access here, do any mess, yes I don't do internal mess, you try, what a very cute mistake we made, because here you will use the label Aishwarya, because that is the same Sam DP, hey. I will use this call-girl is wrong, so I am here use this call-girl is wrong, so I am here use this call-girl is wrong, so I am here for this also, okay, and here for this second one, for the second records people, there is another DB guy from Banaras and passing it like this. Keeping patience, issued separate orders to the officers that it is successful and submit, it will be removed, now we should go and go, so here we do a very top 10 to 12 times and from home to where to subscribe and in this way now I We have to use waterproof, it can be used a little, so now we have come to our solve tab function, the solve tab has been written by unknown persons, within the main 500, we have passed it here, okay now after that. What to do is very simple, so before that, the biggest task is to relate half, depending on Rehman Malik, your license is very good, half is requested, the is very good, half is requested, the is very good, half is requested, the great do the second one and one defeat to do a great do the mixture vegetables. With the managers and I said what to do after this, apart from this, I had the work that I have to make my speakers nice by selling them as gifts and accordingly I have to call withdrawal airways, so if I write from here, then a few couplets of these two. If I have full faith, then I have nothing to do, so I have no intention of doing anything, now what I said was that Krishna had done the best thing in this case, from zero to K-suit, okay, so zero to K-suit, okay, so zero to K-suit, okay, so we are like this as much as possible. Time Thought To Myself Will Go Simple So You Stole A Flop You Run A Showroom And Index Request To K Himanshu To Inducted Into 06 - - A 06 - - A 06 - - A That After This Your Number Of Places Was Okay By Three Se After going towards more zero, I definitely used to go that top-down returned with homemade Tata, this only you will run it simple, I will search for shift on you, go that top-down returned with homemade Tata, this only you will run it simple, I will search for shift on you, go that top-down returned with homemade Tata, this only you will run it simple, I will search for shift on you, for any damages, costs 20 is equal to two, three is l and n plus, if you write from here, can I? To collect your 120, go up, the answer is definitely antique ruby, it is 30 inches, so it is not for clicking on these districts, set it off, okay, what should I write inside, it is written on its do, write it, copy it. What should you present, make them international with color, share them, let us convert it into this code, I will repair it. Okay, so I said, convert it into solve member leadership quality and reach DP off and here it is used like this, then do it. Sam is converted to D on Di, similarly, this is to be converted Chaddi P1, this is how we have hit on this here we have given this precious, okay, so this is how I have converted this in my DP tuition solution. Inside and very good light, in this way I have filed a case, which gas is this, Ashwagandha, this type, so where will my answer be saved here, so where will my instrument be saved here and it would be simple. The answer to K's dream is coming to you, where is DPO 90 and K? Okay, I have understood now, it is a food item for me, I have done it from here to this why are we going on like this Be it - you have to why are we going on like this Be it - you have to why are we going on like this Be it - you have to go towards 101 and what did you do? Everything is going to be SIM from then onwards it is going to come but it will be made here. Now we have written these two answers in the update of Maths. The name of this lineage of Decrese Two is Sukma. K to Ghaghare, call him immediately, Kam commented, we said turn on, do n't forget to subscribe to this channel, given its name, if you do, you will talk about these, now watch the talk carefully for half an hour. Friends, if you look carefully then you will understand that this is K-2 and you made the will understand that this is K-2 and you made the will understand that this is K-2 and you made the contact clear, then you and Top went to an inter college in Bundelkhand region, this is youth, you invest in the Indus, further here from don't want to What did you do? Do it safely. To remember, I have made it to the Play Store. It will be affected. We have done it. We have submitted it to WhatsApp and it is successful. This is how we solved the schools using Our tabulation method, this is our tabulation method, then the question is, can I further optimize it? Diver seems to be big in the Play Store, but the question is, can I make Aamir match it? What space optimization do I do here? Is it possible or not? Look at the time on which the DP of one depends. While calculating this, you said Dip of the P1 which is the index training, it depends on it. Look at line no. 23, DP of one index plus two ok, these two raws are ahead. Two raw ahead depends on someone online number four look at China index plus one okay grow them ahead depends on someone did you understand that I am late what should I say to this row what should I say to him that its name is security current to the previous If she goes and has a high neck then I can solve this question in three processes in three days Same Slice Pintu Syrup Laddu db2 So I had to make three forms and the work would be done There is no one to make UTI so my DP Varney became deadlocked How should I forget tractor center like notification, what size women's plus two science university press, it is very good, I made two more like this, previous one, current top and next one, so I said that I am calling the index one as Brijesh. So that means here it will be changed, here it will be made previous, I said, I am calling the N Carefully read this thing, three diseases of matters are like this, 3 pro is like this, one should be away, 30 if in starting, your previous is on this, your current is on this, your next is on this, till inside a train, in the latest, why and Just write carefully, in the next hydration the next will reach here and the current will reach here, so can I take that next will happen in one well of your current and the current will be yours but it is going to happen in the middle of one hydration, absolutely brother, I stopped completely and said in the room. That whatever is our next, she will go to that icon of current and current, this is our education quality quarter at one place, it matters of 2 statements and it matters, now there are two chopped in it, so this is I gave the son of db2 by these three. Put into work the previous two were the current two and the next one which has changed here is the next two whose name was This statement has been tension so here it will be so changed its name that a to how to this way cricket questions and pieces of and are reinstalled we said take this from yours here the current went out from inside current one and This answer will come out of the control only in this way, we have sorted it out, let's try it once inside the solitaire box or enter 9.00, inside the solitaire box or enter 9.00, stretch it and first make a space here so that you feel that it will be formed into slices soon. Now here the continuous action of space three to two because it seems that you are done with it, the fun of it is gone, money earn, Shankar is inside it, A is successful, but in this way, we have solved the schools and if you could see, you can see a little bit of the solution. It might seem that it is a bit easy, okay, so this is how we solved it took a lot of time, okay, there were notifications and they took our SIM from each other's officers, see what reaction they had, this week also made her less pregnant. If you look at the solution, how much capacity is there, from where you can see, this is your time, it is going on, by brother, set the time, by whom it came here, by whom, it is right here, time for elections, from Reddy, this is the superintendent of teachers, our money will come verification. Solved it and blessings, it's time to understand that if we talk about there are strings in the budget and it seems that if you comment, I understood brother, I enjoyed it, this is a very dirty video, then I will get peace, friends, did I In the beginning, 34 opinions are not that you would have seen and here after the contra voucher, Ajay has not freed his daughter to a great extent.
|
Pizza With 3n Slices
|
greatest-sum-divisible-by-three
|
There is a pizza with `3n` slices of varying size, you and your friends will take slices of pizza as follows:
* You will pick **any** pizza slice.
* Your friend Alice will pick the next slice in the anti-clockwise direction of your pick.
* Your friend Bob will pick the next slice in the clockwise direction of your pick.
* Repeat until there are no more slices of pizzas.
Given an integer array `slices` that represent the sizes of the pizza slices in a clockwise direction, return _the maximum possible sum of slice sizes that you can pick_.
**Example 1:**
**Input:** slices = \[1,2,3,4,5,6\]
**Output:** 10
**Explanation:** Pick pizza slice of size 4, Alice and Bob will pick slices with size 3 and 5 respectively. Then Pick slices with size 6, finally Alice and Bob will pick slice of size 2 and 1 respectively. Total = 4 + 6.
**Example 2:**
**Input:** slices = \[8,9,8,6,1,1\]
**Output:** 16
**Explanation:** Pick pizza slice of size 8 in each turn. If you pick slice with size 9 your partners will pick slices of size 8.
**Constraints:**
* `3 * n == slices.length`
* `1 <= slices.length <= 500`
* `1 <= slices[i] <= 1000`
|
Represent the state as DP[pos][mod]: maximum possible sum starting in the position "pos" in the array where the current sum modulo 3 is equal to mod.
|
Array,Dynamic Programming,Greedy
|
Medium
| null |
141 |
So the name of the question is Link List Cycle. You will find this question in the lead code 141. So let's look at the problem statement. You have a link list and in this you have to tell whether it is a cycle or not. This is the example I have taken. In this, first of all we We are on the head which is van, from here you will go to next, you will go to a, from you will go to four, and from four, you will go to next. If there is tap, then there is no bicycle here, so you have to return false, so we have to return true or false. There is no cycle, it will return false, let's take another example, you will go from three to three, from three you will go to four and from four you will go back to you and you will get trapped in this cycle because after coming back to you will cycle again. If then you have to return true so this is our problem statement so let's quickly see some approaches then we are going to discuss two approaches Using Has Set So this is a data structure in Java, you cannot store duplicates in it and what it means Lookup time is, if you guys can do it in constant time, then the first approach will be based on this. The second approach will be more optimized using flight cycle finding algorithm, this is also called hair and toys algorithm. Okay, so these are two approaches. If we are going to do this, then quickly go to the first approach, this is our has set and take a link list inside which there will be a bicycle, so this is our bicycle. Okay, so what will be our approach? First of all, let us take the load on the head. Store it, okay, after that you will , next okay, after that you will , next okay, after that you will , next note you will store tu hai tu ko, tu se again you will go to the next, if you store note 3 for free, you will go to the next note is four, so here again of you store. You are doing this, but this is already stored in our set, so it will be rejected because as I told, the set does not store duplicates, okay, if it is rejected, then you will understand, then you will return it, you can quickly see the time complexity. You will add all the notes in this set. If it is fine, then our time complexity will become bigo n because we are going to visit all the notes. The list is fine and as I told you, if you store all the notes in a year, then you will know the space complexity yourself. Which will be Big of N, then there will be a simple code for this, I think everyone can code this, it is going to be very easy, now let's move on to the optimized approach which is our flight cycle finding algorithm, so take a quick example. Let's take this is our link list, okay and we are coming from four to you, we have cycle, so this is the hair of being in the algorithm, we will do it with two pointer, one will say slow pointer, fast pointer will say, slow pointer will go one position ahead, fast. Pointer 2 position will go ahead. Okay now if you move both the pointers in the first attraction then what will happen in the first attraction, slow pointer will go to you because next from our van is you but if one more moves forward then after you we have free four. What's next, if you are next, then our fast pointer will go on tu, okay, now let's do one more, fast pointer, if you are on, then our fast pointer will go on 2 to 3:00, then on then our fast pointer will go on 2 to 3:00, then on then our fast pointer will go on 2 to 3:00, then on 3 to 4, so after on the thirdration, okay. Both these pointers are at the same position, so here we will know that there is a cycle in it and we will return it. Now let us understand it in a slightly different way that how these two pointers are matching, so for this I have to We will have to draw a circle, let's say that the slow pointer is somewhere here and the fast pointer is somewhere here, so I want to tell you why these will be found every time. What is the proof that these two pointers will always be found whenever there is a cycle? So let's see once that the distance between these two is five units, okay and this difference in units is okay, so the slow pointer basically we know how it will go 1234, something like this, it takes steps. And when he takes the distance, the fast pointer will be at 8. Okay, so one more, let's write 5n here and 10. Now let's see the difference, what is the difference between these two points. If the fast pointer has gone one unit ahead, then it will catch it. So what I mean to say is that whether this distance is 101 units or 19 units or 500, both these pointers will meet every time because their difference is increasing in multiples of WAN and all these numbers are related to WAN. If it is multiple, then this fast pointer will always catch the slow pointer. Okay, so every time there is a cycle, both these pointers will meet. Okay, now in one last point, I want to explain to you that this is a slow pointer, this is for example, there are many things inside it. If all the notes are there, then this is five units, meaning after traveling 5 notes, the fast pointer will reach the slow pointer. Okay, this van tu three four pe a is going, okay, so we know that if this is a bicycle, okay and a little more. If we increase one or two more notes, then if there are five units inside this cycle, if there are five notes, then in the entire link list, then give more, there will be five units, there will be more than five notes, right, so I want to tell you that fast pointer when If it catches the slow pointer then it will travel less denotes, okay, it does not need to travel the node, by traveling less notes, it will catch it and our algorithm will be completed because there are nodes in the entire link list, okay and the 5 If we take the example of the unit, these five notes, then if you look at the comparison of the entire linked list, it is very less. Okay, so the time complexity of this algorithm will be Big of N because even after coming in the cycle, these are very limited numbers of We are traveling through the notes, there are not many iterations happening here, okay, so I want to tell you that because of this, its time complexity is Big of N and its space complexity, but we have given it two pointers ] It is a constant, it will not increase, only two points will remain, so with this, you guys must have understood this approach gas, if not, then you can watch the video again by going back, you jump directly to the code. This is our fast pointer, this is our slow point, so what we are checking here in the loop is that if there is no cycle then the fast pointer is going to go straight and hit the tap. We know that the speed of the fast pointer is higher. It will hit the tap. Okay, so we have set the condition that if it hits the tap, then we will exit this wiring loop and return will fall down. Okay, but here the fast pointer will go at 2X speed and every time you check. Take this and you will get this percentage every time, both of these are going to be met, if there is a cycle, then add a simple condition here, if both of these are found, then there is a cycle here and return true, then this video ends. Thank you very much for watching this video. There are many videos on my channel. Go check them out and if you like the videos then subscribe. Thank you very much.
|
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
|
876 |
Hello friends welcome back today I'm going to solve liquid problem number 876 middle of the linked list this is a so what are we given is we are given a single linked list of length n so it could be of an odd length or an even length and we need to find out the middle of the linked list so for an odd length it's obvious right the middle is where the number of nodes to the right and the number of nodes to the left are equal but for the even in case of even actually the middle lies with lies somewhere where to the right it has one more note I mean to the left it has one more note than it has to the right so how are we going to solve this using two pointer let me show it you here um so we actually Define two pointers and one of the uh we will actually have a fast pointer and a slope pointer so let me uh both of them are first uh pointing to the head so pointer and our fast pointer so what is actually super pointer and what is actually fast pointer so slow pointer only moves one note so slow only move one or which is slow in the next iteration will be equals to slow that next whereas fast pointer it moves two nodes so it jumps two nodes so fast in the next iteration will be equals to faster next that next so let me show you here in this figure itself so before that let me tell you about the logic here um so when we have uh one two and a three right so we are starting from here um so fast is moving two steps here we could see fast is moving two steps slow is only moving one step right so every time what happens is fast is double the steps slow has moved so fast and slow if both of them are here in the next iteration slow is here but fast is here and that is when we have reached our middle similarly in this next iteration if we have one more then fast uh fast is actually next of next so our fast is equals to none here and our slow is here in that case this is our middle value so here also we are going to do the same thing so now my next slow is equals to slow that next and my fast it jumps two notes one no two notes so fast that next so this is my fast now again I jump slow and then I jump two notes for fast and now my fast is here now we have reached our middle value of the list here next um we start for this one when the length of the least e is equals to even so I um the next iteration my slow is here and my fast is here right and the next iteration my slow is here and then my fast is one note two notes so it's here and the next iteration my slow moves to the middle and when my slow is in the middle my fast moves one node two node so my fast is equals to null here now so this is when we have actually reached our middle so how do we identify we have reached a middle if fast is the next of the fast is null or if the fast itself is equals to null so that is when we have reached our middle pointers so let's get started now with our code uh we Define slow equals to head fast equals head and then while fast we have fast and faster next so if we have fast and we have fast as the next because our H condition is when fast is equals to null that is when we have reached our middle value or when fast that next is no land is when we have reached our middle when slow has reached the middle so that is when we return slow so what are we doing we just update slow that next and then update our fast too fast that next step next so that's just everything that we need to do for this problem and you see it's so easy okay have a great day guys
|
Middle of the Linked List
|
hand-of-straights
|
Given the `head` of a singly linked list, return _the middle node of the linked list_.
If there are two middle nodes, return **the second middle** node.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[3,4,5\]
**Explanation:** The middle node of the list is node 3.
**Example 2:**
**Input:** head = \[1,2,3,4,5,6\]
**Output:** \[4,5,6\]
**Explanation:** Since the list has two middle nodes with values 3 and 4, we return the second one.
**Constraints:**
* The number of nodes in the list is in the range `[1, 100]`.
* `1 <= Node.val <= 100`
| null |
Array,Hash Table,Greedy,Sorting
|
Medium
| null |
1,705 |
hey what's up guys this is sean here again so let's take a look at uh this one uh 1705 maximum number of eaten apples so i'm going gonna give it my own upvote so you're giving like a special apple tree that grows apples every day for end days okay and on the ice day the tree grows apples ice number of apples that will rot after this number of days so which means on day i plus days i the apples will be rotten and cannot be eaten and now some days the apple tree does not grow any apples which are denoted by zero and you can only eat at most one apple per day to keep the doctors away okay if there's any apple that has not uh got rotten yet and here note that you can keep eating after the first end days so which means that you know even after the first end dates if there's still some like apples left you can still eat them so given two integer arrays days and apples and you need to return the maximum number of apples you can eat so for example right so this one on days on the first day on date zero the apple trees uh can produce to make like one apple that can last three days so which means that on day three this one will be rotten so on day two here we have two apples who will also be so this one will also get rotten in day three or day four whatever or either zero base or one base same thing for this one for one right so this one on day three here we have three apple that will be rotten in one day so that's gonna be also another uh three apples that will be routine on day four okay so on and so forth and so in the end we can have like we can eat at most seven apples in total so yeah and here are some constraints right cool so i mean this one i think the a normal approach is that you know let's see if we have on a certain day on the ice state here let's see we have searched some apples right we have some apples here we have apple here we have some apples here so i mean a common or a reasonable approach that is that we always want to eat the apples that will cut rotten first so let's see we have these three apples so let's see this one let's say we have car dice let's see the current day is day three and if we have this two apple uh one apple that will be rotten in day four and then we have like another so this one will be rotten in day six this one will be rotten in day five so obviously we always want to eat the apples that will that's close to the current date right the routing date is close to the current date that's why that's how we can eat at mo as many apples as possible yeah i think that's the basic idea for this problem you know and to keep the closest state for the uh fraud apples right i mean a common approach is by using a priority queue right where the in the product queue basically for each of the elements in the product queue will save two uh numbers so the first one is the rods and date right these days that the apples will be all rotten it will get rotten and then the second one is that number of apples okay right and then we just get the uh every time when we try to eat the diapers we just get the first one of the priority which is the smallest date right and then we decrease the apple by one and then after that we check if the current element has if the output has been decreased to zero if it is then we should remove this one up from the priority queue because so why is that because at the at each new date we're going to insert this the same we're going to insert the element into the prior queue so which means that at each at the same day we could have multiple um numbers uh element for example this one right so at so here we have at the day one here right so we have one apple right that will got rotten in day three that's why we have three and one and then at the day two here we have what we have another one which is the uh we have also got three day three going to be the wrong data with apples we have two and in day three here we also have like three and then we have three so that's why you know every time when we have uh decrease the numbers from this one we're gonna remove this one so as long as this zero this number of apple becomes zero we'll remove it so that the next time we can consume the next one in the priority queue right yeah and that's that so we just keep doing it and oh and one more thing and every time when we add that say a new date here we'll also be uh removing the product queue first because let's say if we are at day three right if the is three here and we have we still have some uh apples that's left in the product queue right then it means that anything that's either equal or smaller than the current date those apples they're all they will all be rotten right so which means that we will need to pop those uh elements out from the priority queue yeah and that's that so that's the only two things and then of course in the end we also need to uh figure uh handle this one handle the uh this special case which is the uh you can keep eating after the first end days cool so i'll try to explain a little bit more while i'm doing the how i'm coding so first thing first we're going to have it about like the priority queue right then we have a length of apples and i'm gonna have like the answer equal to zero right so for i in range of n here okay and if apple is not empty right because we could that the tree could produce nothing on the on this on the day that's why we only gonna insert into the queue when the apple is not zero and then we say let's insert right to the product queue like i said so the first one is going to be the i the date right so the dates those apples will be rotten that's going to be day i plus day i right then the apple will be the iphone's i here so the reason i'm using a list instead of like a tuple is that you know later on i will i'll directly modify this apples here if we do a like tuple like this one i cannot do an in-place modification i cannot do an in-place modification i cannot do an in-place modification that's why i use a list here so and here remove pop out the rotten apples right so basically while the priority queue is not empty and the product q dot zero is smaller equal smaller than i then i just keep q dot pop right so the reason i can pop from doing the priority queue pop is that you know the pq 0 is always the early state right so that's why i can always do the pop from the left the by using the current date okay and then eat an apple right who has the earliest right earliest routing date right here so here we need to check the priority queue one more time if the product is not i'm empty because it's possible that you know there's no apples left at this at the moment and if this one and yeah so if the product use i still have some apples left here and then we just need to actually do an answer plus one right because we are we have ethanol sir and then we have eaten an apple and then the we just need to decrease the product zero one by one right that's going to be that the number of the apples left and then if the product q 0 1 is empty sorry it's 0 which is a heap q dot heap pop the prodigy right so if there's nothing left of the kernel element let's pop this thing out so that's that okay and let's handle the uh i know the case that after the end state we still have some apples left in the priority queue so now we have n i equals to n here right so same thing right priority q whenever the product queue is not empty i can just literally just copy this part okay you know the uh to here it's basically the same logic the only difference is that now we don't have any new apples coming in but at the each day here it's still the same logic here right to pop out the rods and apples for the current date and then we eat an apple right then whenever the particle is empty that's when we stop okay and here don't forget to increase the i by one and then here we just return the answer yeah i think that's it so if i run the code here accept it so that's it right the uh so the time complexity right so and the time complexity for this one is so the product q is it's like the uh it's n log n yeah so i would say it's unlocking right because we have a off in here and each time and for each of the elements we have a prior key which is going to be the login here for push pop and same thing here right so here is also like the uh and login i would say that right because you know let's say we have like a big days right here after this end state but still like this here is its end right so the same as the apples that's why the end is like the 2 to the i mean this is the 10 to the power of 4. so yeah i would say the total time complexity is unlocked yeah and the space complexity is it's often right so the priority queue uh yeah so the worst case scenario is we're gonna input every so the particle can have like up to the number of elements of the length of the end here yeah i think that's it right i mean this is like a typical use of the priority queue so that we can implement this greedy approach and by always eating the apple that has the earliest rotten the route the date the rotten date and then yeah other than that it's just a bunch of uh minor places that we have to pop the rotten apples right at each of the new each of the date here and then also like the uh if this current element has zero apples left we need to pop it out so that you know we can keep eating the other apples yeah actually and then another yeah or you can like the uh not keep increasing keep like uh sorry just yeah i forgot forget about that so yeah you have to keep pushing into the product queue at each of the date here and then the last thing is that you know once you have finished producing the apples then you have to basically utilize use the same logic to keep eating the apples until there's nothing left in the prodigy yeah and then there you go cool i think that's it for this problem thank you so much for watching this video guys stay tuned see you guys soon bye
|
Maximum Number of Eaten Apples
|
count-unhappy-friends
|
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`.
You decided to eat **at most** one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days.
Given two integer arrays `days` and `apples` of length `n`, return _the maximum number of apples you can eat._
**Example 1:**
**Input:** apples = \[1,2,3,5,2\], days = \[3,2,1,4,2\]
**Output:** 7
**Explanation:** You can eat 7 apples:
- On the first day, you eat an apple that grew on the first day.
- On the second day, you eat an apple that grew on the second day.
- On the third day, you eat an apple that grew on the second day. After this day, the apples that grew on the third day rot.
- On the fourth to the seventh days, you eat apples that grew on the fourth day.
**Example 2:**
**Input:** apples = \[3,0,0,0,0,2\], days = \[3,0,0,0,0,2\]
**Output:** 5
**Explanation:** You can eat 5 apples:
- On the first to the third day you eat apples that grew on the first day.
- Do nothing on the fouth and fifth days.
- On the sixth and seventh days you eat apples that grew on the sixth day.
**Constraints:**
* `n == apples.length == days.length`
* `1 <= n <= 2 * 104`
* `0 <= apples[i], days[i] <= 2 * 104`
* `days[i] = 0` if and only if `apples[i] = 0`.
|
Create a matrix “rank” where rank[i][j] holds how highly friend ‘i' views ‘j’. This allows for O(1) comparisons between people
|
Array,Simulation
|
Medium
| null |
547 |
hey everybody this is Larry this is day four of the June liquor day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's form 547 number of provinces I'm still here in Irvine um in Romania I think a couple of days off from hiking because uh kind of my back is sore if you kind of notice my uh I've mentioned this before uh I'll probably have some more drone videos in the future I'm going to just you know not tap one today I suppose uh but yeah number of provinces so there are n cities some oh yeah if you want to follow me on Instagram uh to kind of see what I'm up to I just look at pretty pictures uh that would be great I don't know anyway and cities some of them are connected some are not if a is B and ASC is connected indirectly okay uh okay so yeah so basically a province it's just a connected component right yeah so province is a connected component or you just try to find the number of connected components and of course you can do this with uh traditionally breakfast search that first search Union fine and Etc right um I think that is I mean I don't know I mean you can do it any of those ways the thing that is a little bit um yeah I mean I don't know because here you're given it an adjacency Matrix which is actually not a format that I'm usually given for whatever reason this is why I'm giving some cards um I honestly I'm just trying to think whether that in like is there a way that you can kind of take advantage of it a little bit more but I guess that's just part of the product input format right because technically when you do stuff like we plus e and stuff like this the E part um you're given like you know you're given a matrix of or zeros and that's at that point then your adjacency Matrix which is going to be re-square no Matrix which is going to be re-square no Matrix which is going to be re-square no matter what first so for a sports graph is still going to be re-squared so now your going to be re-squared so now your going to be re-squared so now your e part is actually not part of the analysis right so it's a little bit awkward but I think that's still the case so yeah so you could do this search that first search whatever uh I'm out there with that first search so uh you should flip a coin but today maybe not so much so yeah so let's just get to it then and yeah uh yeah whatever right so now we set it up and then you know maybe provinces I was gonna buy islands for some reason uh if not you stuff I um what do you want to say travel maybe Traverse I and provinces uh and you know this is just kind of the number of provinces and of course you do need a Troublesome thing well that's true worse okay that's why I was like why does this word look funny um yeah and then let's start Maybe uh all right shoot that and start is um and then current is equal to q that well it doesn't really matter if you pop left or at night but yeah and then for I in range of n we have disconnected I then um then yeah I used I as usual okay and that's pretty much it really I think yeah let me give a submit hopefully I didn't make a certain mistake and yes I did not 1160 and yeah and that's all I have for today I mean I think we've been doing connected components a little a bunch like recently so yeah let me know what you think uh yeah stay good stay healthy to go mental health I'll see you later take care bye
|
Number of Provinces
|
number-of-provinces
|
There are `n` cities. Some of them are connected, while some are not. If city `a` is connected directly with city `b`, and city `b` is connected directly with city `c`, then city `a` is connected indirectly with city `c`.
A **province** is a group of directly or indirectly connected cities and no other cities outside of the group.
You are given an `n x n` matrix `isConnected` where `isConnected[i][j] = 1` if the `ith` city and the `jth` city are directly connected, and `isConnected[i][j] = 0` otherwise.
Return _the total number of **provinces**_.
**Example 1:**
**Input:** isConnected = \[\[1,1,0\],\[1,1,0\],\[0,0,1\]\]
**Output:** 2
**Example 2:**
**Input:** isConnected = \[\[1,0,0\],\[0,1,0\],\[0,0,1\]\]
**Output:** 3
**Constraints:**
* `1 <= n <= 200`
* `n == isConnected.length`
* `n == isConnected[i].length`
* `isConnected[i][j]` is `1` or `0`.
* `isConnected[i][i] == 1`
* `isConnected[i][j] == isConnected[j][i]`
| null |
Depth-First Search,Breadth-First Search,Union Find,Graph
|
Medium
|
323,657,734,737,1085,2206
|
235 |
hello everyone welcome to learn overflow in this video we will discuss about today's later problem that is the lowest covered ancestor of a binary search tree this is a easy level problem and we'll understand what this question is asking us to do and how we can actually solve a question like this so this is easy level question that this won't be having much complexity but uh understanding this question is really interesting i'll make you understand exactly how you can think on finding a solution like this how easily you can do those and how interesting the question is so what's till then i this will be interesting as well but before starting this video make sure to subscribe to this channel for regularly videos like this so a question says uh given a binary search tree so it says a binary search tree is given the binary system means uh the root value like is the middle value and all the value on the left and the root are less than the root and all the color on the right of the root are less than the are greater than the root of value so you can see like there are five three four two zero all are less than six and there are seven eight nine all are greater than six so that's the binary search tree so that's given to us okay it's more or less you can think it's kind of a sorted order okay if you know the order then it's kind of sorted for you now uh let's uh look further what's uh what we need to do with this it says we need to find the lowest common ancestor lowest carbon ion system that is the lca node of two given nodes in the binary system okay there are there will be two given nodes uh look here there are p and q are the two different nodes and this is the root the main whole tree given to us we need to find the lowest common ancestor of the binary system so what uh this lowest common ancestor is like given a definition as per wikipedia that ah this is defined between the two nodes p and q the lowest note t ah at uh that has both p and q descendants uh where uh why we allow the node to be descended of itself okay so what it exactly means let's uh understand this say you were given two nodes as uh zero and say five okay so what's the lowest common ancestor the lowest curve ancestor for us will be two fine that would be two so as per the question uh example one if you see the given nodes that pair two and eight so two and eight are the two nodes what's the lowest common ancestor and system is the node above it's uh six okay uh so that's the answer to us there's a six so uh other way what would be the other way other would be see say we are given two nodes a zero and two okay so what will be the lowest common ancestor of this so you might think that zero and two the ancestor of two is uh six so we should go ahead with six no we should go ahead with two because zero and two uh have ancestor uh like the lowest ancestor is two itself uh because uh the last line over here where we allow a note to be descendant of itself okay so that's the reason we go ahead with two okay if a situation like that arises okay so the main idea is not like the idea is simple okay we are given two nodes what will check we'll check uh for each of the root okay uh each of the tree root or maybe the sub trace of each of the sub trees we'll keep on checking if uh both these nodes uh are less than the current rule or are greater than fine so if it is a if both the roots are less than the current root then we'll move into the left subtree fine if both the roots are greater than the current root then we will move into the right subtree five and if not if we don't if we find that both the roots are on two sides or not uh both the roots are not less or not greater okay there isn't any condition of equal to there is a condition only for less than or greater than fine and we will need to check that for both the root so if both the roots are not less or both the roots are not greater then the whatever the current root we are at that's our answer okay so that's our answer for this particular uh particular test case so that's the way we should uh look ahead into it okay so we need to check that if both the roots are less then go with uh a particular one i'll go with the left one if both the roots are greater go with the uh right subtree or uh if these two conditions fails then simply go with the return the current route okay so that's the understanding of the question now uh if you just uh like look at ahead into the uh complex constraints that we are given the constraints are see the nodes lie in the range 2 to 2.5 so the nodes lie in the range 2 to 2.5 so the nodes lie in the range 2 to 2.5 so you are sure that there are two nodes at least so there's no need to check whether this uh root node is null or not so that condition uh doesn't uh that doesn't hold in this case because you are given that there will be at least two nodes uh for sure fine and this is the range of the node val value can die anywhere and if you also give it all the values are unique so all the values are unique that means there is no chance of duplication or no chance that the values uh might be less than or get at the top but like there cannot be repetition of numbers so there can be a double answer to our question okay and also given the p is not equal to q so p is not equals to q that means uh both are not a single node that's also possible uh okay like you know like you may not think that uh both nodes are given to a single node okay so that's not a case okay also uh it says like p and q will exist in the pst so uh it's uh you can be rest assured that uh p and q these two numbers given to us will be there like it may not happen that you are searching for it and you didn't end up finding anything so that's won't be a case so that's all the they have uh like in our constraints so now it since uh i don't think it's too hard to think of how we can go ahead with simply let's write some two three lines to solve this code and then i will explain again how we uh solve this as far what we thought of uh thought of the pro way of solving this okay let's write the so that's it guys you can see that this is a six millisecond solution let's understand what uh the what we exactly did in this question we first uh checked if the p val is less than root well and i remember this and q val is less than root so if both the values are on the list less than the current root value then we should go with a root dot left uh okay then you should left okay in the left subtree uh in the other case if the p val is greater than root value and uh q value is greater than root value if this host like if both are greater than the current root value then we should go with root.right okay then we should go with root.right okay then we should go with root.right okay if that's not the case like both are not on same side or anyone is equal to the root or uh both are in the different size okay if those kind of condition arise we simply return that this is the root no words uh spoken this is the rule this is our lowest coverage system and that's the perfect way to do it and you can see that this works pretty fine this gets accepted as a solution so that's the whole idea behind this question i hope i can make you understand how we can solve a question like this uh if you have any doubts make sure to comment them down on the uh comment section below i'll be happy to help you out also all the description or all the description of this problem or everything related to problem will be there in the description section uh make sure to check that out for uh other details about this problem and uh make sure to like the video also so that it uh in case you were better reached other people to understand that and also make don't forget to subscribe this channel for regular videos like this so thank you all for watching this video i hope i can make you understand how to solve this kind of questions so hope to see you soon in my next video as well thanks
|
Lowest Common Ancestor of a Binary Search Tree
|
lowest-common-ancestor-of-a-binary-search-tree
|
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
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 = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 8
**Output:** 6
**Explanation:** The LCA of nodes 2 and 8 is 6.
**Example 2:**
**Input:** root = \[6,2,8,0,4,7,9,null,null,3,5\], p = 2, q = 4
**Output:** 2
**Explanation:** The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[2,1\], p = 2, q = 1
**Output:** 2
**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 BST.
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Easy
|
236,1190,1780,1790,1816
|
150 |
hey guys welcome or welcome back to my channel so today we are going to discuss another problem is evaluate reverse polish notation so in this problem we'll be given an arithmetic expression in Reverse polish notation so if you do not know what reverse policy notation is I would highly recommend just go through this article here and so this is reverse polish notation which is given to us and we have to evaluate it and we have to give the output so valid operators are plus minus multiplication division okay it is guaranteed that there will be always a valid answer for this expression okay and there would be no division by zero operation so it's fine that it will give you the correct output so let's see how we can approach this problem so see what we uh basically what is the answer how we have to evaluate it so this 2 and this one Whatever the operation is before these that operation will be so basically for so let's say this is Operation right so the numbers two numbers which are previous to this operation will be executed on those two numbers so 2 plus 1. so we get 3. so this whole thing is replaced by three then left is this okay so now here this is our operation so previous two numbers which is this and this so This operation will be applied on those two previous numbers so three into three nine so nine will be the output okay so guys Wherever Whenever you have to like you are involving some previous numbers right previous numbers you have to use previous numbers in that case you can think of using a stack because in stack we can know the previous number so if this is X this is why we can know why okay by popping X we can know why so we will use stack in this problem so let's quickly see how we can use stack to 1 plus 3 star so we'll take a stack we will iterate this string from starting if we get a digit if this is a digit so we will simply add it in the stack so when again we go this is a digit we will add it in the stack then we go and we see okay this is an operation so whenever there is Operation we will pop the last two elements let's say x we are storing this one and pop the last two elements and we will apply the operation that is X Plus y because plus was the operation right so X Plus Y which is 3 now this three we will store in the stack okay this 3 will go into the stack now we iterate further we go to 3 this is a digit add it into the stack we go further we see multiplication right so previous two numbers X is what three the support that is this is now removed from the stack now the next previous number is three so Y is equal to 3. so this multiplication will be done on X multiplied by that is 3 multiplied 3 will be 9. okay 9 is the output so you can similarly check this out this is this one so this is very simple problem let's see the code weekly so in the code what we are doing is same thing we will iterate on each of the character which is in this vector okay and we have created this set which is storing all the operations so if here we will checking if the current this character if it is a digit that is it's not we are not able to find it in this operation set so obviously it means it's a digit so we'll push it in the stack and we'll convert it into integer because we have to uh like we have to uh find the output as integer return as integer see integer otherwise if it's not in a digit it is in this uh one of these operations so we'll push will pop the two elements from the stack accordingly whatever the operation is we will do the result we will evaluate it and we will add it in the stack like here we added three right in the stack and Atlas will return Stacks talk so I hope you understood the problem and the approach time complexity is O of N and space complexity is O of n if you found the video helpful please like it let me know in the comments if you have any doubts and do subscribe my channel thank you
|
Evaluate Reverse Polish Notation
|
evaluate-reverse-polish-notation
|
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation).
Evaluate the expression. Return _an integer that represents the value of the expression_.
**Note** that:
* The valid operators are `'+'`, `'-'`, `'*'`, and `'/'`.
* Each operand may be an integer or another expression.
* The division between two integers always **truncates toward zero**.
* There will not be any division by zero.
* The input represents a valid arithmetic expression in a reverse polish notation.
* The answer and all the intermediate calculations can be represented in a **32-bit** integer.
**Example 1:**
**Input:** tokens = \[ "2 ", "1 ", "+ ", "3 ", "\* "\]
**Output:** 9
**Explanation:** ((2 + 1) \* 3) = 9
**Example 2:**
**Input:** tokens = \[ "4 ", "13 ", "5 ", "/ ", "+ "\]
**Output:** 6
**Explanation:** (4 + (13 / 5)) = 6
**Example 3:**
**Input:** tokens = \[ "10 ", "6 ", "9 ", "3 ", "+ ", "-11 ", "\* ", "/ ", "\* ", "17 ", "+ ", "5 ", "+ "\]
**Output:** 22
**Explanation:** ((10 \* (6 / ((9 + 3) \* -11))) + 17) + 5
= ((10 \* (6 / (12 \* -11))) + 17) + 5
= ((10 \* (6 / -132)) + 17) + 5
= ((10 \* 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
**Constraints:**
* `1 <= tokens.length <= 104`
* `tokens[i]` is either an operator: `"+ "`, `"- "`, `"* "`, or `"/ "`, or an integer in the range `[-200, 200]`.
| null |
Array,Math,Stack
|
Medium
|
224,282
|
148 |
so today we're doing this problem called sort list and the problem is that we get a soul we have to sort a linking list in our plugin time and using constant space complexity and this is the linkedlist and so we're gonna sort it so something like this and like this so it was not sorted and we need to sort of like this so what I'm going to use to solve this in something very small too much salt or actually just measure salt but applied to Lincoln list I'm going to sort it I'm going to do it recursively which means that it's not constant space complexity but currently but I will follow up in another video with it with the merge sort done iteratively not in this video though but yeah so let's look into it so merge sort divide the problem divide de the array usually if it's done in array divide it into half and then keeps dividing into happened at each steps merges in the right order so that at the end we have a sorted array we're going to do the same thing in this case we are going to find the middle of the linked list and then divide it into two devices into two linked lists and sort each merge then third step is to merge the two mentalist in the right house and so usually when something is recursive we need to find the base case or base case is if there is nothing which means not here or there is just one note and that's also sorted by default right so that's the so this is the base case now the reducing the emphasize the way we are going to do it is pretty much just by reducing by half by dividing it into two so dividing I think that like this into two and then the other how are we going to do it since this is a linkedlist we can't just divide the length by two you can't do that but I require an open so clever more clever approach than just finding of a length dividing by two and then going again through the interest to determine the position of that index instead of doing that but who are going to do is just use two pointers approach which have basically how we can have let me just take this here so like this so using slow and the path pointer this is a very common technique is to put to point us technique with a linkedlist and so what you are going to do is we are going to have a slow pointer and a fast one right and then a fast one that is that goes in here and I cheat at each step we are going to advance the slow pointer by just one step so it will just go here but the fast pointer will go two steps so it will be here mistake one that where it would be clear so let's take a list with let's say is for example here and so the first pointer would be here at this point we move slow pointer to this and fast pointer moves to this and so now the fast pointer is done is at the end and you can see this is our middle point this is where we need to divide by half the only thing is that this is the start of our second half right and we can keep we need to keep track of another pointer at this position here that was at position two here now we'll just call it let's say three previous to slow right why do we need this because we wanna divide into half so our first half would be this portion here our second half would be this portion here right and so what do we need to do to with this link here should not be there because we want them to be a separate list and then we'll reconnect them in the merge step right and so to do that we are going to just say previous the next is equal to none so that we can ordinal interval so that we can break this link and iterate on each list separately right and so in order so the first half would be from head so this is usually we had points to that one so it's from Ted to three prime and the second half would be from slow to fast right from this point idea to this path point of last year and it doesn't matter here that the second half is bigger than one bigger with we thought with one extra would than the first half that's just because the number of nodes is odd if the number of nodes was even you can happen if split right so but it doesn't matter if it's out much and yeah so that's pretty much it so let's close this up so the first thing we need to do is the same trick which is that if the list is just two elements we need a way to be able to divide into the first and a half so we need a previous four so we need previous for this for so for that we need a dummy node to handle that and so we're just going to create them you know that there is a list node of value zero and then we are going to do while so no actually let's just first do the base case right so we said here which is this so that's the case then just return head then we need our previous our slow and fast pointers so previous stuff such as nothing right and then small starts out as head and first also starts out as and when do we stop some when so when fast either is no so it should like something like this or when fast that next is now which means which is something like this both cases we should be done for the even first even case pass would be at the nail position for the arcade number of nodes case over here so we need to handle this case a while I'm fast and Plus that next we need to start advancing the notes so what should happen so we need to change previous slow and fast pointers so we know that the previous pointer here will get updated to be the slow value right so each time we progress so the slow was here before and then previous here all right since we want previous to be the tail of the first list we need to advance it one slow advances before we update the pointer slow we need to set the previous value to be that slope out in life and so three would be slow and slope will advance with one step which is so dynasty and fast will advance by two steps so it would be fast die next annexed and at the end the first half would be head to previous so we need to cut the link so we need to do previous done X is equal to none and then we need to sort the first half and the second half so because laughs let's just call it left that would be source list word so that's a short list what's the head of the sort of the left side that's just path right and then the right side is just low right is from so to fast and slow start side the slow pointer and now we need to merge the two and return that so we can merge left and right so we need to define a function that merges so it emerged left right so to do that we'll just compare and put this model value first compare each two notes from each and put the smaller value first and then compare again the new value just what measure of merge sort usually does so if you have a sale I'll link up this with all three and then the second half plus imagine it's three up five like this or maybe with something like eight here so we'll compare one into three now and to do the result one and three one is smaller so put one and we advance the pointer so we'd have two pointers here and we'd have a pointer to our own new list so we advance this when we used its value and then our next point our compare three and four three smaller so to put three advance the pointer and then advance this pointer we compare four and five four smaller so put forward and then advance the pointer again and with us pointer of this one and three and five three smaller so put three and now since we are at mil for this one exit the main wire book or manual book and then go again and check if any of the Toula still has remaining element if any of them still has a remaining element we just put these remaining elements at the end of this one right and so the remaining elements here are five and eight so we just put them right so that's just a part we will be doing and so for the mers here so while both our content elements then compare them and put the smaller one so web left and right and then we need also a dummy node so that it keeps track of this here of this list since first we don't know what's in it so we'll just put a dummy node and then at the end we can pretend I mean that so that would be list node zero and then at the end here we can return damodar next as the measured list and here we said we want to compare this value with the right value right and so if it's less then we will put the left value right so we need to also keep track so we said we need a node that keeps track of where we add at the list so that we can point next to it and so we need a current node here that is equal starts off as equal to dummy and then every time we have a new element is a Condor next is equal to this new node which is just left right and then we need to advance left as we said earlier and then once we do that we need to advance current also right so current will be equal now to here onto that next now else we do something similar but this one is right at this time we it has the right pointer variable count so this is also the same thing as count equal to left right that's the same thing count equal to like it okay and then after that we need to actually you can make this one outside of the loop because it does the same thing outside of the if and else so we would have this and now at the end maybe one of them still has some remaining elements so we need to just put them in at the end of our list so we can do it with a wire loop but it's easier to just say okay count down X is going to be equal to whichever one has the remaining element and that you can just do with the left side all right so if left has a remaining element it will assign it and it will stop but if right has remaining element it will assign it and it will stop also and that's pretty much it for the merge step so we can run this it's free okay looks like it okay so the solution passes and the if we look at the time complexity here this is very similar to merge sort it so basically these recursive function will call them at most log of n time because we divide each time by two so that will give us like of n complexity because like append times we will call the function but in each hole we are doing this troubles up here which goes through the entire list and so that's n log n time complexity so the recursive functions are called log of n times and then each call does ends and so that openly like any time complexity space complexity so we are just using some extra pointers but the you can see that the curse of course that are done of lag and time means that we have in the stack we use all like and space right so it's not come it's not constant complexity if we did mergesort it's a rate of death there is a way to do that it would have been all one I would hopefully do that in another video and yeah that's all for this problem see you next time bye
|
Sort List
|
sort-list
|
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_.
**Example 1:**
**Input:** head = \[4,2,1,3\]
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** head = \[-1,5,3,4,0\]
**Output:** \[-1,0,3,4,5\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 5 * 104]`.
* `-105 <= Node.val <= 105`
**Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
| null |
Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort
|
Medium
|
21,75,147,1992
|
1,022 |
hi i am ayoshi rawat and welcome to my channel today we will discuss the september lead code challenge day 8 problem sum of root to leave binary numbers let's have a look at the problem statement now given a binary tree each node has value 0 or 1. each root to leave path represents a binary number starting with the most significant bit for example if path is 0 to 1 to 0 to 1 then this could represent 0 1 in binary which is 13. for all the leaves in tree consider the numbers represented by path from the root to the leaf return the sum of these numbers okay now let's have a look at the example input is 1 0 1 and output is 22 let's understand the example it can be represented as 100 1 0 and 1 we can use eight four two one method here zero one zero can be written as four zero one can be represented as four plus one equals to five one zero can be written as 4 plus 2 that is 6 and 0 1 can be written as 4 plus 2 plus 1 that is 7. if we sum all of them up we get 22. the note says the number of nodes in the tree is between one two thousand node.well one two thousand node.well one two thousand node.well is zero or one that is a node can take up value either one or zero the answer will not exceed 2 to the power 31 minus 1. there is a hint for each path then transform that part to an integer in base 10. there can be multiple approach to this problem let's discuss two approach one is iterative one here we will implement the standard iterative pre-order traversal iterative pre-order traversal iterative pre-order traversal with the stack first we will push the route into the stack and we will check while stack is not empty in that case we will perform three operations pop out a node from the stack and update the current number if the node is a leaf update root to leave sum and at the end push the right and left child nodes into the stack once done we can return root to leave some here we are making use of tree traversal i am hoping that you must be aware of tree traversal there are three kinds of tree traverses pre-order pre-order pre-order post order and in order if you want to work with decimal representation the conversion of 1 to 2 into 12 is easy we can start from current number equals to 1 and then shift 1 register to the left and add the next digit current number equals to 1 into 10 plus 2 that is 12. if we work with binaries 1 2 3 it's same you start from current number equals to 1 and then shift 1 register to the left and add the next digit iterative approach can also be converted into recursive one so let's look at the second approach now recursive pre-order traversal is simple recursive pre-order traversal is simple recursive pre-order traversal is simple we simply need to follow root to left to right direction that is do all the business with the node and update the current number and root to leave sum and we can make recursive calls for left and right side nodes it will become more clearer to you once we code let's quickly dive into the code i am using a helper function here i'll call it as preorder i will declare route to leave as non-local now non-local now non-local now we will use if condition on r and check the current number if it's a leaf we'll update root to leave sum now we will make recursive calls for left and the right side we can exit the function and set root to leave as zero now i will call our helper function and pass the parameters root as r and 0 as the current number and return root to leave at the end and we are done now let's run our code now let's try submitting it and here we go you can find the code at my github repository the link is mentioned in my description box below if you wish to connect with me on other social platforms the link is mentioned in the description box please like and subscribe my channel for more such videos thank you for watching
|
Sum of Root To Leaf Binary Numbers
|
unique-paths-iii
|
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_.
The test cases are generated so that the answer fits in a **32-bits** integer.
**Example 1:**
**Input:** root = \[1,0,1,0,1,0,1\]
**Output:** 22
**Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
**Example 2:**
**Input:** root = \[0\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val` is `0` or `1`.
| null |
Array,Backtracking,Bit Manipulation,Matrix
|
Hard
|
37,63,212
|
518 |
Hello everyone, today we are going to do question number 518 of the network, whose name is coin change, this question can be asked many times in the interview and its approach is absolutely standard, although it is a medium mark, but its problem statement is very standard. Yes, representing coins of different denominations and wait, amount representing total amount of money return, D number of combination, date amount, so with an example, we understand what is the question, we have been given amount 5 and we have coins that we How many coins can we make lake amount Your answer is simple Let's understand it is ₹ 5000 Profit is 125 I have [ I have [ I have We have this file Can give us Steel Industry Why, because we got it from here, it's fine, so now if we are not uniting it, then what will we do? We have made absolutely zero returns And now let's see if our index goes out of the water. If we have then we will make the return zero Total Ramesh Koi race kar karta So now we have the amount you and our in If we do not pick this then we will be flooded further So there is flood here we can do farming if we have to It will become zero and as I told that if the amount lesson is zero then we will make its return zero then our amount will remain the same but the index will flood further and here it will go to 25. So now for this also our country is that if the index is already Goes out from here also we return zero Now we have sent 22 till here So now we move ahead Now we have the amount free and we can't pick one We are doing this, we will reach this state 125 Now our index here is the amount If we pick this then we will have the amount one Let's go ahead Now again there will be zero from here, that too is our country so from here also zero return From here it will be zero. Zero plus zero will become zero again. From here the return will be zero. If we don't pick, our index will go out. This will become. If we don't pick, one of our indexes will be flooded. You witch is this. Four mines have infinite supply so we will still stand at 2 zero we have internet supply So now let's see if we don't pick it up If we pick it up then it will be ours Now its from here The return will be zero and if not then it will be made because we have infinite supply, that is why I was saying that this point is very important, now again if we make it 3125 then 3 - 2 then 3 - 2 then 3 - 2 1 we will be left with the amount . Image this also a little. Let me tell you if we are standing then can we pick 5 again or not and if we don't pick then we will go out of form and will get zero from here also, zero return from here, wherever we send zero. Let's send zero from here too because I will send zero from here also, the return from here is zero You can also pick up, we will have two options, it will go out like this 5 points once If we are doing that, then our zero is doing our point, so from here we will get zero How is this the base? As we know biscuits are very important, so how is this the same base Be here It will mean that we have got one way, that is, Be here It will mean that we have got one way, that is, Be here It will mean that we have got one way, that is, when our amount lesson becomes zero, then it means that we have not got it. If or the index is out of account, then we have not got anyone from there. The amount will be reduced by this much if we pick. Our index will remain here, the amount will remain reduced For every index we have two choices, either we can pick it, we can't pick it, either we can pick it or we ca n't, either We can tick or not tick, two options for this, but there is also a request that we can tick these two options when we do not have infinite number of supply and we have infinite number of supply. We ca n't count how many times we can pick this up, we can repeat this one over and over again, our amount is 10, so if we have normal complexity, that's it Now we can do this Let's optimize and do this for BP problem So you don't have to do anything to voice me, in which we will get as many likes as you have declared, see -1 will be there but whenever we get the answer like -1 will be there but whenever we get the answer like -1 will be there but whenever we get the answer like We got the answer here, we got the answer 3, we got the answer here, so we stored it 3, installed it and we will check, when the story comes again, we know, processed it and we stored it that we I install this So what we are doing in this is that every time whatever status comes, if it comes again, I will store it, then its time complex will also become N + Let me show 1 and N + 1 here So what will we do in this, the first one means that our amount is zero, when our amount is zero then we will make one in it, so if our amount is then sending zero to us like We must have understood that how was our base, the first one will be used for index, the second one will be used for amount, what is the amount, if ours which was indexed in ours, which are coins, if we give a lesson, then only we will give them the amount. Only if we pick it, what will we have to do to pick it and our amount will be reduced, it is okay with the same number of coins, the value which came from the left side, plus both of them and if we have If it is not available then what do we do? We move an index ahead, meaning if we travel from the back then we will write that We added a little more space to the next space which was going to be our detergent. And we reduced that, so our oxidation space went back. Now let's look at another approach So what is in this approach, we first do two tu di dp a rahi hai, let's do that, meaning matrix was doing that, we were doing it to store But now we know that we are getting the answer, it will be stored in this one, we will get the answer from this one, so why should we install this one completely, we are getting the answer from this one, so why should we install the entire one, if when I go to this one If I come here then I definitely don't care about this. It's definitely not for everyone. And if I keep storing the amount in it then you will understand better what I want to understand. So let me tell you once again that we are a We can enter the answer by doing this space by doing this upper Ara by doing this. We do not need to do the whole Eric again and again. Mother, take it that we are standing on this one. Look, we are filing, so only we have to do this. This one is needed, don't we need the one above also Only I need this one, so I will install it, so wife, I have done it here, I have only stored the elements which are in your one and made the last one from that. I have returned it, have you understood it? If you have any doubts, you can ask me in the comment section and like. This is my first video on this channel, so if you like it then comment.
|
Coin Change II
|
coin-change-2
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000`
| null |
Array,Dynamic Programming
|
Medium
|
1393
|
304 |
hello everyone welcome to our channel code with sunny and in this video i am going to talk about the problem rain some query 2d and it is immutable and the problem index is 304 and the problem is of one of the medium type problem of the lead code okay so given a 2d matrix that is going to handle multiple queries of the given type that is the sum of the elements of the matrix inside the rectangle so there must be given some end points of this rectangle like upper left corner and the lower right corner denoted by row 1 column 1 and row 2 column 2 respectively and there is a matrix class that we have to initialize with that okay so what we have to output like ok we have to output the sum of the elements of the matrix inside this rectangle so let me just take a look at the constraints yes it is like for every query we have to output the sum of the reason formed by the rectangle having the inputs upper left corner and the lower right corner okay so basically in this problem there is a it is a problem of brain somebody like you can uh by looking over the problem statement or like the writing the looking over the title you can think like it must consist of a problem including like segmentry but i don't think this problem should be categorized into segment tree you can easily do this problem with the help of simple logics of dynamic programming of prefix sums like in a matrix and like a simple match you can easily handle this problem and find out the best solution of this problem okay so in this video we will be talking about how we are going to have a of 1 per query that we are going to answer the sum of the region formed by this rectangle in o of one time for everybody okay so we must have to do some prerequisite calculations okay then only we can answer like you know one time for every query okay and you can easily see the sizes of the length of this rectangle can go maximum up to this m and n and m and n can go maximum up to 200 okay so let us try to have a like a overview of this problem with the help of examples and then we will together find it out what could be the best solution of this problem under these constraints okay so let's move further okay so consider this 2d matrix as an example where the cell values are denoted over here now consider that we have to find some of the reason of this rectangle like this one okay just i'm filling it with a green color okay so consider this uh that we have to find the sum of the elements present in this matrix starting from this column number one up to this column number three for the row number one up to this column uh up to this row number two okay and suppose you have to find this sum and how we are going to do that for every query in the best possible way now one thing one approach that would obviously click to your mind is the brute force approach that is for every query you are going to just find it out the sum but if you notice over the query it is route and 10 power four calls should be made at most 10 for four calls and considering the worst is like m and n would be like every time 200 for every query so in the in that case your total number of iterations would vary up to around 4 into 10 power 8 and this is going to cross the normal limit of the iterations normal limit of the saturation is around 10 power 4 or 10 power 5 for every problem okay so we should consider this problem to be done under this limit that is maximum at most 10 or 4 iterations should be done okay so how we are going to do this in the best possible way now here you can easily see the sum that is coming out to be like 14 i think yes sum is coming out to be 49 plus 4 13 and plus 140 the sum is coming out to be 14. now you can do easily do with the help of brute force approach but can we just optimize that one in a much more extent so that i can answer in o of one per query for the for every query that is i'm just answering the sum for every query in of one time can we answer that yes we can easily answer that and the logic behind this is like simple maths and you can also call it as a dynamic programming i just don't prefer to call it as a dynamic programming because if you consider the logic of prefix something suffix some it must be like very much easier to manipulate this problem and find out the best solution okay so i'm just first erasing this stuff and i'm just trying to just explain how we can just uh in the case like dynamic program we are just doing some prerequisite calculations in the similar case as of now i am just doing some prerequisite calculations for this matrix and what is that calculation okay so let me just state it down like okay so for this let's say i am just at this position that is at this cell that is i'm just at two comma two cell and the index is from zero best indexing it okay so if i'm at two comma two cell and consider my rectangle whose lower right corner is that two comma two cell then i'm just finding it out the sum for all the cells up to this cells okay if you're not going to understand this no need to worry about okay so i'm just explaining it out in much more simpler way that is for every cell i comma j i will find it out what is the sum for all the cells up to this cell and for which cell i'm talking about consider that this is the cell i'm talking about two comma two then if i will just transform my matrix to prefix sub matrix such that for every cell i comma j it will denote for the sum of all the cells that is merging into this cell that is for 2 comma 2 i will have the sum for this one okay so i will just fill it out as fast as possible okay so for 2 comma 2 my 2 comma 2 i comma j cell it will denote the sum of all these cells okay and consider if i am at three comma three it will denote the sum of all these cells for all the cells which are colored in blue okay now consider some more different varieties like if i am at cell one comma four for which cells it will denote if i'm at one comma four it will denote the sum of all these cells okay it should be like this one if i'm at one comma four that is at this position i'm just marking it down with another color that is if i'm at this position okay that is this position 1 comma 4 then it will denote the sum of all these cells how we are going to compute this cell and how this value for every cell of this matrix is going to help us for answering every query in o of one per time let us try to understand that okay so okay let me first erase this stuff and let us try to take another example where i will explain how this query is going to help us so i will just transform this matrix first into this sum matrix that is uh into the like the sum that i have explained for every cell i comma j it will just denote the sum starting from zero comma zero cell up to this cell such that for every i up to in this range will be less than the lower right corner row number and for every g which is going to be like varying in this range will be less than equal to this uh column number of this lower right corner of this rectangle okay so i'm just transforming this matrix into that sum matrix okay so let us try to do that okay so this is the transform some matrix of this when i will also tell how this transforms some matrix we can easily calculate okay so for now you just you can just easily see that suppose our lower end of this rectangle is this position and the value at the cell is coming out to be 28 it is basically denoting the sum of all these cells okay and suppose the value at here is 36 it will denote the sum of all these cells okay so i'm not just talking about the sum of every cell okay so just try to focus upon suppose if we have been given this rectangle and we need to find the sum so what i am going to do is i am just subtracting it out the sum of all these sum of all the values present over these cells from the value of this lower right corner of the cell that is 28 of this transformed sum matrix and why this is going to give us a correct answer and let us try to analyze over that and you can easily see the 28 is going to be sum of all these values and if we try to subtract the values of this one three zero one four and three five one i will get the sum of only these six three two and two zero one and this is going to be valid okay so how we are going to do this in a product that is for every query the time complexity would be like of one so that we can pass all the test cases okay so let us try to focus upon that how we can easily do like if i will have this transformed some matrix and we will have been given this rectangle with lower right corner and upper left corner of this coordinates of this rectangle i am just going to add this value that is 28 to our answer and i will subtract two or more than two values and depending upon the orientation of this rectangle that is suppose if this is the rectangle that i have been working upon i will add the value 28 to one to our answer and i will subtract this value 8 and if i will subtract this value eight basically i'm subtracting all these values present over this cell that is three zero one and four which is coming out to be eight you can easily see the sum is coming out to be eight that is four plus three seven plus one eight yes sum is coming out to be eight i will subtract eight from this value of twenty eight that is overall i'm subs i'm just subtracting it out that is sum of all the cells over here minus three 3014 this amount of cell also after doing this i'm just also subtracting it out the cells of this type okay if i will subtract the cells of this type it means that now my sum would be would contain this value plus one additional term you can easily see if i will subtract 3 0 1 4 for all the cells over there also 3 5 1 then my value would be like 28 minus s 1 plus s minus s 2 that is for this one and for this one but you can easily see i've just subtracted 2 times the cell that is present over here so i just need to add this amount again okay so i'm just like i'm just compressing the entire thing into one statement that is for every lower right corner of this given rectangle for every query just add the value present in the transform sum matrix for this cell present at the lower right corner of this rectangle and subtract the values present over these cells okay like these cells of this that is cell present over directly for this row one that is this is defined as row one and row one minus one and column two that is as given in this question you can easily see it is like this one the upper left corner is row one comma column one and upper right corner is uh like lower right corner is like row two comma column two then i will subtract this eight which is actually row one minus one comma column two you can easily see eight coordinate would be like row one minus one comma column two also i will subtract the cell value of this transforms a matrix the nine is actually the coordinate of you can easily see this lower right corner has the coordinate row 2 comma column 2 then 9 will have the coordinate like row 2 comma column 1 minus 1 okay but if there exists some cell which is added twice that is which is subtracted twice i will add once again okay that is the value present over this one okay so in more easier way let us try to understand this on the with the help of coding part also which will make it more clearer okay so i've just submitted the code i think i'm just trying to show that okay so this is loading okay it is accepted already okay so you can easily see the runtime bits are 99.84 easily see the runtime bits are 99.84 easily see the runtime bits are 99.84 percentage so what i've basically done is i've taken the maximum size of 200 and for every for this constructor i just initialize n and initialize m so first i have taken this matrix into my vector 2d vector of defined as matte and i find the cumulative sum up to the current cell that is starting from 0 up to this particular cell such that the for every i comma j the cell value should be like less than equal to this particular uh lower right corner of any cell that is for if you consider it as a rectangle it is like lower right corner of this rectangle whose one upper left corner will add 0 comma 0 and you can easily see first i have found this sum and this sum is which is basically for every column i will try to find out that is for every column i will try to find out prefix sum for every row that is starting from 0 through up to the end row that is row n minus 1 for every column i have just modified the value present at this matrix value present at these cells that is the prefix sum starting from 0 through up to the n minus 1 through for every column you can easily see j is trying to vary from 0 to less than m and for every column i will just find out this prefix sum that is rho starting from 0 up to this n minus 1 and also you can easily see after doing this operation i have just found out the same thing that is the vice versa of the previous one that is for every row i will just try to i trade for every g starting from 1 up to less than m minus 1 i will just try to find out the prefix sum for every row okay you can easily see this will end up giving the value of each cell equal to the cumulative sum of all the cells starting from 0 comma 0 and ending up to this current cell the exactly same thing if i'm talking about this one it will denote the sum of all these values okay so this will give us a time complexity around o of n into m okay and for in case of some reason what i have done is like my answer would always be initialized with this one that is the lower right corner value it will denote the sum starting from zero comma zero up to ending up to this cell and we just need to take care for the coordinate cells and corner cells are if row one is positive and column one is positive that is the exact same case that i have taken over here then my sum would be modified my answer would be modified i will subtract the values present over these cells that is you can see row 1 minus 1 or under 1 minus 1 and column 2 that is the value present over there here that is 8 it will basically subtract the value 3 0 1 4 and again i have subtracted this row 2 comma column 1 minus 1 that is the value present over here that is 9 and which is basically subtracting 3 5 1 but you can easily see i've subtracted 2 times some of the cells that is here only 3 is present so i will just adding the matrix present to that is the cell value present over this one row 1 minus 1 and column 1 minus 1 and these operations is these operations need to be done 1 11 row 1 is positive and column 1 is positive and what about this row 1 is 0 and column 1 is non-zero column 1 is non-zero column 1 is non-zero that is we have some cell whose row 1 is exactly 0 that is the upper left corner can vary up to that is can vary for only that is upper left corners will be only present at this row zero and it will vary throughout the column okay so in that case i just need to subtract only this thing i just not need to subtract this one that is if my this upper left corner will coincide up for this cell the whose row 1 is going to be like 0 i just need to subtract this value 9 i don't need to subtract this value present over there because this upper end of this rectangle will coincide to the exactly the 0th row and similarly this if row 1 is non-zero if row 1 is non-zero if row 1 is non-zero and column 1 is 0 i will subtract the exact reverse case present over there okay and finally return the answer so this is going to give us a uh all correct test cases passed okay if you had 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
|
Range Sum Query 2D - Immutable
|
range-sum-query-2d-immutable
|
Given a 2D matrix `matrix`, handle multiple queries of the following type:
* Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
Implement the `NumMatrix` class:
* `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`.
* `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
You must design an algorithm where `sumRegion` works on `O(1)` time complexity.
**Example 1:**
**Input**
\[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\]
\[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\]
**Output**
\[null, 8, 11, 12\]
**Explanation**
NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `-104 <= matrix[i][j] <= 104`
* `0 <= row1 <= row2 < m`
* `0 <= col1 <= col2 < n`
* At most `104` calls will be made to `sumRegion`.
| null |
Array,Design,Matrix,Prefix Sum
|
Medium
|
303,308
|
645 |
hi everyone so today we'll be doing this problem called uh said mismatch so you're you have a set of number a set of integers which originally contains all the numbers from one to n unfortunately due to some error one of the numbers in s got duplicated to another number in the set which results in the repetition of one number and the loss of another number so basically what we are giving is we're given this array of numbers and we have one duplicate within that array so the duplicate happens in such a way that the number that is supposed to happen after the number that is being duplicated is missing so basically here at this point 3 is supposed to occur and so our output is supposed to be the number that is the duplicate and the number that is missing so 2 comma 3 is the output in this case so that is what we're supposed to find in here so let's solve this problem uh initially we'll identify what our input and output is which we just discussed so our input is going to be one two four and our output is going to be um our output is going to be 2 comma three so how can we do this in and of end time complexity and uh a space let's say we use a data structure uh in this case to make sure that we keep track of the duplicates so we may have to use a hash map so maybe so the time complexity for this problem would probably be oven and space would be again open so let's go with this approach and see how we can solve this problem so let's diagram this out and then explain the approach so we have our array one two four and we're going to use a pointer and then we're going to look for the duplicate so what we're going to do is we're going to we're definitely going to use a for Loop to iterate through the array and while doing that we need to keep track of the we need to capture our duplicate so let's say a duplicate is a variable and we initialize it as none and then we also have to capture the missing number as well so that missing number let's call that also no none so when we start at instead of starting at the very beginning let's start at the very first position which is two and then what we do is uh we actually before doing any of these we need to make sure that we also have a hash map full of like uh keys and values of the counter basically a counter map that keeps track of the frequency of every number so let's also have that uh so one is occurring once and two is occurring twice and four is occurring one time so we also have this as well so what we do is when we iterate through this array using this eye pointer using a for Loop like let's say we start at two when we started two we what we do is we try to see if that number is in the lookup table so if it's in the lookup table and if the frequency of that is greater than one which in this case for two it is so what we would do is that is the number that is occurring uh more than once we'll like set that to be the duplicate and then what we would do is uh if the number is not appearing in here which is the lookup table that would be the number that is missing in the array so we'll assign that as the missing number so that's the idea behind this so when we're iterating through it if the number that we're looking at is in the lookup table then that's the duplicate number the number that we are looking if the number that we're iterating uh through the length of this array is not in the lookup table then it is the number that is missing so we're not necessarily like iterating through we're not necessarily looking at the number in the array but we're looking at the length of this array so we're iterating from 1 through n basically the index so we're iterating from that is another important thing that we need to make sure so we're iterating from 1 through n so what where our I is our nums of I is going to be in this case above it's going to be one two three four but actually it's going to yeah it's going to be one two three four and then even five we're going to go uh from one to length plus length line of numbers plus one so that's the idea behind this and uh that is how we're going to do this problem so let's uh let's code this out so the very beginning what we need to do is we'll call duplicate to be none and let's just have a missing number which is also none and uh let's use a counter of the nums which is the nums is the input and then assign that as the hash map um and let's say that is equal to the hashback and we say 4i in range one two Len of nums plus one iterating from 1 to 11 months plus one why everybody can see if we see if I uh if I not in hashmab #if I is not in hashgrab that means if #if I is not in hashgrab that means if #if I is not in hashgrab that means if it's not in the hash Fab that's the number that we are missing so I'll say missing equal to I uh and if I uh if I is or actually if the hash map of I which is the frequency of the number that we're looking at if it's greater than one that is greater than one then in that case that I is the duplicate so that we have now are missing and our duplicate so outside the for Loop what we would have to return is the array that contains the uh the array that contains the duplicate and the missing yeah so that will be it that is the solution to this problem let's see if this runs oh there you go so I think that does work for that let's run submit this and see if it works yep there you go so that is a solution and it is as you can see this is pretty efficient and uh also is pretty uh efficient in time and space as well um uh I hope you I hope this explains the solution to this problem and uh thank you so much for watching and I hope you have a great rest of your day
|
Set Mismatch
|
set-mismatch
|
You have a set of integers `s`, which originally contains all the numbers from `1` to `n`. Unfortunately, due to some error, one of the numbers in `s` got duplicated to another number in the set, which results in **repetition of one** number and **loss of another** number.
You are given an integer array `nums` representing the data status of this set after the error.
Find the number that occurs twice and the number that is missing and return _them in the form of an array_.
**Example 1:**
**Input:** nums = \[1,2,2,4\]
**Output:** \[2,3\]
**Example 2:**
**Input:** nums = \[1,1\]
**Output:** \[1,2\]
**Constraints:**
* `2 <= nums.length <= 104`
* `1 <= nums[i] <= 104`
| null |
Array,Hash Table,Bit Manipulation,Sorting
|
Easy
|
287
|
417 |
um hello so today we are going to do this problem called pacific atlantic water flow um so part of um lead code august dairy challenge so we have an m by n rectangular island um that borders the pacific ocean from the top and the left side and borders the atlantic ocean from the right and the bottom side right um and what we want is to the basically the matrix also has these values which are called hates so 5 represents h5 3 represents hate 3 which represents the hate above sea level and what we want is basically uh water can flow from a cell if the neighboring cell is less than or equal to it so five can flow to three can flow to um three can flow to because it's small or equal to it and three comes flow to two can flow to two but three cannot flow to four because it's bigger than it so this is not possible so that's the idea so neighbors are all those that have hate all those that are to the left right top or bottom of a cell but i have values less than or equal to the current cell value so that's the idea and the goal of what we want to return is a result array such that has all the coordinates of all the cells where water can flow from bo from that cell to both pacific ocean and the atlantic ocean right um so if basically pacific ocean both the pacific ocean and atlantic oceans are reachable from a cell with the definition of reachable being this here with this uh with these top bottom left right being the directions um then we consider those um we written this in the result right um now let's take a look at the example here so we have this matrix um and what are the values that let's take a couple of examples so zero four if we take the zero throw and then take zero one two three four so five here um it can flow to the atlantic ocean just by going left right going right um and then it can flow here by going top um if we take a look at one three so one three four here well it can float to the top here to pacific ocean by because three is smaller so we can go there and then from there we go here we reach here um once you reach the boundaries basically you can consider yourself you can consider you have reached the ocean because once you are in the one of these boundary cells i'll say that either the top row left row or um most right most row or bottom row right most column or barramca row then yeah you can consider yourself rich at this basically there is no restriction into moving from here to here or bottom to the atlantic ocean um yeah so let's take a look at the other examples here so one three we said you can go to the pacific ocean this way and then because four is equal to four you can also go this way so you can go to both so we need to return it so we need to return these two for one four this four here um we can go this way um and then go we can't go to five because five is bigger but we can go to four because it's equal and then to three and then we reach it so 1 4 is also valid solution um 2 for example uh just to make sure we understand this so 2 0 1 2 that's 5 here well we can go this is smaller so we can go there we can go here and then we reach the pacific ocean we can go here and we reach atlantic ocean so you get the idea and we return it for all of them so that's the problem we are dealing with here now let's see how we can solve it um okay so let's see how we can solve it so this is the matrix that we get now one thing to note is that all the cells here and here are which are immediately reachable by the atlantic this one is immediately reachable by the atlantic ocean and this one is whenever one once you get here you can reach the pacific ocean and once you get here you can reach the atlantic ocean so that's the main idea so now knowing that we can just think okay let's reverse the process right so the problem asks us to start from the cells and try to go to the pacific ocean using the rule that the neighbor the value in the neighbor the hate in the neighbor has to be small or equal to the height in the current cell right so how about we reverse it instead of doing this well let's just start from the cells that we know are reachable so those that are in the edges and then just try to go to all the cells and all the cells that we can reach those are the cells that can go to pacific ocean or atlantic ocean right um so the idea is to start from for each so what we want is to be reachable from both right so what we want is reachable from the boundaries of both pacific ocean and atlantic ocean right but we can do this separately right we don't have to do it for both at the same time so what we can do is first have those maybe have a visited from the pacific ocean and have visited from the atlantic ocean basically have all the cells that we can visit from the pacific ocean which are all the cells that we can visit when we start from these and all those that are visited when we start from these because one once you reach these um yeah you can just go to the yeah we can just go here and go to the pacific ocean or here right so we do that for a pacific ocean and we get the set and then we do the same for the atlantic ocean so we just start from this column and from this row and we see all those that are reachable and then we put these in this and then our solution would be just the union of these two sets so we can do it separately so that's the first i the second idea so the first idea is to start from the boundary um rows and columns and then the second idea is to just do it separately and uni union everything together now the problem now the question becomes how do we determine that we can go from here to here right if we started from the cell and we need to know if we can reach the boundary row or column we can just check this formula right that four is the current cell needs to be bigger than the three but if we want the reverse right we want to go from here to here we need to reverse this relation we need to do smaller right because this is actually then we are starting from the potential neighbors right so what we want to check instead is that the current is smaller or equal to the neighbor right because the original problem says we want to go from here and try to go here but we are starting from where we need to arrive and so to trace it back we need to reverse the relation right because if let's say a is smaller than b right um and that's if we are looking at b but if we are looking at a we need to check smaller right so that's kind of the way we are reversing it i hope that makes sense um and so that's the pretty much all we need to um to understand here so the third thing the third observation here we are doing is we are going to start from boundaries and traverse with uh traverse with um with the rule that current smaller than the neighbor because we are actually starting from these boundaries and looking for the cells that would have reached the boundaries right um okay so what's the process is going to be so we are going to use definitely dfs here you could use bfs as well but the general idea is we are going to do dfs and start from the boundary cells so we'll do dfs and start from the boundaries let's take an example here just for the pacific ocean where we are filling this visited set so we are going to start from this we will start from each of these points and do dfs and try to see what are all the cells that we can reach using this formula here using this um this condition but the other condition is that the neighbors are only left right top bottom and so here our neighbors can we go to three um so can we get to go to three here um one is smaller than three so we can actually go there right because the real problem says if one is bigger three is bigger then we can go here right so that's why we reverse it and so that automatically means that this position here we can we added to visited right because it's reachable as so we would have um what is this is the one and this is zero so one zero is going to be added to the visited set of pacific ocean and then we'll go um the neighbors are can we go to two well three is bigger than two so we can't go there can we go here no we can't go there so because it's uh bigger and so we stop for one here and for two we try to go here we can because it's equal and so this one is reachable so we will add this is one so we'll add one to the visited set of pacific ocean and then can we go left to three is already visited anyway but also it's um is the current is too small yes so we can go to three but three is already visited so we don't go there is this visited we can go can we go to this three yes is it visited no and so we can go there so we add this so this is two one so we add or one two so we add that to the visited set and we keep doing this until the end and then we do the same dfs traversal for this side here um and we do the same thing that we did for the row and then once we do that so we will cover we will fill all the visited pacific ocean the second step is to do it for the atlantic ocean visited set and so we'll go here right and then we will say um okay five is can we go to three uh five is bigger than three so we can't go there can we go to four yes four is um five is no way i can't actually go too far and so we yeah we can go anywhere here if we start from then we start from four can we go left yes because four is equal um and so we add four to the visited set for the atlantic ocean and four is zero one two three so zero one it's um one three right so we add that one three to the pacific ocean here and then can we go to three here we can't because four is not smaller than three can we go here no we can't can we go here no we can so we stop now we go to one can we go to three yes because it's uh one is smaller um and so we add three to the visited set for the atlantic ocean so it's two three and if and then at the end we will have all of these visited set here visited element here and all of these visited here and we take the intersection basically and why do we take the intersection because the intersection means we were able to reach that cell from both the boundaries for the pacific ocean and the boundaries of the atlantic ocean so which means that it's reachable from both and yeah that's pretty much it actually um yeah so let's um implement this and make sure it passes test cases um okay so let's get started here um so we need the rows and columns just the values i'll just make this h so that it's easier to write so this is the length the number of rows and the number of columns is h0 we are guaranteed that the heat is um yeah small or equal it's bigger or equal to one um and then we need to define both the visited things that we need so we need one for the pacific ocean and so this is a set and we need one for the atlantic ocean and then we'll do dfs so we'll do our dfs here but at the end once we do the dfs we want to return the intersection right cells that are reachable by both and we'll just get a set here we'll convert it to a list because the problem wants a less and now we'll do first um boundary rows boundary start from boundary rows and then we will start from boundary columns here okay so for the rows um sorry this is start from boundary columns and this is start from boundary rows so for the boundary columns well it's the first the top row and the bottom row right and so um for and for the boundary columns it's the first the leftmost row and the rightmost row rightmost column i mean and so to do that we'll need to go through i in the range of the size of rows right and what's the for the so this is for the leftmost row uh column i mean so we need to do the fdfs on it and pass the coordinates inj for i changes but for the leftmost column j is always zero and according to the problem here the leftmost column is reachable by the pacific ocean so we need to pass the visited set for the pacific ocean so that we fill that one and for the right most column we have um i changed this right but the yep i changes but the column is the same it's the last one and so to fill that one we need to say it's columns minus one it's just n minus one right um and it's reachable by the atlantic ocean not the pacific ocean so we need to yeah any cell that is reachable from this column we can say that it reaches the atlantic ocean so that's why we passed the visited set for the atlantic ocean okay and now we do it for the boundary column so the boundary rows top and right top and bottom so here we do a j in the range of columns and we do dfs so j changes but for the top row so this is here tab row the row index is zero right so that's why we put here zero and it's reachable by the pacific ocean right so we need to pass the visited set for the pacific ocean here and then we do the same thing for bottom row however for the bottom row j values change right but the row index is row minus 1 right so that's why here we say row is minus 1 n minus 1 or minus 1 essentially and the bottom row is reachable by the atlantic ocean right so we want to um pass the value visited set for the atlantic ocean instead right and now that we have all our differences that we need right we do four differences from each boundary and now we need to write our dfs so it needs i j and it needs the visited set and we know we want to visit when we visit we want to add to the visited set right that's why we can do this and we want to go through the neighbors i'll just create a function that gives us the left right top bottom neighbors and so we'll write it in a second and we want to check that this neighbor is still within the boundaries right we don't want to go past the boundaries um so this is would be needs to be rows and this needs to be columns um and we don't want to visit something that we already visited right we did that in the overview where when we reached three from here because we already visited it from here we don't go there right and so that's why here we can we need to check not in visit it and we need to check that this is valid cell to go to and that's the initial condition is that if you are coming from the cell to the boundary you need to check that it's smaller or equal but if since we are doing it in the reverse we need to check bigger or equal so we need to check if the value the height in the neighbor is bigger or equal or actually let's start from let's write for i j so we need the current cell which is starts from the boundaries needs to be smaller or equal to the neighbor and the neighbor is actually the one that needs to be higher that's the reverse of the initial one um and if this is valid then we can go there and so we can pass visited another thing we can do just in case for example uh we are traversing here but this one was already visited by the row so we don't need to go there so let's do a check here for i j in visited we want to return and that way since we are doing this check here we don't need to do this check um yeah so that's pretty much it we just need to go there we don't need to return anything because we are already filling what we need in the visited sets um so let's run this uh yeah we didn't define neighbors function so let's just write it down so that one should be pretty quick it's just the top so you i plus one go to the top row go to the bottom row um and here go to the right column or go to go right or go left or go up right and that's pretty much it so let's run this and let's submit and that passes this cases um yeah so that's pretty much it for this problem um the main idea here is we've got the problem um text but we need we if we reverse it the solution becomes easier and so that's what we did here um yeah so that's pretty much it thanks for watching and see you on the next one 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,266 |
hello guys and welcome back to lead Logics this is the minimum time visiting All Points problem it is a lead code easy and the number for this is 1266 uh so in this problem we are given a 2d plane and there are n points with integer coordinates given by points of I so points is actually a 2d array and every Row in points uh points array consist of two coordinate x and the Y coord orate of a particular point so we have to return the minimum time in seconds to visit all the points in the points aray and there are some rules what are the rules in 1 second we can either move vertically by one unit or horizontally by one unit or we can move diagonally uh diagonally square root units so we can move like 1 + 1 so we units so we can move like 1 + 1 so we units so we can move like 1 + 1 so we have to visit the points in the same order as they appear in the array and we are allowed to pass through the points that appear later in the order but do not count at visits so okay uh okay we can do this so for this we may be using a chessboard distance formula which is also known as the chbby shf distance which is given by Max of X2 - X1 uh this is the absolute Max of X2 - X1 uh this is the absolute Max of X2 - X1 uh this is the absolute value of X2 - X1 and absolute value of X2 - X1 and absolute value of X2 - X1 and absolute value of Y2 - y1 so we can take the ma maximum Y2 - y1 so we can take the ma maximum Y2 - y1 so we can take the ma maximum value of these two and take this distance and return as the answer so this is how we are going to solve so the problem essentially ask for the minimum time to travs the sequence of points on the 2D plane using the this following specific movement rules this is the problem and we can calculate the time as it uh takes to move between consecutive points using this formula so let's see through an example suppose we take this example 1 3 4 -10 so how we are going to do this so we -10 so how we are going to do this so we -10 so how we are going to do this so we are going to defi uh divide the points array into different uh different sub arrays like this will be a different subarray and this will be a different sub there will be virtual division like we will be passing the uh divided uh rows of the points array to the function and we would not be actually dividing the array so we would be creating a function two time and we would be passing a sub array from and a sub array to do this and we'll calculate the time using this formula so let's see so initially the ACC accumulated time will be zero so first of all the two from will be this and two will be this uh from will be 1 and two will be 34 so we use this formula calculate so the maximum becomes three okay accumulated time is three then in the second point we go from 34 to we go to -1 0 then we apply the formula again X2 -1 0 then we apply the formula again X2 -1 0 then we apply the formula again X2 - X1 Y2 - y1 we take the - X1 Y2 - y1 we take the - X1 Y2 - y1 we take the maximum so in this case the maximum becomes 7 so we take seven and after accumulating and traversing all the points the since the accumulated time is 7 so we return 7 which is true as per the given sample test case so this is how we are going to do this but uh now let's come to the code section of this approach but before that do like the video share it with your friends and subscribe to the channel so first of all in this we need to define a time to calculate the result then we are iterating on the this will start from one points since we will be dividing so we'll be using IUS one so that's why I'm starting it from one so time plus equal to we'll create a function two time function will be created and this will take virtually divided subar so points of IUS one points of I this is the from we are going from this point points of IUS one to we are going to points of I okay and here we need to return s simply the time now let's write the two time function as well one will be 2 one will be from we can Define two variables here x difference will be giving m. Abs from 0 minus two of Z because the zero index is containing the X coordinate and for the y coordinate we'll be using from of Z from of one and from two of one and we have to return the maximum of this now let's I think I've written the code let's run it for the sample test cases there's some error here and what's the oh we have to give the return type the sample test cases are passed let's try to run it for the hidden test case as well okay passed so the time complexity for this solution is O of n uh where n is the number of points in the points array and the space complexity is O of one because we are not using any extra space in this so there is the complexity if you want the C++ JavaScript and python code you the C++ JavaScript and python code you the C++ JavaScript and python code you can go to the solutions panel in the lead code section and check this solution this is my solution given here and you can go down you can also see the explanation intuition complexities and you can check the code for Java C++ python JavaScript and yes for Java C++ python JavaScript and yes for Java C++ python JavaScript and yes you can afford the solution as well so thank you for watching the video have a nice day I hope you like the video and understood the logic
|
Minimum Time Visiting All Points
|
minimum-time-visiting-all-points
|
On a 2D plane, there are `n` points with integer coordinates `points[i] = [xi, yi]`. Return _the **minimum time** in seconds to visit all the points in the order given by_ `points`.
You can move according to these rules:
* In `1` second, you can either:
* move vertically by one unit,
* move horizontally by one unit, or
* move diagonally `sqrt(2)` units (in other words, move one unit vertically then one unit horizontally in `1` second).
* You have to visit the points in the same order as they appear in the array.
* You are allowed to pass through points that appear later in the order, but these do not count as visits.
**Example 1:**
**Input:** points = \[\[1,1\],\[3,4\],\[-1,0\]\]
**Output:** 7
**Explanation:** One optimal path is **\[1,1\]** -> \[2,2\] -> \[3,3\] -> **\[3,4\]** \-> \[2,3\] -> \[1,2\] -> \[0,1\] -> **\[-1,0\]**
Time from \[1,1\] to \[3,4\] = 3 seconds
Time from \[3,4\] to \[-1,0\] = 4 seconds
Total time = 7 seconds
**Example 2:**
**Input:** points = \[\[3,2\],\[-2,2\]\]
**Output:** 5
**Constraints:**
* `points.length == n`
* `1 <= n <= 100`
* `points[i].length == 2`
* `-1000 <= points[i][0], points[i][1] <= 1000`
| null | null |
Easy
| null |
1,928 |
is so minimum cost to reach a destination in time question so we are given Ages which is a graph and we also have the maximum time we want to go from The Source node to the destination node and we must fulfill that the total time used should be less or equal the maximum time and then we wish to know what would be the least parsing fee we needed to pay so the passing fee would be the sum of the fee of all the notes on the path so if we choose the first road then the passing field would be five plus one oh sorry plus two plus three and we should notice that the time in total would be 10 plus 10 Which is less than maximum time but what if the maximum time change to 29 then we cannot choose the first row we can only go to the second Road and then the passing field would be 48 so how to solve this question we notice that it's actually trying to solve the shortest path question but in this case the distance is not the real distance but the sum of the passing feet so it's kind of a cost a type of cost or distance we may think of the digestral algorithm which is to make sure the first time we reach one note would be the time the cost is minimum so basically we can use the digestional algorithm to solve this question and at the same time we just need to add one restriction about the maximum time like when we reach each node what is the time so far if the time plus the time to next node exceed the maximum time then we cannot add the neighbor node otherwise we can add it into the Heap but what about the like pruning can we be faster otherwise it will make whole time limitation uh exceeded Arrow because there are so many notes would be added to the Heap one thing we can do the pruning is that well it's I think I will draw this figure again so I'll just do let's see um wait a second so I just go here okay so what I'm trying to say that let's suppose there are three note but actually this is the destination note so well if this is the this one is the left is the source node and then there's a Target so there are two nodes here of the time here would be like two one and the like the fee would be um for example it's four and maybe this is five it's Etc well at the first we will like uh I will give some name this is a b c d so for node a we will because the source node so we will uh include that node and then we it has been pulled to the queue then we have two neighbors to decide right to name BC so we can put a b to the cube and what would be the time would be there too right and what is the fee would be uh no matter what it is it will be one plus four it would be five right this is the fee and the same for the c would also be um offer to the queue and the time would be one and the fee would be six one plus five six right and then things this five is less than six so it this B would be pull from the Q first and then we check it has the neighbor of c and d right do we want to offer C again to the Q that's the question actually no why because now if we go to C the time would become 2 plus 2 equal to four right but previously the time would only be one so actually means the time become larger if the time becomes larger then it actually means a we these parts would never be the result one of the results since we set the priority of the Heap based on the passing fee so anyone with the smaller field would be poor first so since the fee go to B is smaller than if we go to C so B has been pulled first um at this time the one we go to see the field to be larger and the time would be larger so it's not we don't need to offer C to the Q anymore since it would never be the result so as you can see we can do the pruning here we should have a minimum time array which uses two records at the time um to each node so at the very beginning when we offer and the pole a from the Q we will add the BC to the Heap right and then we update the minimum time to the C to one oh I mean it means C right and equal to one so afterwards when we pull B from the Q the time from C would be 2 plus 2 which is four right but since it's greater than one so we will not over C to the Q so we actually save the time so that's the reason we need a minimum time to do the pruning okay the rest is the same as the typical digestive algorithm okay let's write it first the graph is represented at AJ so we need to candy the two agency list so it would be graph new array list since we know the lens of the graph right in total is n so I equal to zero I less than n plus and then graph add the new array list and then we iterate the h H then H is then it from equal to h0 2 equal to H1 and the fee would equal to H2 and then graph um get because this is a undirectional graph so we get from and add the ending node which is 2 and the C which represents the weight and it gets to add the new into from feet so that would be the graph then we will use the priority Q what would we saved inside would be oh we will need to save the priority which is a cost we also need to save their time and the know the index so it will be an integer rate and then we call it the Heap and the new priority queue we should Define the comparator which will be a b and we just put the priority as the first element so to be a0 minus B zero okay then we put the first note into the Heap the priority would be passing fee zero and the time would be zero no the index will also be zero so while hip is not empty we will just pull a thing from hip and then we will know the curve cost is curve one curtain is cursed one and the kernel though the beaker two then if kernel equal to M minus one we reached the target so we just return curve cost otherwise we'll need to check its neighbor which is a graph get node and then for each one we will catch the next note would be neighbor one also a0 and the next time what time to reach there would be neighbor one um yeah okay so then we just check if the uh if the time we used to reach the next node exceed the maximum time or it exceeded the minimum time reached the next node we will just continue so we also need a minimum tan which the size would be in and the things we want to get some the mini the like the smallest thing so we first failed it to um integer max value so here if the time next time plus curtain like uh we can just uh write it give it a name so it would be well anyway so just if it's greater than maximum time so there's no way to use it or it is greater or equals a minimum time this is for the pruning so it would be um next note right it's a bit greater then continue otherwise we just write a minimum time next node equal to this one and at the same time over this node to hit then with the first would be the feet right so it will be curve Cost Plus passing fees next note and the time the this is the time and then the next node index so in the end the return next one okay or we didn't Define them equal to passing fees passing feast or length okay thank you for watching see you next time
|
Minimum Cost to Reach Destination in Time
|
number-of-orders-in-the-backlog
|
There is a country of `n` cities numbered from `0` to `n - 1` where **all the cities are connected** by bi-directional roads. The roads are represented as a 2D integer array `edges` where `edges[i] = [xi, yi, timei]` denotes a road between cities `xi` and `yi` that takes `timei` minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself.
Each time you pass through a city, you must pay a passing fee. This is represented as a **0-indexed** integer array `passingFees` of length `n` where `passingFees[j]` is the amount of dollars you must pay when you pass through city `j`.
In the beginning, you are at city `0` and want to reach city `n - 1` in `maxTime` **minutes or less**. The **cost** of your journey is the **summation of passing fees** for each city that you passed through at some moment of your journey (**including** the source and destination cities).
Given `maxTime`, `edges`, and `passingFees`, return _the **minimum cost** to complete your journey, or_ `-1` _if you cannot complete it within_ `maxTime` _minutes_.
**Example 1:**
**Input:** maxTime = 30, edges = \[\[0,1,10\],\[1,2,10\],\[2,5,10\],\[0,3,1\],\[3,4,10\],\[4,5,15\]\], passingFees = \[5,1,2,20,20,3\]
**Output:** 11
**Explanation:** The path to take is 0 -> 1 -> 2 -> 5, which takes 30 minutes and has $11 worth of passing fees.
**Example 2:**
**Input:** maxTime = 29, edges = \[\[0,1,10\],\[1,2,10\],\[2,5,10\],\[0,3,1\],\[3,4,10\],\[4,5,15\]\], passingFees = \[5,1,2,20,20,3\]
**Output:** 48
**Explanation:** The path to take is 0 -> 3 -> 4 -> 5, which takes 26 minutes and has $48 worth of passing fees.
You cannot take path 0 -> 1 -> 2 -> 5 since it would take too long.
**Example 3:**
**Input:** maxTime = 25, edges = \[\[0,1,10\],\[1,2,10\],\[2,5,10\],\[0,3,1\],\[3,4,10\],\[4,5,15\]\], passingFees = \[5,1,2,20,20,3\]
**Output:** -1
**Explanation:** There is no way to reach city 5 from city 0 within 25 minutes.
**Constraints:**
* `1 <= maxTime <= 1000`
* `n == passingFees.length`
* `2 <= n <= 1000`
* `n - 1 <= edges.length <= 1000`
* `0 <= xi, yi <= n - 1`
* `1 <= timei <= 1000`
* `1 <= passingFees[j] <= 1000`
* The graph may contain multiple edges between two nodes.
* The graph does not contain self loops.
|
Store the backlog buy and sell orders in two heaps, the buy orders in a max heap by price and the sell orders in a min heap by price. Store the orders in batches and update the fields according to new incoming orders. Each batch should only take 1 "slot" in the heap.
|
Array,Heap (Priority Queue),Simulation
|
Medium
| null |
409 |
so given a string which consists of Upper and upper and lowercase like this so return the length of the longest palindrome that can be built with those letters and the letters are case sensitive for example a cannot be considered as a palindrome here so what is the parental number Palatine number or palindrome string is a string if you read it from left to right or right to left that will give the same string so let's say take an example a b a so if you read it from left to right it's a b a similarly let's read it from right to left then it's a b a so both are same so this can be a palindrome if it is a number then let's say 121 so left to right is 121 right left is one two one same number so they are the parallel numbers let's say let's take another example ABC so left to write it is ABC but right to left it is c b a which both are not equals this is not a palindrome string so and one more thing we have noticed what here is case sensitive the letters are case sensitive so let's say kind of a okay so from left to right it's a capital A but right to left it is capital a capital A at e so these two are not equal because a both the A's are treated differently so that is what they mean here so what is the approach to solve this problem uh one thing we can make sure is so they are given the string and we have to generate and longest parallel from this let's say any letter b is given or c this can be a palindrome for sure because if two even number of unilateral is present then that will be included in the pylor group for sure because if you say b a b r if they are even see first we can append it first another one can appear in the end so that middle it can contain any number or any digit or uh sorry any letter or it may not contain anywhere foreign CA C and then this is also a palindrome so any letter that is appearing even times that will be a palindrome for sure so how do I get to know a letter is applying even times or not for how do we get to know that so for that let's have a use hash map and this is here we will use the array of size 123 or 128 also 1.8 will cover all last 123 or 128 also 1.8 will cover all last 123 or 128 also 1.8 will cover all last key values 123 we know the integer range capital a capital Z is 65 tonight then all this range will be covered so first of all iterate over the string so a is a present so we'll have all the letters and let's initialize it with zero let's create an array of size 123 and let's initialize all the values to zero once you find a in the place of a this is a let's say here it is K let's next again you move to C so increment the value by one three C's are there so it should be 4. then I get two more disks so it will be three so finally in that way you have this minus a appearing one C appearing four times D appearing three twice now I try to other okay you could see a is appearing only once appear in only once can this be included in the polynomial that I'll come to next okay now we will go to c is appearing even times how do you need to know whether a number uh digit is appearing even times or not you have to do four modulus two other is equal to 0 then that will be increment included in the program so count plus C equals to four you do so count will be four okay next year more to D here in this case three modulus 2 is not equal to zero so can this be included in the Peloton equals to given number 3 minus 1 Q so that will be 2 . so account will be so that will be 2 . so account will be so that will be 2 . so account will be incremented to 6 now and what about this remaining one so remaining one if you see in D we have one and in a also we have one so similarly this rule applies for a as well so since a has only one if we subtract it minus 1 then it will be 0 so let's say let's have a combination let's say c and One D here so in this middle there can be either d or a this is what we can have to get the palantrope okay so this is what we can have to get the value how do we select b or a for that what we need to do is after the loop we will have a Boolean variable called Earth odd form okay we'll set it to false initially if in case we get any number model is to not equal to zero then all form will be set to true so that after the loop if out for also is set to true then we will add that count as well either the one or D we cannot add both D or uh you can add either D or E so that's why after the loop we'll check whether we have odd found is set to true or false so I'll explain this from beginning so any number that is model is 2 if it is equal to 0 then just add the count okay that is one thing next if else condition what you have to do odd form should be set to true and then we have to add any number minus one odd number minus one why odd number management as I said if three d's are present out of 3D 2D can be two days can be of course we can add it to the palindrome if you find again yeah so either you can add a or you cannot add both right so if we add both then it won't be a parallel draw so at last once you set r equal to true in the first very first loop at the AO at this position only when you find the letter A when you will set or equal to true so at the after the loop you just check whether if R form is equal to true if it is set to true then you just increment the count by then that means we will add one of the odd numbers our number letter over the middle position that can be added to the valuable any other person we cannot add an odd number so first we'll create a array let's name it as character count of size 123 and all are set to 0 or usually we take a standard size of 120 that includes all the ASCII values one set it to 128. so next for each character see in the string s character count of C plus C implementer value so next what we need to do we have to titrate over the array so for int count in the character count array if count modulus 2 equal to 0 then what should we do we have to add that yeah before that you have to initialize let's initialize print max length to zero and also we'll have one volume value hard form and let that be set to false so if we get count modulus or equal to 0 we can add that to the palindrome so max length plus equals to count otherwise first we need to set odd form two and then maximum plus equals to count minus 1 y minus 1 if it is 3 if so one lesson in that only we can add it to the palindrome uh if it is seven one less eleven six is our number so we can add that to the current row that is fine so at last we have to return the max length okay um I had missed one statement here okay that got whenever it controls that it was removed so max length that's equals to count minus one that should be there no for if count modulus 2 is not equal to zero yeah and also I missed the major part as I said after the loop I have to check now if all found is set to true then we have to add one more count position so max length will be incremented so that is what let's do it sometimes it will happen you have to correct this so okay so first you wanna initialize the array of size 128 then increment the count frequency then max length there are from set to false if count modulus 2 is set to zero then you just increment the count if it is even if it is on one pressure then that number will be even so that you add that count and remaining one we don't know so that for that what we'll do is we will just set our found equal to after the loop if we set or if we have our found equal to true in such case we'll increment the max line by one that means only one odd number can be added not more than that will be in the middle position that is what this middle position and yeah can you adjust within the maxi yeah and for Java also same code so we initialize the array instead of 1.3 your connection is array instead of 1.3 your connection is array instead of 1.3 your connection is 1.8 that's the standard value and for 1.8 that's the standard value and for 1.8 that's the standard value and for each character in the string so you convert into the array of characters and then increment the count same procedure will submit this yeah successfully submit 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 until then keep learning thank you
|
Longest Palindrome
|
longest-palindrome
|
Given a string `s` which consists of lowercase or uppercase letters, return _the length of the **longest palindrome**_ that can be built with those letters.
Letters are **case sensitive**, for example, `"Aa "` is not considered a palindrome here.
**Example 1:**
**Input:** s = "abccccdd "
**Output:** 7
**Explanation:** One longest palindrome that can be built is "dccaccd ", whose length is 7.
**Example 2:**
**Input:** s = "a "
**Output:** 1
**Explanation:** The longest palindrome that can be built is "a ", whose length is 1.
**Constraints:**
* `1 <= s.length <= 2000`
* `s` consists of lowercase **and/or** uppercase English letters only.
| null |
Hash Table,String,Greedy
|
Easy
|
266,2237
|
165 |
hello everyone hope you all are doing well so i am back with another daily challenge and it is late number of 165 compare version numbers it is a medium level question and i also fill the cell however you can see that the ratio of the light and the dislike is very poor more people don't like the question however i am able to solve it enough in one go but still i uh i also don't like this question okay very poor quality of question and but still we need to solve it so i'm going to explain this okay so the question is you are given to number version one and version two and you need to compare them okay so the description of the question is again very poor okay so i will explain it like what we have to do okay so you can see here you are given two versions okay and version length can go up to 500 okay so you are given two version uh and you have to compare this to version okay and oh and if your version one is small uh what is the condition if the version one is smaller than version two written minus one if my version one is greater than version two return one otherwise written zero okay so for example uh you can see here the version one and version two are zero it means both are equal okay how look if you got some leading zero just simply ignore it okay so if you ignore this leading zero it will be one point one and in the version two also if you ignore this leading zeros it will be one point one again so they both are equal so we just written zero similarly for this example you can see that one dot zero and here it is one dot zero so one dot zero is equivalent to one dot zero okay because zero don't have any values okay leading zero there so we can ignore it so just simply written again zero but in the third example you can see that it is zero point one and version one it is one point one and version two of course one point one is greater version than the 0.1 therefore version than the 0.1 therefore version than the 0.1 therefore uh version 2 is greater okay so we just simply write a minus 1 so here you can see that it returns -1 see that it returns -1 see that it returns -1 so the constraint is version 1.length and the constraint is version 1.length and the constraint is version 1.length and version two dot length can go up to 500 version one and version two contain only digit and dot version one and version two are the valid version numbers okay and all the given revisions in version one and version two can be stored in a 32-bit integer okay 32-bit integer okay 32-bit integer okay uh like what is the revisions uh the element okay this part in between the dots okay like for this example it is one point zero so one is one version zero is another version and zero is another version for this example one is a version and zero one is another one uh revision sorry okay node version it is revision the complete string is a version okay so let's go through the explanation um okay so here now we have to take some of cases like we have to handle three cases okay so case number one is leading zeroes okay if my string is something like 0 1 dot 1 0 1 dot 0 1 0 sorry 1 0 1 okay so this is equivalent to one point one zero one okay we just simply remove all the leading zero so this one and this one now case number two guess number two it is leading zero okay but empty revision leading zero leads to empty revision uh so what is it like if it is like something like 0 1 0 then it is again 0 1 so if you remove all the leading zeroes then this can this three zero can uh can lead you to an empty revision but you cannot uh make an empty revision so what you have to do you just simply need to put a single zero in place okay like this remove all the revision and if your revision all the leading zero in from the from a particular division if it is empty then just simply put zero otherwise put one otherwise uh put other string okay the remaining string now case number three if length of two string okay are different like if my string a is 1 0 1 and my length of string b is 1 0 1 again 0 1 okay so you can write this two string as one zero and dot one and you can write this string as one zero dot one okay so here you can see that in this uh a there is only two revision but in b we have three revisions okay so what you have to do if there are then we have to simply take a revision and put a zero okay so we will compare this and one more observation you can see here like it is given that the uh the divisions can be stored in a 32-bit integer okay so be stored in a 32-bit integer okay so be stored in a 32-bit integer okay so what we are going to do we will first of all reduce this lead in zeros okay and just simply convert uh this revisions okay after removing this leading zero into an integer and store that into a vector okay and that element into a vector for both the strings we do the same in two different vector okay after that we just simply compare it like for this example uh let's take this two example you can compare like it is first of all it is one zero dot one dot zero okay then it is one zero dot one so these two are same so if we will continue further then one and one is same then it is zero is less than uh one okay means uh string one is less than string two so we will return a minus one okay here you can see that the version one is if less than version two it will be minus one okay and if it is vice versa then we will return one so we will do the same thing okay so let's see the code uh i think i have explained you all the observations and concepts okay so let me show you the code so here i have taken two function one is a helper function which will which i used to remove the leading zeros and put all my revisions to a vector okay and one is checker which check if my uh we check this conditions okay this three condition so first of all i pass my version one and version two or separately and store it in b1 and v2 vector so i passed it and i checked uh and i put a text string and i direct for from the string and i check if my current character is zero okay and my string size is not equal to zero what that means if my string size is not zero then what i what it means like uh there are some element before this zero so it cannot be a leading zero okay otherwise if my uh see if my current character is not zero if it is one two three any number and if it is not dot okay other than zero and dot we can put we can add this element to our string okay this str then i check if my c if my current character is a dot or my i is equal to equals to n minus 1 means that i have processed this complete string okay then i have to put this uh this revisions inside my vector okay so what i have done i am just checking if uh if my string size is zero okay if there is some leading zeros like zero okay uh then it can it will give you a empty string okay so i check and i just put a single zero inside my string and i just convert it to integer okay because it is given that uh your revision can be inside earth in a story inside a 32-bit integer okay inside a 32-bit integer okay inside a 32-bit integer okay and i just simply push that inside my integer vector and i reset my htr to empty okay so basically what i am doing i am just uh taking this revisions one by one okay this revision one then again one revision one division and i just convert it i remove all this um all the leading zeros and i just convert it into integer and i just simply store it okay now what i have done and i just uh i have i just written my vector okay now int checker uh for the attacks of injector like you can see that i have passed both the vector okay v one and v two for version one and version two and uh i just going through i just go through this uh complete vector of means both the vector and i check if my current i and j is minus 1 or not okay if it is uh it means if it is uh i v if i first vectors i is less than my v2s vectors then it is it means that version 1 is less than version 2. so i just written minus 1 else if is it is greater than v2 v1 is greater than v2 then i just written one okay otherwise i just simply iterate okay after that as i told you if there is let's say it is 1 0 and 0 1 and there is number like 1 0 1 then something ok then again something ok so we have to consider this like 0 and 0 for the previous means for the smaller one so this condition is for that okay i am checking if my i is less than weight of size it means i have not i tried my first vector completely so i check it with zero okay so if it is greater or it means that version 1 is greater than version 2. i just simply written one and similarly for this i will check for version 2 is greater than version 0 i mean so version 1 so i will written -1 mean so version 1 so i will written -1 mean so version 1 so i will written -1 if all this if any of them uh will not satisfy then i just simply return zero it means that both my string are uh simply same okay so finally i just return my answer and from this function and then i just return that element of that integer to my driver okay so i hope you understand this concept and there it and let me submit it okay so it is hundred percent faster you can see that and i have tried three times uh and all that i might get zero milliseconds so hope you understood this explanation and you like and if you then do a like share and subscribe to the channel it will motivate me okay and i will provide this code and my solution uh with that description box so you can if you need you can check it out okay so i will see you tomorrow till then goodbye
|
Compare Version Numbers
|
compare-version-numbers
|
Given two version numbers, `version1` and `version2`, compare them.
Version numbers consist of **one or more revisions** joined by a dot `'.'`. Each revision consists of **digits** and may contain leading **zeros**. Every revision contains **at least one character**. Revisions are **0-indexed from left to right**, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example `2.5.33` and `0.1` are valid version numbers.
To compare version numbers, compare their revisions in **left-to-right order**. Revisions are compared using their **integer value ignoring any leading zeros**. This means that revisions `1` and `001` are considered **equal**. If a version number does not specify a revision at an index, then **treat the revision as `0`**. For example, version `1.0` is less than version `1.1` because their revision 0s are the same, but their revision 1s are `0` and `1` respectively, and `0 < 1`.
_Return the following:_
* If `version1 < version2`, return `-1`.
* If `version1 > version2`, return `1`.
* Otherwise, return `0`.
**Example 1:**
**Input:** version1 = "1.01 ", version2 = "1.001 "
**Output:** 0
**Explanation:** Ignoring leading zeroes, both "01 " and "001 " represent the same integer "1 ".
**Example 2:**
**Input:** version1 = "1.0 ", version2 = "1.0.0 "
**Output:** 0
**Explanation:** version1 does not specify revision 2, which means it is treated as "0 ".
**Example 3:**
**Input:** version1 = "0.1 ", version2 = "1.1 "
**Output:** -1
**Explanation:** version1's revision 0 is "0 ", while version2's revision 0 is "1 ". 0 < 1, so version1 < version2.
**Constraints:**
* `1 <= version1.length, version2.length <= 500`
* `version1` and `version2` only contain digits and `'.'`.
* `version1` and `version2` **are valid version numbers**.
* All the given revisions in `version1` and `version2` can be stored in a **32-bit integer**.
| null |
Two Pointers,String
|
Medium
| null |
1,183 |
everyone with Calvin here so let's accessible beauty contests eight for question so we have a matrix of size win with time sake and then every cells inside have either value of 0 or 1 and any square sub-matrix of the of their any square sub-matrix of the of their any square sub-matrix of the of their matrix with size of side length times a lens can have at most maximum number of one equals max ones so see the first example we have matrix of 3 times 3 and then sub matrix of 2 times 2 so all any of the sub matrix of 2 times 2 inside that 3 times team 3 matrix can have at most one number of 1 ok so this will be one of the matrix here as you can see the every 2 times 2 matrix there will be having 1 number of 1 at most okay so you can see here right yeah so in the whole 3 times 3 array you can put at most 4 number of 1 inside and take a look on the second example so with n hey also same 3 times 3 and then sapere is 2 times 2 and then you can have at most 2 number of 2 in the 2 times 2 sub matrix so the answer will be 6 so this is the array that can be formed so let's see here the second example so every 2 times 2 will have at most 2 number of 1 inside yeah so that is the second example so how we going to solve this question first we can divide the array the matrix I mean so by the number of holes array and then the rest of it ok and then we put index on each of them so yeah 0 1 2 3 4 5 and then we continue it so even though for the rest for the module apart it's like so also we can imagine it something like this right but this thing here doesn't exist okay so yeah after we put index on all of the sub array then we can determine like zero so of the most frequent here like many times and one so up six times right and then for also for so our only four times and 3 so up six times here okay so this frequency of so up the most frequent one is zero and then the next most frequent one is either 1 or 3 or to rank so that then that we can determine where we should put our one in the entire race so if we have at most one number of one then all the 0 will become we can put one there ok and so on so let's take a look on the code so maximum number of one so first I have a sub array of we have an array of size sitelinks times a link and then I look through the entire matrix to determine how many number of 0 1 2 3 4 and so on so the index 0 how many times it's so up here like the square does the square of the first part let's say the I equals 0 right imma do lose sight line and J modulo cell length equals 0 so it will be this okay yeah and we add up the frequency and then basically after that we have a priority queue so we look through the entire square of size site link and then put it to the priority queue with priority disk ending we get from the highest priority first okay and what is the output so the output of total is equal to depends on how many number of ones we want to take from the most frequent one until they're less frequent one so in our case we will take from zero and then take the one take the two and then take the three and then four and five is less frequent like only four times here right the five also only four times so yeah that's it for this question thank you for watching see you on the next weekly contest
|
Maximum Number of Ones
|
statistics-from-a-large-sample
|
Consider a matrix `M` with dimensions `width * height`, such that every cell has value `0` or `1`, and any **square** sub-matrix of `M` of size `sideLength * sideLength` has at most `maxOnes` ones.
Return the maximum possible number of ones that the matrix `M` can have.
**Example 1:**
**Input:** width = 3, height = 3, sideLength = 2, maxOnes = 1
**Output:** 4
**Explanation:**
In a 3\*3 matrix, no 2\*2 sub-matrix can have more than 1 one.
The best solution that has 4 ones is:
\[1,0,1\]
\[0,0,0\]
\[1,0,1\]
**Example 2:**
**Input:** width = 3, height = 3, sideLength = 2, maxOnes = 2
**Output:** 6
**Explanation:**
\[1,0,1\]
\[1,0,1\]
\[1,0,1\]
**Constraints:**
* `1 <= width, height <= 100`
* `1 <= sideLength <= width, height`
* `0 <= maxOnes <= sideLength * sideLength`
|
The hard part is the median. Write a helper function which finds the k-th element from the sample.
|
Math,Two Pointers,Probability and Statistics
|
Medium
| null |
1,095 |
Hey guys welcome and welcome back to my knowledge today's problem is find in mountain array it is a very interesting problem and there is a concept in it which will be good for your revision so first let's see what is the problem ok so the problem is that you are given in Array and it is a mountain array if and only if. Okay, so what is a mountain array? Look at the meaning of mountain array. You can understand it from the name itself, it will be like mountain, meaning is not obviously mountain but the values will be like mountain like initial value. It will decrease and then as it grows, the values will increase and a grows, the values will increase and a grows, the values will increase and a peak will come. Just like there is a peak of a mountain, after that the values will decrease. after that the values will decrease. after that the values will decrease. Okay, so a period in which initially the values increase and then after coming to a point the values increase and then after coming to a point the values increase and then after coming to a point the values start decreasing. Let's call that array a values start decreasing. Let's call that array a values start decreasing. Let's call that array a mountain array. What can we call that array a mountain array? Well, it was explained that it will start from the zero index and go till the i index in which the values will increase, then go till the i index in which the values will increase, then go till the i index in which the values will increase, then what will happen after the i index, the values will decrease till the what will happen after the i index, the values will decrease till the what will happen after the i index, the values will decrease till the last index. Okay, that means first you will increase the value of a, see that the value of a will be greater than minus one, then one will be greater than zero, then it will reach a, and then whatever will be a, will be the largest and after a, the values till the largest and after a, the values till the largest and after a, the values till the last index will keep decreasing. For example, see. Look at this array, this one is ok which is given in the test case, look at this array, is this a mountain area or not, then look at Tooth 45, it is ok, so if you see this error, okay, if you see this array, then what? This is a mountain array, look, the value is starting from the forest, it is starting from the forest and it is increasing suddenly, our value is increasing, it is increasing till it reaches G, look, the growth is bigger than the forest, then it is bigger than the forest. Se four b then f is bigger, this is the maximum value, after that see your values are decreasing, after that see your values are decreasing, after that see your values are decreasing, smaller than 5, 3 smaller than 3, so your five is your peak, that is your peak, okay, so this is your mountain array, so What are you saying that in the input we have to give a mountain array, okay and we have to return the minimum index of the target, so for the target that is given to us, we have to tell where in the mountain array it is the minimum. The index is there, look at it, like the target is right here, so the target is there, and th is R in two places, th is getting here, one th is getting here, okay, so if you do indexing, then T is 3 4 5 6 r is in two places. But what we have to return is we have to return the minimum index i.e. which is the first currency which is the i.e. which is the first currency which is the i.e. which is the first currency which is the initial currency which is so the index which is so basically what we have to return in the output which is the minimum index now see or you You must have given an array in the function, you must have been given a function in it, which means it is an array, it is not an array, basically it is an object which is given to you and this object has two functions from which you can get the values. We have to fetch, like if you have given us an array from Let's, then we have array off. If we have to take out zero, then we write like this, Er is off zero but sin because in the function that has been given to you, it has given you an object. So how do you have to find out its index values, you have to write that object dot get is ok, to use the function get, that must be a function given in the class, they must have created it in the class, so we have to use the function, so if I have to find out the value at zero index, then I If I put add gut 0, it will give me a value with zero index. Similarly, if you have to find the length of an array, then you write length of error. Here what you have to do is you have to use the err dot function. Length is ok, this is the error. You have an object, basically whatever is given is okay, whatever function you have given here, whatever will be there in it, or this is your object, then you have to call like this and see here the constraint is written that we have more than 100 mountains. Array dot cannot do get calls, that is, the number of get calls that we are doing, right, we cannot do more than 100. Okay, so now let us see the basic problem, I hope you have understood, basically we have been given a target value and We have to find that target, simple is fine in this array and its basic minimum index has to be returned, so I hope you have understood the problem, pause the video once, think for yourself, what can you do, see, this much is simple, it is clear just by looking at the question. Look friend, what do we have to do with a value, we have to find it in the array, right? We have been given this value, we have to find it in the array, that is, what do we have to do, right? What do we have to do, we have to search, so when searching. When it comes to this, it is simple, friend, we can do two types of searching, now there is no one else, we can either do linear search or we can do binary search and if you look here in the question, you have a constraint that friend, look at the gate. Calls are basically that you have to extract the value from the array, you cannot make more than 100 calls, that is, there is a restriction on how many calls can be made on the number, so if you compare yourself, in linear search, we will get every You have to go to every element of the array, you will go to every element, that is, make a get call for every element and in binary search, those calls are obviously less, so we have to reduce them, so what will we do, obviously, we will go linear. We will not search, we will only do binary search, we will do binary searching, now how to do binary searching, think for yourself once, look at this array, look at the target, see what you can do, pause the video and then we will discuss the approach once. I hope you have tried it and if you understand the approach then it is well and good, otherwise we will understand now, so let's do what I do, I write this array once 1 2 3 4 5 see if you Basic Binary Search - If you don't know you Basic Binary Search - If you don't know you Basic Binary Search - If you don't know how to do binary search, then I have made a video. In binary search, I would say that you should watch it first because I will not show you the basic binary search that will be done in it, I will show it to you through a dry run. Basically, you will have to see it yourself. Let me tell you the main concept, what will you do, okay, otherwise the video will become very long, friend, look, this array has been given and what is the target given, you have been given a target of three that you have to find three in this array, so friend, I would have done indexing. I am 0 1 2 3 4 5 and 6s Okay, so I have done this indexing, now look friend, you will think that yes friend, it is okay, this is not a normal array like we are given a sorted array, if a normal sorted array was given then How simple is this question, friend, a sorted array has been given, let's say two times, then four, sorted array, if you want to find the target in it, then do a simple binary search and the target will be found. How easy it would have been if this It is a circular array but friends, it is not a circular array. Is it a mountain array? It means that from here till here the value is increasing but after this point the value is decreasing. Okay, so you are noting one thing. Suppose you know five, which is the peak element, think you know where five is, then the values before five will know where five is, then the values before five will be in sorted order, because if F is the element of PK, then what is this? Mountain is right, so the values before the P element is right, so the values before the P element will be in increasing order, right? So you believe that if I find the element of P, then I will get a sorted array which will end at the element of P and the initial element. It will start with What do you get, what do you get, one, you get a sorted array, so what can you do on this sorted array, if you want to find the target, which is three. You can apply binary search in this sorted array, find out the index of the target, right, it is simple, similarly, if you look at the values after five, what will they be, they will be look at the values after five, what will they be, they will be look at the values after five, what will they be, they will be in decreasing order because it is a mountain array, it will be like this and then it will go down like this. So these values will always down like this. So these values will always down like this. So these values will always be in decreasing order 31 So this will be the second array that you will have the elements after the peak element, this is the P element, okay so these will be these, they will be sorted in decreasing order, is n't this also sorted? But it is not sorted in ascending order. It is sorted in descending order, so you can take Band Sir on this also. Look, Bin Satu can be taken on ascending order also but on descending, the only condition should be that it is sorted, then it is okay. There is nothing, just a slight logical change, there is no such different code of decreasing fear, this code is simple, if there was such a condition in this code, it would have happened like this, then there is not much change like this, our main concern is here. Do you know what is the main concern of finding out this PK element? If we find out the index of this PK element, then we will divide it into two arrays and find out where the target is, so first we will see in the first half why in the first half. We will see because friend we have to find the minimum index so if you have two such arrays then here if you are getting the element then obviously this one is the first one otherwise its index will be smaller. And here also the element is found but its index will be less than the one here, hence if we have to find the minimum index then we will search here first. If not found here then go here. If found here then there is no point in going here itself. Think about it's okay, so I hope you have understood about binary search. Don't worry about binary search. Our main concern is how to find this peak element. Its index is fine, so let's see how to do it. So, let me try and explain. Let me write the array once again. Tooth 45 31 It is very easy. If there is nothing, then what is your target? The target does not matter to us right now. We have to remove the P element for now. 0 2 3 4 5 6 Okay, so I What did I do here? Overall, basically the time complex of this question would have appeared. If we are doing binary search, what is the complex of binary search? It would have seen the time complex, but that is fine, let's not see it now, so see what we have to find out. Extracting the element. What is the meaning of peak element? Look at this. From here, if you go like this, then this will be the peak element. Normal array. If you have something like T 3 4 5 6, you have to extract some value from it, then what do you do? Look, we always find out the mid, what is the mid? Start ps a batu, so the mid value, if like your mid value that you get, if it is what you want to find, then you return the same, no index here. But basically we are not given any target, we know what is the peak element, we have to find that peak element, where is P, which index is P, so the property of P element is that it is in its right here. It will be bigger than both the element and the element here, is n't it? Like F is bigger than four and that is bigger than th. Right, any such element, you see in this array, there will not be such an element which is on its left and right. The P element which is bigger than both of them will be bigger than the left one and the right one will be bigger than the right one i.e. here the left one be bigger than the right one i.e. here the left one be bigger than the right one i.e. here the left one is x and the right one is y, then the element of p will be bigger than x and also ya. Look, here we have 2 which is bigger than 2 but 3 is a little bigger than 4 so this is not a p element, similarly this is just a puck element so we got to know that okay what will we do, we will bring our binary search p What will we do to find the element? Basically, we have to find the index of the element, so we have this is our array, so what will we do, we will go to the right, then what will we do, we will take out the mid, what is mid, start? Put plus start, your end is zero, which is your last index, or si batu is ok, mid, what is start plus end, batu is ok, so 6 batu, what is your 3, that is, your mid has come here. Okay on index three this is the mid this is the index okay index 0 p 6 batu so you come to this you will see if this is my p element we have to find the p element guys we have the mid which will be the mid index. Our P index will be, we have to see whether the mid P has come, which ARR of mid has come, is this the element that has come, is this our P K element and how will we find it, what is the P element. There are elements of P which are one ahead of itself i.e. if this is mid then one ahead of itself i.e. if this is mid then one ahead of itself i.e. if this is mid then what will be the index of this one mid mivi i.e. the one what will be the index of this one mid mivi i.e. the one what will be the index of this one mid mivi i.e. the one which is off mid and off mid should be greater than minus and the one which is off mid is greater than this element. Should also be bigger i.e. mid is bigger than psv index isn't it i.e. mid is bigger than psv index isn't it i.e. mid is bigger than psv index isn't it AR of mid plv If it is bigger than both i.e. bigger than both its left and right i.e. bigger than both its left and right i.e. bigger than both its left and right then our mid is the index of peak element so return mid is ok then This is our first F condition. Our condition is okay. Now comes the question of moving left or right. Now look here, if you see the one which is four, it is bigger than the one on its left, it is bigger than the three. It is bigger but it is not bigger than the one on its right. If it is greater than the one on its right, then it is not mid peak, so you have to either go to the left because in the by search, what do we do, we call one half redundant, we call one half. That's okay, you are useless and if we go to the second half, then either we go left or right, then guess which one we go, what we used to do next. In normal binary search, we used to compare the value of the target if it is greater than mid. So go to the right, if the value of the group is smaller than the middle, then go to the left. On classic binary search, but classic binary search is not going on. Here we are searching by searching so that we can find the P element. Now you see this, friend. The four which is next to four is smaller than four, so what is the possibility that it could be an element of P. Think for yourself, we have said that we are four, but currently we have to decide where we should go here. Or should we go here, you see that it is next to 4, there will be no benefit in going there, why there will be no benefit in going there because you think for yourself, friend, what is there is smaller than 4, so how will the element of future be formed. What is the P element in P, which is bigger than here, P is smaller than F, so there is no chance of it, on the other hand, if you look at F, which is P and is bigger than F, then this can be a possibility, right? That here the element f will be bigger than that, it is possible that it is a possibility, here we did not have the option, it is smaller than four, so it cannot be a peak, but f can be a peak. Can be because it is bigger than four, so who knows, it may be bigger than this one which is on the right side of its phi, so what will we see, how will we shift left and right, look, we will bring elf condition, our condition will be that if your error is Off mid er off jo mid aya hai if then va is bigger than your arr off mid plus va i.e. like here we are currently i.e. like here we are currently i.e. like here we are currently doing a work then we would have taken it smaller if it is small no but here we take it if jo Your error is of mid, it is bigger than mid minus w, so look at er mid, is it bigger than what is a mid minus w, that is, from th, so it means that there is no point in going to the left side because th is small, so Go where on the right side, then what will happen here is that your mid current will start, it is okay, otherwise this is the if condition, otherwise what to do else, if it is not so, that means your mid current is bigger than this one, it is smaller, okay. If it is smaller than here, then what will you have to do, you will have to go to the left, that is, whatever will be the end, your mid will be -1, whatever will be the end, your mid will be -1, whatever will be the end, your mid will be -1, that is, here we will write mid, not mid-1, because what condition will I put write mid, not mid-1, because what condition will I put write mid, not mid-1, because what condition will I put in the Y loop? There is an outer condition of binary surge, that is, I will put start not equal to end, that is, I am doing this, okay, let's understand once by looking at the code. Okay, let's understand by looking at the code, so see what I am doing to get the peak. I see here, first of all I have placed the mountain array, I have applied the dot length function to it and I have taken out the length, why dot length because this is an object here and its length will come like this, its length will not come like this, you are the lane of mountain array. Don't do this because this is not an error or you are given the object okay so after that this is the initial left and right which is our last index or left is lesson right is okay classic binary search see if here I lesson is equal to two If I write then I have to do mid minus and here. If I am doing less then here mid right has to be kept mid. Okay, there are two things, so let me tell you a little about binary search, the meaning of the condition. It's just a game, friend, it's not like that, it's not rote, if your start, if you are putting such a condition, is it not in the will, if you are putting equal to, then you always make the right mid minus and make the start mid plus, it's okay if. Similar if on the opposite side, if you are not putting equal in the while, you are putting start less than end, then you do your right mid and start mid plus and, okay, it means basically where will the difference come here, on the right one you dry once. Try running it on some test case and you will understand what it is, then look at how we are extracting P. Left is less than right. Middle is taken out. Okay, middle is taken out. If your middle element is bigger than your right element, isn't it or equal? It means that here, if this peak of yours is x, this is your root of let's, this is your The elements of P are not there, here they will go to the right side, then they will go to the left, that is, the end which is our end, which is right, means we will reduce it to the middle, otherwise we will increase the left side, so in this way, your peak index will be yours. Left will come. Left is ok, so basically we got the peak index. From this code, we got the peak index. You can dry run it. Once you understand it well, you are okay. So from lets, we got the peak index. So this is our array. Hey Nature Four, I am focusing more on the concept. Guys, I am assuming that you will do the dry run yourself because if you focus too much, then let's give you the peak. Your index is stored in the peak element. Ka means what has come in the peak, P is equal to P, this element of P is four, so four index has come which is the index of the element of P, so now we will have two arrays, one is this array which is from here. It will be till here and the second array will be from here till here, we will apply normal binary search in it, in this we will bring reverse binary search which is binary search in descending order. Okay, so see, one of your left and right will be from zero to the element of P, that is, if Look at this array of yours, this one is fine, this one is one 2 3 4 5 so this is 0 1 2 3 4 5 i.e. zero one 2 3 4 5 so this is 0 1 2 3 4 5 i.e. zero one 2 3 4 5 so this is 0 1 2 3 4 5 i.e. zero index will be your L and the right one will be yours which was index of PK i.e. four yours which was index of PK i.e. four yours which was index of PK i.e. four is ok this one becomes your array this But you apply a normal binary search to find the target, if 'f' is you apply a normal binary search to find the target, if 'f' is you apply a normal binary search to find the target, if 'f' is your three, then from here to index your answer will be returned, okay, we are doing this normal binary search, look, it is a normal binary search, okay, there is nothing different in it, simple. Which is your normal binary search? Otherwise, what to do? Reverse binary search. On whom will the reverse binary search be applied? This is the index p which is after the peak i.e. what will happen on the left. In this, the left after the peak i.e. what will happen on the left. In this, the left after the peak i.e. what will happen on the left. In this, the left will be peak psv i.e. four index pv 5 so it will start from F. psv i.e. four index pv 5 so it will start from F. psv i.e. four index pv 5 so it will start from F. What will be the array and end index which is your right i.e. your right i.e. your right i.e. sis is okay length minus and now nothing happens in reverse binary search like if here you have just this condition in it your reverse happens okay basically because what is happening now. That if your which if this is your mid then here you have big values and here you have small values because values and here you have small values because values and here you have small values because descending order is right so in reverse bond search there is just nothing different it will be like this see let me explain you a little example like from lets you have 3 2 1 is okay and what do you have to find three, if the target is three, then what will come mid, this mid will come, now you see that it is in descending, okay, that is, if you write such a condition that a RR of Mid, if the target is bigger than your target, A RR of Mid, i.e. target is bigger than your target, A RR of Mid, i.e. target is bigger than your target, A RR of Mid, i.e. three, which is obviously bigger, A RR of Mid, i.e., then in this case, you have to shift to the left, Mid, i.e., then in this case, you have to shift to the left, Mid, i.e., then in this case, you have to shift to the left, then what do you do to your end? You will give because there will be big elements here, because there is a descending order, so it will go to mid minus and whereas in normal binary search, it is the reverse. In normal binary search, if we want to go towards the big, if we want a big element, then we go in this direction, but because it is descending. So we will go in this direction, so see if your target here is big, see this target, if your target is big in that, then you will do mid minus and you are okay, so look at this, your basically binary, if you get into this, then you Return from here, if you are getting it in the second half then you return from here, so this is your approach and this was your question basically I hope you have understood what we are doing is time and time complex because We are using binary search and if you look carefully, we are taking only variables everywhere, we have not created any such extra array, right, our space will also be constant, okay, O of one, so this is If time is complicated then tell in the comment section and you will get this code in the description, so if you found the video helpful, please like, subscribe, share the channel with your friends, this is a very important question and thanks for watching.
|
Find in Mountain Array
|
two-city-scheduling
|
_(This problem is an **interactive problem**.)_
You may recall that an array `arr` is a **mountain array** if and only if:
* `arr.length >= 3`
* There exists some `i` with `0 < i < arr.length - 1` such that:
* `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]`
* `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`
Given a mountain array `mountainArr`, return the **minimum** `index` such that `mountainArr.get(index) == target`. If such an `index` does not exist, return `-1`.
**You cannot access the mountain array directly.** You may only access the array using a `MountainArray` interface:
* `MountainArray.get(k)` returns the element of the array at index `k` (0-indexed).
* `MountainArray.length()` returns the length of the array.
Submissions making more than `100` calls to `MountainArray.get` will be judged _Wrong Answer_. Also, any solutions that attempt to circumvent the judge will result in disqualification.
**Example 1:**
**Input:** array = \[1,2,3,4,5,3,1\], target = 3
**Output:** 2
**Explanation:** 3 exists in the array, at index=2 and index=5. Return the minimum index, which is 2.
**Example 2:**
**Input:** array = \[0,1,2,4,2,1\], target = 3
**Output:** -1
**Explanation:** 3 does not exist in `the array,` so we return -1.
**Constraints:**
* `3 <= mountain_arr.length() <= 104`
* `0 <= target <= 109`
* `0 <= mountain_arr.get(index) <= 109`
| null |
Array,Greedy,Sorting
|
Medium
| null |
1,763 |
and I don't really know what comes next I'm just doing my best even though I'm so stressed out everything just feels like a test that I feel so depressed when I can't seem to get up with something deep inside won't let me quit I swearing that's what God inspired by thirst I'm inspired by worth I desire your worst so you can just hide while I work I'm tired you first all right the second third verse about the lies you go disperse you never did I know it hurts but something deep inside won't let me Secret s the best foreign foreign foreign foreign foreign foreign foreign
|
Longest Nice Substring
|
all-valid-triplets-that-can-represent-a-country
|
A string `s` is **nice** if, for every letter of the alphabet that `s` contains, it appears **both** in uppercase and lowercase. For example, `"abABB "` is nice because `'A'` and `'a'` appear, and `'B'` and `'b'` appear. However, `"abA "` is not because `'b'` appears, but `'B'` does not.
Given a string `s`, return _the longest **substring** of `s` that is **nice**. If there are multiple, return the substring of the **earliest** occurrence. If there are none, return an empty string_.
**Example 1:**
**Input:** s = "YazaAay "
**Output:** "aAa "
**Explanation: ** "aAa " is a nice string because 'A/a' is the only letter of the alphabet in s, and both 'A' and 'a' appear.
"aAa " is the longest nice substring.
**Example 2:**
**Input:** s = "Bb "
**Output:** "Bb "
**Explanation:** "Bb " is a nice string because both 'B' and 'b' appear. The whole string is a substring.
**Example 3:**
**Input:** s = "c "
**Output:** " "
**Explanation:** There are no nice substrings.
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists of uppercase and lowercase English letters.
| null |
Database
|
Easy
| null |
1,678 |
hey everybody this is larry this is me going over q1 of the week the contest 2218's first forum q1 uh hit the like button to subscribe on drummond discord and you can watch me solve it live during the contest afterwards um but go faster interpretation so i think this is pretty straightforward in the sense that you just have to be really careful uh into looking at the substrings uh and there's no the easy part about this problem is that there's no ambiguity about it um all you have to do is just you know convert these sub strings to uh al and this substring to o ooh and to get gold and that's pretty much it really uh and the way that i did it in python is with one line uh just by doing well what you see here so yeah i think i have probably one of the fastest scores in a contest on this problem i did it in about 50 seconds during the contest um yeah i don't really have much to explain about this one um let me know what you think and let me know how you did during the contest uh and you could watch me do that now three seconds let's go wish me luck what uh hey thanks for watching hit the like button hit the subscribe button join me on discord let me know what you think about this farm or other farms and let me know if you have any questions uh and i will see y'all next contest bye
|
Goal Parser Interpretation
|
number-of-ways-to-split-a-string
|
You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order.
Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`.
**Example 1:**
**Input:** command = "G()(al) "
**Output:** "Goal "
**Explanation:** The Goal Parser interprets the command as follows:
G -> G
() -> o
(al) -> al
The final concatenated result is "Goal ".
**Example 2:**
**Input:** command = "G()()()()(al) "
**Output:** "Gooooal "
**Example 3:**
**Input:** command = "(al)G(al)()()G "
**Output:** "alGalooG "
**Constraints:**
* `1 <= command.length <= 100`
* `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order.
|
There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same?
|
Math,String
|
Medium
|
548
|
475 |
hey everyone um welcome to the channel in this video we are going to discuss about the lead code problem called heaters in this problem we are given houses array as well as heaters right so what uh basically we have to find is uh by this array heaters we know that uh at the second position right if we take this as an example in the second position is present right so we have to calculate that what is the maximum distance that should be there you know uh when from each element to any heater right that is for the radius so we can take example of this right one four is current so heaters are present at first position as well as in the second position right so what it means is if we Loop through this array we go to the first element right so the heater is present on that element only right so the distance should be zero right so it does not need any distance because that heater is present on that particular element right so if we go to 2 there is no heater present on two but heaters are presented at uh for in the first position and on the second on the fourth position right so if you consider two the heater is present at the distance of one okay uh so it is getting Satisfied by the heater present under one and the distance is one right and the heater is present on the fourth position also so it is getting satisfied with the fourth one also but it is so far you know we can take the minimum like what is the minimum between one and two by two we mean that the distance between two and four is two so we'll take one side like it is getting Satisfied by the first heater similarly three is getting Satisfied by the fourth heater so we'll take the distance as one uh will not take the distance as uh two which is uh this is the distance between the one and three because it is getting Satisfied by four which is near to three in order to three right so here if we calculate the total distance the maximum distance should be one like two is getting satisfied the one three is getting Satisfied by four so right so the distance between them are one only right so the maximum uh value of the distance is called the radius and that is called uh that is one here right so how we are going to solve this problem we have to calculate the radius the maximum value of your distance combining all the elements right for each element we have to find our distance so like if we take one uh two three four and we take 1 4 is the heater's position and that is The house's first position so for each element we are going to calculate the left distance as well as the right distance for 2 the left distance is one and the right distance is two so we are going to take uh the value 1 for the element 2. this one this distance similarly for 3 we are going to take this distance but for one as the heater is present on the first element we are going to take 0 as the distance and for 4 we are also going to take 0 as the distance because the heater is present on the four also so the maximum value is uh one right so how we are going to approach this problem we are going to approach like we'll declare this array you will have a function right in that function we will send this element to right as well as uh this array and that function will return the index uh if the element is present in this array like if the heater is present on this element or not if it is present on this element then the answer will be zero obviously but if it is not present on the supplement then you know uh it was returned uh it will not return anything so we one approach can we can do is like we can you know uh pass this to and this array in a function and we can have a linear search and we can find by that method module it will take o n for this search right but we can do uh this thing in login also because we have the binary search option right so uh so that is the thing we can do so uh with the help of binary search we are going to solve this problem uh the binary search method is called arrays.binary search arrays.binary search arrays.binary search uh all right and in this we press pass the element value which is 2 here right and we pass this array one port right so as we can see uh 2 is not present here in one and four so what does this binary search value return right so if the element is not present right if the element is not present here then it will tell us that if it was present then at which position it should have been present right so first thing we can do we should do is we actually saw this heater side because binary search works on the sorted arrays right so if 2 was present then it should it would have been present here right so the binary search value will return the value minus 2. y minus 2 because this is the first position and this is the second position right so two value and Y minus because it is not present actually what we do is to convert into the actual index we take the help of this formula which is minus index Plus 1. all right so what will happen is it will be minus 2 plus 1 and it will be 1. okay so it would have been present at position one on position one right so either it gives this if the value is not present then it gives some negative value like if it was present in at which on which position it would have been present way or it gives the value the index of the element which is if it is present like for four it will return two or one it will return one right so um so uh let's uh do the coding part I think yeah one thing I forgot to explain that for any element you have to calculate the left distance and we have to calculate the right distance right so uh what we're gonna do is uh we'll get the index here like for two for element two we are going to get the index as minus 2 will convert into one okay so we are going to convert this index to 1 right and what we have to do is if we have to calculate the left part like left part we have to calculate so if we are getting one it means that this element would have been present at this point right so this particular number and this particular number right the difference between them is the left thing left a value and the difference between 2 and 4 is the right value right so uh so the uh so what we can do is we can code and we can find out how the situation actually works right so let's move on to the code what we will do is we will be taking an eye first let's okay we will iterate through each house all right and we have to calculate that we have to calculate the right so for before that we need to find the index all right so first and then the element to be searched it will return some value right so if the index is negative by that formula we will apply so we'll calculate the left value on the right value so left value for left value we have to check for index minus 1 right so if 2 was present here between 1 and 4 right so we'll calculate the minus one index we have got the index as 1 right index or S1 so in this array 1 and 4 the index 1 is 4 but we have to find we have to calculate the left to index 1 right so not index one element one which is our index 0 so we will do is so yeah what we will do is 1 4 it was there two was we are searching for two so index we are getting as one so what we will do is uh we'll uh check for index minus 1. all right so index is 1 and index minus 1 will be this element so for F2 will calculate index minus one we have to calculate the depth one if we are calculating minus one then we have to check if uh it is greater than equal to 0 if it is not then we will uh change it to minor uh integer.max uh change it to minor uh integer.max uh change it to minor uh integer.max value right and if it is uh greater than equal to 0 then what we will do is house minus heaters I all right so this is the house element and minus heaters I use the index right so index will be uh minus one right so here it will be index minus 1. all right so similarly we'll calculate for right all right what we'll do is uh so we have to calculate the difference between two this two and just four all right so actually what we got I've indexed earlier we had gotten uh minus 2 which we converted into uh one right so what is the in value of the index one and the heater salary which is four right so here we will not check uh change any index but we will have this condition that we should be less than details dot length you know you need to maximum value right because if you know if index is comes here right if index by chance you know comes here you know one four was there if index was coming here right if suppose the element was 5 is not present the five is not present then it would have returned this index after 4 then the right value of 5 in the right value of 5 would have been Infinity like there is no heater present on the right side so we'll take it as Infinity similar is the case with uh left element we would have taken uh the value was uh you know Infinity uh if the left value was are not present in the heaters added so that is why we are taking data.max value and taking data.max value and taking data.max value and all right we'll calculators as the heaters is bigger videos right so I will calculate like this right and in the list we will give them maximum of Y maximum because we have to calculate the maximum weight here will calculate the minimum radius something wrong the answer is wrong because we have not sorted the heaters binary Source function will work right so for that first sort the heater side you know and 950 okay now it should run it's running time complexity should be you know for all the elements is taking login and there are how many elements are there and login will be the time complexity login is the binary search value right so analogy should be the time complexity so uh thank you all for watching this video and please like and share this video and also subscribe to this channel uh I'll be regularly uploading the videos related to this field so thank you for watching bye
|
Heaters
|
heaters
|
Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.
Every house can be warmed, as long as the house is within the heater's warm radius range.
Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius standard of heaters so that those heaters could cover all houses._
**Notice** that all the `heaters` follow your radius standard, and the warm radius will the same.
**Example 1:**
**Input:** houses = \[1,2,3\], heaters = \[2\]
**Output:** 1
**Explanation:** The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
**Example 2:**
**Input:** houses = \[1,2,3,4\], heaters = \[1,4\]
**Output:** 1
**Explanation:** The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
**Example 3:**
**Input:** houses = \[1,5\], heaters = \[2\]
**Output:** 3
**Constraints:**
* `1 <= houses.length, heaters.length <= 3 * 104`
* `1 <= houses[i], heaters[i] <= 109`
| null |
Array,Two Pointers,Binary Search,Sorting
|
Medium
| null |
1,970 |
Hello everyone welcome to my channel my page is available with the name liquid 1970 hard mark to hai but it is going to be very easy very simple bfs and dfs bill help you solve this question ok there is just a small catch that too we understand Lange last where you can style cross question name is this it has been asked in meta and onsite round of Google this question has been asked with D slide variation is ok what is the question you have given one ODI matrix one base meaning Key is not in zero based indexing where zero represents land and one represents water zero mains what is that there is land there one mains key there is water you are life ints row one column representing d number of roses number of columns in date Matters are fine, zero d'entre matrix land is fine, right now the country is becoming zero, so sir, whatever is the example, all the lands are 0 something like this if they give a new cell becomes flood with water every day. What happens is that a cell is filled with water, one day it is filled with water, on the second day it is filled with water, so on and we have to fill it with water, we have given a vector named cells and vector is given in the cells. What is the meaning of cells? It has come like a pen, it will be filled with water and every day one cell will be filled with water. Okay, you want to find the last date, it is possible, from top to bottom by only working. On Land Sales: What is the working. On Land Sales: What is the working. On Land Sales: What is the point of saying that if you buy Ma then you have to land here right now, okay, so you have to go from the upper row to the lower Rohtak and you can start from any cell in the upper row or from this. Either this or this and you have to reach the bottom row and you can reach any cell either here or here it is okay if the water fills then you will not be able to go from here We will have to go and so on, slowly the water is going to India, so on the first day, we take water here, India, on the second day, water here, India is still there, now you can go down, but on the third day the water is filled here, we take mother, so it means only You can go down only till the second day. Last day, it will be your second day only. By the third day, the water is filled till here. If it is okay then you will not be able to go down. Look, if you start from here, you will not be able to go down here even if you start from here. You will not be able to go, even if you start from here, you will not be able to go and now you can go in any direction from any cell, there is no problem in this, you can go in all four directions, but you can start from the top of the story, either at the top or here. Start from right, you won't be able to go down, so this last one is asking which day is the last date, yes day you can go from top to bottom, right then he is asking you that the last date of return is possible, talk to you at the bottom. Of others only working on land sales, but is n't it like this, take this example, it is a small example but it will be quite clear, look at this, you have given row, comma, row and pen are 2, meaning this is mine, you are cross, you are greater, now this is Look, there are all zeros in the beginning, that means everyone is all land, now you can go from top to bottom and this is my zero, this is mine, this is one, this is you, this is three, okay and in the cells I have given that. Look at de one, 1 will be filled with water, look at a1, 1 is filled with water, look at but c, you can still go from top to bottom, if you start from this cell, you will go down to a, okay, no problem, update, I go, date you. Who is speaking in this, you comma one will be filled with water, okay, this is one, you are one, base indexing, he is speaking, 2 common meaning, this is also filled with water, okay still now, but you can go from top to bottom, give third What happened to me, okay now you can't go up, there is no land at the top, otherwise you ca n't start from the top, that means what will be your answer, you will be, that is, there was the last date when you could go down from the top, okay So the question is very easy to understand. Now let's see how to solve it. So let's see how to solve it. The easiest way was to know in the exam that brute force is mine, what will I do? Who is telling whom on the first day? Hey forest comma is telling the forest to turn into water ok I gave the forest a cloud now what will I do with all the lenses in the first row above I would like to try from all the lands whether I can reach the bottom or not ok So I will try this and DFS or hit the buffs and it said that from any cell you can go up and down, right, you know how to write, right, so what did I do in the first day, I said, fill water in it. It was filled and I will take DFS from any one of the children who land in the first row. If I can reach the bottom then it is okay, I will survive till day one on the first day. I can go from top to bottom similarly. Then I will come here, filled the forest with water, filled it with water as well, okay again I will go to the first room, whichever land I get, I will try DFS or BFS tree at least once. Reached the bottom till the last row, so that means they If we can reach R good, then let us also survive, I came to d3, I will look above again to see if there is any such land, the land above is not available, so I ended here, it is our right, what does it mean that you every Whatever the cell is telling you in a day, you are going to the cell and trying it. Okay, and you are trying the DFS. Okay, so now it is obvious that this is a very expensive method, because you are trying every single day. I am doing a bus tomorrow for this, first this water in India, their mobile water in India, then tried DFS, then came here, then tried DFS, then here, then this first try. Okay, so this is a very costly approach, but definitely you should try this approach. Okay, so look, writing BFS or DFS is very easy, right, you will have to do that. Anyhow, no matter how much you match, VFX, BF will not be required, but what is the point? What did you do for this for every single day, India, then you are trying DFS, you take mother from this cell, if you cannot go from this cell, then if there is another cell, then you try from that. Neither is this a very expensive mountain nor is that court so you can already write but there is a point in the butt that how to optimize it, why is there a post to do tomorrow for every day? Okay, so first of all it comes in our mother's mind that Brother, in intuition, can some one think, this is the question of binary search, this is the most important question is that people ask how the intuition would have been built, okay then look, the answer is hidden in your brat force itself. Taking this example, I try to make you understand that can some one think, this can be made through binary search, so look, this is my great, this is my self, this is one, you are three, I have written four. Well, indexing is done by doing zero one, three, I will agree, okay, now see, now the route was simpler than four, I came here, in the first day, water in one, India, then DFS prime kept coming, okay, then I went here, I gave money in one. Paani Bharat means the forest was filled with water and then you came into the forest itself, Paani Bharat, India can be seen in this. Now pay attention to one thing, there is a very basic notification here, but let's take an example, okay and give three. It must have been filled with water at many places. It must have been filled with water here and there. Let's fill everything with water. One comma one is filled with water. 2 1 itself is filled with water. One comma 2 itself is filled with water. Moved to direct on d3. And I see that if I go to direct A in date three, then I am not going from top to bottom. Look here, it must be visible that you will not be able to go from top to bottom, what does it mean that definitely give one or give five or the six. It is not necessary for me, what does it mean that if the water up to level three is filled, this is filled, then I am not going from top to bottom, so there is no need to check from top to bottom. Meaning, I can discard, I will not check further, the next index is fine, that is, definitely give me any other number, that is, give me number three, I will not give you the number, I will check till you, right, you are clear here only. It must have been there, like when I checked in d3, I saw that I was not going down because more cells would be filled in, that they were reducing like a binary search, I used to come out with a mid point, if it did not satisfy me. If it was either left or right side, I would completely discard it and then saw this half here. Or if I was not able to reduce it on the left side, then I would complete it from the left and then saw it in the right half. Here is a I used to go and came here this date is the same, this binary search is fine and I have also asked a similar question which is a very easy version of this question, I have given a link to it for you to see in the description, it is also a similar question. Okay, that too in that too, I had created it from Brat Four, then I understood that search can be done there also. Okay, so it has become simple, so our question is very clear. Now see, how will we solve Binani surface, so see, here I am. I will agree with R here, I will agree with it is okay, what I mean is that first fill the water from zero to mid, okay, so which one is this one comma one in the zero index, but this one comma is this one based indexing. But manage, whatever row comma I am making tomorrow, I will make it great, whatever I make, I will keep it in zero based indexing. Okay, so it is saying in this, what will happen to it, actually, it is saying because it is speaking with one based indexing, right, I am here. But I have made a grate in Zero, it is okay, this one is just like this, no, there was a simple thing in it, so okay, I fill water in 0, here I have filled water, okay where else will I have to fill water in Zero too. Diya is ok, I have filled the water up to the med, that is, I am checking till date tu, in the direct, the water has been filled up to d2, so I am checking whether I can go from top to bottom or not, it is ok. First of all, what I did was take out the mid and fill all the water from zero to lake mid. Now I just have to check all the lands in the first row. I will try once from each land and hit BFS either. DFS and I will see whether I have reached the last row or not. Okay, if I can reach then my answer will be A. So look here, I have reached the last row, I will hit DFS from here, I will go from here to here, if I reach the last row then I will say that yes, I am in reach, what does it mean that my answer is the last one, okay, mine is the last one, whatever answer I have given, I can say it, no, whatever value of the middle is one, that is, which is the number. Hai di number tu hai to med plus one I have solved that yes di number you can be my answer but look at the style here I have been approaching from top to bottom what does it mean I can explore the right side and the left side I ignore because if I am able to reach de tu, then obviously I will be able to reach de one de zero. From top to bottom, I will take L = mid able to reach de one de zero. From top to bottom, I will take L = mid able to reach de one de zero. From top to bottom, I will take L = mid plus one, L is here, A is here and R is mine here. So it is already ok, took out the med again, ok took it out again and from now on this will be my refresh again, 2 + 3 - 2 / 2 A will go, so this time my mid 2 + 3 - 2 / 2 A will go, so this time my mid 2 + 3 - 2 / 2 A will go, so this time my mid is here, look, this is important here, understand that this time What I am saying is that from zero till I mean in which direct kiss I have reached number three, then brother, I am saying that from zero till here the entire water has been filled, so I will fill it first. What is the meaning of one, fill the zero one with water, fill it with water, what is it after that, 2 1, meaning, fill water with one comma, zero, fill it with water, what is it after that, one comma, you are, what is the meaning of water with zero comma 1? Fill it ok, let's fill it, now after this I have to check whether I can find any such land in the first row from where I can do DFS. So, I have found that there is no land in the first room to do DFS. Okay, what does this mean? What does it mean that I cannot reach from top to bottom, then if I give a number in this index, if I am not able to reach from top to bottom, then there is no use of life in future, then it will be filled with water. Right, what does it mean that I should go to the left side, okay, so what will I do, I will make R minus one, and here A will go, okay, you answer will be stored, that will be my answer, right, this is very basic, you and also If you iron the tree in a larger example, it will become clearer. If you have seen, its story point is going to be very simple. L = 0 and it has to be made out to L = 0 and it has to be made out to L = 0 and it has to be made out to make a size-1 simple binary set of equal tu size-1 cells, make a size-1 simple binary set of equal tu size-1 cells, make a size-1 simple binary set of equal tu size-1 cells, okay. And what did you say in the middle, from zero till Madhya Pradesh, whatever is given in the cells, the value of all the cells has to be reduced to one, that means I will fill water in all, okay after filling the water, now I have to check either it is BF or not. By hitting BFS and where else to check, your guess will be that I am going from top to bottom row, which means it can be my answer, not made, it will be made plus one because it is zero based indexing, that is me plus one, my answer. Maybe but even bigger answer if I want to find the last one then I will try eligible tu meddplus one by going to the right side and if it is not so then R = M - 1 ok R = M - 1 ok R = M - 1 ok and BFS is either BF we will code both BFS And DFS will do both, now just one small minor thing is left to tell, after that we can code, so look, this is a very small thing, but I notice the story is not discussed, that is why we are trying to highlight this point, see what I am doing here. I am saying that because of my mother, I just took out some water and filled it with water in all the shelves from zero to lake mid. Okay, so where is that water, this is India, so that water here is India, here is forest is everywhere. Have filled water there, ok will try and from where will you try, you can try from any cell, it is plus, if this is true, it means I can go from top to bottom, then I will start the return from here itself and if so Not done, its name is great, if we take mother, then start here, let us take mother, I was here, okay, where can I go with this, up, down, here, I can't go here, not here, I can only go here. So okay, I am going but science, I should not go back to this place from here, I will have to mark that also as a visit, I will have to mark this as one, okay, now I have come here, I cannot go to the story, I will mark it from here, okay. I am going to give it a visit, now I can't continue the story from here, right, obviously our answer will be water, so it means that this zero pen did not work, in the first pen, my value is one, so I can't try even this and now I went to the second pen when I tried it. Okay, there will be DFS again tomorrow, so do I need to zero these people again because they are doing DFS in Great again tomorrow, it was zero, remember from back then? It is necessary to make it zero, no, it is not necessary, it is okay, if you do it, you will become the most valuable because it is not necessary for you, because look, if you take the mother, you make it zero and then make it back to zero, then it will be even if you want to reach. So last time too, if you don't go down from here, then now if you come here again in the future, how will you go down? If last time you don't go down from this cell, then in the future too, if you take the mother in this cell, then how will you go down? You will be able to go, it's an obvious thing, okay, if you make it back to 1, then it will be fine, or else you gave it a band back to zero, from here we did DFS yesterday, so let it be one, then it will be fine, there is no problem, okay now. There is only one here, so nothing will happen. Right now, we are trying. Okay, we are trying with this pen. We will hit DFS again. It is zero through the pen. Who are you? Where can we go from here? We can only go down. Marked as visited, from here also you can only go down. Marked it as visited. From here, you can only go down. Ok, it is cleared till here, so see if we go, the answer will be true, I will return true, you will return to binary search. I will do it, okay, so this thing was very important that you make it a special made value again, if whenever you are trying for all the pen, then urine how you, whatever bf inside it, if you mark a visit from yourself, then not that again, definitely not. Okay, then the medical will get a new value, then it is okay, then it is an obvious thing, then a new fresh will be created, it will be zero, then the value till that point will be increased to 11 and so on, okay, it was a small point but very important. Now I think you have solved your problem. Okay, so now the story point is clear to you. Okay, now let's code quickly and finish it. So let's quickly finish the code exactly as per the story point. We will proceed according to that, first of all, here we define an intro and these pens, we make it equal every day, you took it yesterday, okay , we will be able to cross if we take this made value. So if you send sales and are able to do so, then I store it in the answer in the last page. Meddplus will be one but you will go to the right side and check it. If you move to the left side only then R = Madam, let's start sales tomorrow. This is the ex-coordinator. In A = ok but science -1 will have to be done because what it is ok but science -1 will have to be done because what it is ok but science -1 will have to be done because what it is saying is by doing one based indexing we are ok, now in the grate I will fill water in this Till what did I say that out of all the pens in the first row, we will do a BFS tree, if it is equal then zero is ok then you will have to send great, if true is gone from here then you will return here only, this return is you. Who will it go to? Will it go to the research center this time? And if it is not so then it will keep checking further. Okay, rest is the last row, then I will return true that I can reach last. Okay, and if I can't reach. Okay, now you remember all the four directions, how to do it, we used to define these direction vectors for life in road direction, we have done this many times. Okay, now you must have also remembered this right one, comma, zero and what was zero. Mines In direction great, new underscore came and new, go ahead and from there, if a is true then we will return true. If there is no return 2 on the story, then we will return true here. Ok, I have used simple binary search, that's all. After that I have written DFS BFS and after submitting, let's see this Farable Tu Pass which is the latest and we have also got this math bass, Congratulations, you are everyone of you and its time complexity is very easy. Look here, people of N are singing. What is N is the size of the cell and for each see we are doing a DFS and BFS tomorrow and what you will do in DFS and BFS is burst how will you visit each cell then that off mx will go there m crossing otherwise rock Row stress will be done tomorrow, okay, so it is simple, time compressor, but here I solved it with DFS, you can simply solve it with BF also, okay, I will solve it with BF here and show you this same function. Convert it to BF and remove it completely from here. The current coordinator which you have got is right i comma aam ke got it is ok and science you have to mark it as electrical ok if my which is Should write it must be great note be equal you one either write that it must be the land right him how to do what to do put the leisure life here and mark it as visit great of new underscore brother do one to do Diya ok
|
Last Day Where You Can Still Cross
|
sorting-the-sentence
|
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**.
|
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
|
String,Sorting
|
Easy
|
2168
|
1,169 |
Hey guys, welcome back to the lead code series, this is Manish Sharif, today we are going to do question number 1169 and our question is invalid transactions, it is a very complicated question, it is a medium level problem, it was fun to do this question because here in oops. You will get to see many concepts together in this question, Hajj I will try to solve it by making different methods from your list. Okay, so first of all let us understand the problem, what has been given to us and what we have to do. Okay, so look at the input that has been given to us, it has been given to us in this way, it has been given in the form of a string, we have been given a list of input strings, okay here multiple strings have been given to us, now how is this input? What is the input? Once we understand this, inside this input we have been given multiple fields, which is the first field here, we will call it name like, name is day, first field is day, second field is day, third is time. The first one is converting the price into days, the fourth one is converting the amount into days and we will call the fourth one as City, so according to this, we will get a string in the parameter which will be named as 'Time Amount' and 'City' will be as 'Method'. Let's be named as 'Time Amount' and 'City' will be as 'Method'. Let's be named as 'Time Amount' and 'City' will be as 'Method'. Let's see the conditions inside this, what conditions have been given so that we can solve it. Okay, so inside this we have to print the invalid transaction, so what is this to say that the transaction is potentially invalid, that is, when will the transaction become invalid? IF AMOUNT EXCEEDS THOUSAND DOLLARS If the amount crosses ₹ 1000 amount crosses ₹ 1000 amount crosses ₹ 1000 then it is invalid. First of all, here 800 is given in the first string and 100 in the next one, so we have to notice this condition. It is ok with you, invalid as soon as thousand dollars is crossed, we can write IF condition for this, it is ok, what is your next condition including 60 minutes, that is, if the transaction is happening within 60 minutes, then it is also invalid, two conditions are correct, actual. The time that I have given is within seconds parameter, it is within minutes, okay, we have already cleared it and we are running if it is within 60 seconds, then brother, you will be invalid here and what is your next condition if that? It is the name of the city. Look, it is the name of the city. Even if the name of the city is different, it will be invalid. These two conditions are without. If the time is less than 60 and what they say, if the city is different then this is going to happen. Okay, we have seen the conditions. What are the questions for this? Now let's see what we have next. What will be our approach? To solve this, first of all we know that we have given a string, we have to apply some operations on it and what we have to do. We have to print all the invalid transactions and return them, so what will be my first step? First of all, I will split the string given to me, name, time, the objects that we saw, like just now in its base. We will create an object, we will call it transaction, okay and inside it we will store all the values, name is done, time is done, city is done and amount is done, this is how our first step is going to be, what will be the next step, we will have to do a valid check separately. We have seen that we have many conditions like 16 minutes, we have a city condition and also we have a condition related to amount. There are three conditions, we will write a separate method for them, it will be a little easier for us. Okay, so we are going to do only this and what will be the last step, we will create a map and what will be inside the map, whatever is ours, like the object that we have created, the transaction, we will put it inside the map and then the map. After coming inside, we will get it validated whether it is valid or not and from there we will return our answer, so this is how we are going to approach, now what we need for this is that once they see it, first of all So brother, what do I need? To question, first of all, look, you need a new list because you need to print the list, we need a map, we need to create an object of transaction and along with that we need a valid method, we need all these things basically. What have to be done? One of ours will be a function, one will create our object, so we are going to create like where we will split because we have given the string, what will we do in the string and next what is ours, a valid method is going to be a valid method which will be He will check what it does for himself and whether he is invalid, okay and let's try to see there how to pay intelligence, why because there is going to be a little big code, it will be easy to pay there, so we will try it there, then quickly. From this we go to our intelligence and try there how what is going to happen, so here I have created basic three classes, I have created a class, I have created a transaction which we will call object, okay and this is my method like here in my There will be logic and this is our validator where we will write the code of validation, then we have three conditions, after this we check what we have to do so that we can start our operation. What is the first thing that we have talked about. First we will create our object, that is, we will create our object of transaction, let us quickly see which fields are required for this, first of all I need a string name, I need a name, next, what do I need? What do you need? Do you also need a string city? Do you need a city? And apart from the city, what else do you need? Apart from the city, you need time and let's keep time in less pieces. It will be a little easy for you, so here we are. Let's keep time for this, now we need to enter the amount, now what do we need, the amount is also required, there was tax field only, I thought, yes, our should be reduced from the tax field, now we create a constructor for this, quickly create a public transaction and this What is this string in the input? Brother, we are denoting it like this and now what will we do inside it, we can split it, what will I have, string off, I have it, okay, string off, I will tell it, I will say something. Plate say I am late and ok Plate now what am I going to do here which is my S which has my head data inside it, from there we will apply split operation in it Apna Koi Mila Now what will be my name, the name will be Apna split off vote off Vote zero, the first variable is our name, we know what is the next variable after name, if it is time, then time will become ours Even with the amount, we will have to do the same. Come on, we are getting this benefit of intelligence here. We will do it with pe tu because the second which is ours is fine and the last which is ours is our city, so we also update the city, split of what is three right, so in this way we have created our object, this which is ours. The object of the transaction has been created and whenever it comes, it will update the value here and will return it to itself. We close it for now so that it becomes a little easier for us to understand the code and what to do. What not to do, that's it, now as much code as we have, what will we do there, we talked earlier that we have to make it, right, we have to make it, so first of all, what we need is to return. First of all we need that list, we will return the list of what we need string, we have to print only the list of strings and which one we want to print is invalid, so we keep its name also invalid and this is what we do here. Let's take a new list, okay according to me, it is okay, now we had talked that we have to make a map also, so let's quickly make the map. Now what is going to be inside the map, first of all we will keep the string, okay first of all. First we will keep the type, next what will happen is the transactions, which we have done now, the object is ok, our map is created, whatever has to be done here, we will do it later sir, first we have our validation, we will see it quickly, after the validation is done, we will do our joe. The code is there but we will reduce it. Was the condition good or not, do you have some conditions? Tell me, look at my transaction, which is your current transaction, what will be the list, which will be taken from the map, which list is coming or not, we will pass it inside the map, there will be a complete list. There will be all the details here, there will be one detail here, so what do I do here, now before I talk about the amount, T dot amount, if my amount brother is more than thousand dollars, it is more than thousand dollars, then what are you doing, I will look at something. Don't know, please return what water transaction is invalid, tell me your type, it is ok to remember this and if it is not so, now we will do the same for 4G, we will do the same transaction for porridge and let's keep some name for it, let's keep it. Let's take T but we already have it, right? T R A N S. Let's keep this on transactions. Think okay, mango is not available here, ok, now it's okay, introduce yourself, we place the operation on the list which we have created our transaction, that is, the current on which we are in the transaction, from there I have to pick up the time and Out of this, we will mine whatever we are getting from outside, right, that time, we will mine it, what will we do, we will mine it, and if it is our own, or is it equal, from which 66, you are equal. Why did we take it because there we were including 60 rupees and we are doing the same because there were two conditions, one cannot be taken, what will be the second condition, trans dot city, we will talk about the city, now if we have any city, we will get equal check. Now what we have to do is whether it is city or not then dot equal what OK equal function, we will make it equal of what t dot city, if he had said that if city is not equal then we will have to put this sign or we are saying brother. Even if it is not there, what will happen to us, our transaction has become invalid, what will we do to return it, we will simply return the water and if our code is out of all these conditions and there is no match in any code, then we will We can return true because then there is no condition left in which we return true. If the reason is true then the code of our invalid condition has been completed. We band this method. We have completed the transaction. Now our saving is only in the logic. There is saving which is our own method, only that is left, inside that one also we have made our map, after the map we have made the list, now what we have to do is just put the data, first of all what we have to do is We have created a map, we have to put data inside the map, what can we do for that, we can make it 4 inches but what will we keep inside the rich, first of all, our string of what transactions is ok, the spelling may be a little wrong. There is power but there is no problem, see the transactions have become similar here, we do such transactions so that it does not happen, that is fine, the battery is also going to run out, no one, let's solve the question quickly, we are here in the group. What we will do is map, inside our map we will check whether our object is already present. If it is present then it does not matter to us. Like, we will just update it and if not then we will update it along with its name. We will do this, there is a function for this, what is called absent, okay, if it is named as absent, then update it and if it is, then leave it, okay, we will reduce things in this way, so what is our object here? What is our object here? It is invalid but before updating, we will have to create a temporary object inside which we have the details of the transactions. Let's call it T. Here is the new transaction. What will we pass in this string? Whatever is the current transaction, we will pass it. Okay, now we are checking T Dot Name by name. If this is the name, then what will I say, pass the new list, we have passed the earlist now, we have passed the earlist. What will we do after this, we will gate this, okay, we will gate this, whatever name it is, we will gate it like this and inside this, we will add multiples of one name to ourselves. Transactions can happen, we have seen in the example, so that's why we are doing this, so we are not updating in a single big and that is why we have created an empty here, so here in this 4 inch loop, we have not updated the map. Done, here only this much is less, now here we will make another four loop and check that it has its valid condition inside the loop on the second one, how will we do that, so one more I will write 4, let it be 4 inches and what is its own variable? Brother, first string will be transaction and where will it be based on the transactions that we are getting the list of, so what will we do in this, like let's create an object, first take the T of our transaction. Now brother, tell me whether I have to pass the string, what will I pass, the transaction, I have got the object, now what we have to do here, we have to check whether it is valid or not because this is where we are now in our list. If we update it, then this is valid, we have created a function, remember this is valid, yes, remember, now this is valid, what do we take first, transition type P is late, so here we have T, na se name's own pass P. Next thing we will pass is the list of votes, that is, we are the invalids, the map that we have created above, we can pass it is direct, otherwise we will not pass it directly, what if it gets a different name? We will do it with our map, we have to print the list, map dot, we will do it with this method, we have to help whom, with the help of name, if it is there, then it is fine and if it is not there, then we will say only that, no, whatever is there. Just return it's a simple thing, isn't it, and this is the reason for doing it in intelligence. It's a little big code, so it will be easy to write, you should also try there and if it is not the band of your IF condition, then put it inside it. What benefit will we get by writing something? If this is the condition, then we will add the invalid transactions that we have created. The transaction which is the current transaction is fine. We will update the one on which we are here. But I have to update the transaction and not the object, so I could have done it. Okay, this is less and if this condition is failing, then what will we make a return? What will we make a return, we will make a return invalid, we will make an invalid return. Now what is invalid? Okay, here a bracket is showing extra. Okay, one second, let's remove it from here. Look at your condition where it is closing, a condition is closing here and the loop is closing here. So outside the four look, we will make return because ultimately we have to return the entire function. We have to make some return on some portal. Now this condition is required, we have to look for the invalid, how will he give us the valid one? If you want Nariya, then some of your code is going to be in this method. Now I have banded this method also. I will quickly copy these three once and run them once. We will see in our lead code and after that we can understand. Here I have copied the code and removed the static function, I like joystick, we can do it, we need intelligence, run it once and see what is coming, do we have any error, ok so it is accepted, run once. Let's see how much time it took to solve this question. It took 43 hours of time and space. Now after this we can discuss here like what is its time complexity and what is its space complexity. Let's see what is once, after that we will try this. Okay, so what, we have our first method, right, once the call is being made, then like will be ours there because here we have taken three variables here. So this space will remain constant. What is the method for this one? We made a list. We have made a list of big open relief time complexity. It will also be inside the map. Now we are calling the object, so there will be big of n. Okay and Anyway, look here is also doing it, so anyway, now the bottom one is the loop, there is this valid function, there is a loop inside it, there is a loop outside also, so from here it will be your n², so you have time. Complexity will be done and square is fine and now space complexity, you tell me in the comments what is the base complexity and how much is it, this is your question in this question, this is Manish thank you very much, see you in the next video.
|
Invalid Transactions
|
largest-values-from-labels
|
A transaction is possibly invalid if:
* the amount exceeds `$1000`, or;
* if it occurs within (and including) `60` minutes of another transaction with the **same name** in a **different city**.
You are given an array of strings `transaction` where `transactions[i]` consists of comma-separated values representing the name, time (in minutes), amount, and city of the transaction.
Return a list of `transactions` that are possibly invalid. You may return the answer in **any order**.
**Example 1:**
**Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,100,beijing "\]
**Output:** \[ "alice,20,800,mtv ", "alice,50,100,beijing "\]
**Explanation:** The first transaction is invalid because the second transaction occurs within a difference of 60 minutes, have the same name and is in a different city. Similarly the second one is invalid too.
**Example 2:**
**Input:** transactions = \[ "alice,20,800,mtv ", "alice,50,1200,mtv "\]
**Output:** \[ "alice,50,1200,mtv "\]
**Example 3:**
**Input:** transactions = \[ "alice,20,800,mtv ", "bob,50,1200,mtv "\]
**Output:** \[ "bob,50,1200,mtv "\]
**Constraints:**
* `transactions.length <= 1000`
* Each `transactions[i]` takes the form `"{name},{time},{amount},{city} "`
* Each `{name}` and `{city}` consist of lowercase English letters, and have lengths between `1` and `10`.
* Each `{time}` consist of digits, and represent an integer between `0` and `1000`.
* Each `{amount}` consist of digits, and represent an integer between `0` and `2000`.
|
Consider the items in order from largest to smallest value, and greedily take the items if they fall under the use_limit. We can keep track of how many items of each label are used by using a hash table.
|
Array,Hash Table,Greedy,Sorting,Counting
|
Medium
| null |
121 |
hey everyone welcome back to take you forward so we completed one ddp dp on grids dp on subsequences and dp on strings so it's sty it's so it's time to start dp on stocks yes and there are generically uh six problem stocks uh is that the spelling yeah that's suspending so we have six problems and in any of the interviews if you go across by doing these six problems dp on stocks gets covered and i'll be doing all these six problems like sequentially it's very important that you follow every problem like make sure you don't directly jump to the fourth problem make sure you watch all the videos on that given sequence because i'll be building the intuition problem by problem and yes in dpo stocks it's very important to understand the space optimization in an interview you cannot skip this portion you cannot skip the space optimization portion because in an interview in dp on stocks people tend to expect you to answer the space optimization technique so it's very important you don't skip it so yeah without wasting any time let's actually start with the first problem so the first problem is best time to buy and sell stock what does the problem state you will be given an array and it states if you sell or buy a stock on any given day this is the first day this is the second day third day fourth day fifth day sixth day the price of that stock is seven rupees on the first day the price is one on the second day the price is five on the third day the price is uh three on the fourth day the price is sixth on the fifth and so on now it states you that you have n number of days yes over here you have six days you have to decide a day when you buy the stock and you have to decide a day when you sell of the stock assume i decide that i'm going to buy the stock on this day so buying that well cost me one rupee and i'm asking you when will you sell it so you will be selling it on this day which is costing you six so if i ask you invested one in buying it and now you're selling it at six what is the profit that you make is five so the question states you have to maximize the profit remember in order to sell a stock you have to buy it so the buying has to be done before the selling you can't be like okay i'll sell it on this day i'll buy it on this day seven minus one no it doesn't work this way first you have to buy it like you bought it on here and then you decided to sell it over here you could have done other ways like buy it on this day sell it on this day this could have given you the profit of four and you are only allowed to do this transaction like buy and selling can only be done once so that is the problem given the stock prices on n number of days you decide when do you buy it and then you decide when do you sell it and just make sure the difference of these guys the profit has to be maximum is what you need to do it i hope that makes sense so how do you approach this problem now in order to approach this problem just assume i'm asking you if you're selling the stock on this day selling it on this day when will you try to buy it you will definitely try to buy it on the day which is the minimum price like do you agree or not it won't make sense if you uh buy it on this day because then you will have loss if you are selling it over here on the left you will try to buy it on the day which is minimal which is this similarly if you are selling it on this you will try to buy it on a day when it has a minimum always remember if you are selling on ayat day you buy on the minimum price from the first day to the i minus one day agreed if you are selling it over here whichever is the minimum you buy it on that so can i say i will drive for every day i'll be like okay i definitely cannot buy and sell on the same day because the profit will be zero that won't make any sense because i want to make profit i don't want to make losses right so i'll definitely start from here for this guy who's the minimal is seven the profit will be negative so not considered for this guy who's the minimal one so the profit will be five minus one four so you got a profit of four for this guy who's the minimum one the profit will be three minus one two for this guy who's the minimal one the profit will be six minus one five perfect for this guy who's the minimal one so the profit will be four minus one three so for every day for every price you saw what profit you can make and you got for this six if you sell it on six the profit you will make five and that is the maximum so i can support every guy if i can keep a track of the minimal on the left my job will be done so why don't you do that it's very simple and straightforward i'm like okay fine i know one thing for sure the minimum as of now the first guy is the minimum and i know the profit that i can make zero like i will not i'm not interested in making negative profit if i'm making negative profit i will not buy and sell or i'll buy it on the same day i'll sell it on the same day so profit will be 0 so profit is 0 now can i say for i equal to 1 i lesser than n i plus whenever you are at i equal to 1 which is this guy this is the minimal this is the minimum so can i say the cost that you will the cost that it will cost you is if you like if you are selling it on this price and you bought it on the minimal price this is the cost and can i say the profit you need to maximize it so can i say it will be of this cost on the previous one right now in the next step when i goes to two which means you will go to here which means you'll go to here which is the second index this will be the minimum can i say before moving to the next guy before doing an i plus i just need to make sure the mini is updated by the share price on this day so that on the next iteration i keep a track of the minimum so while moving i'm keeping a track of all the minimals of a of i so that for the next of a of i for the next a of i will be having the minimal and i can easily find the costing and throughout whichever is the maximal profit is going to be my answer so i've written the exact same code which i wrote on the ipad let's see if it is running fine yeah it is running fine it's going to submit this off to see if this gives us the correct answer it does give us the correct answer time complexity guys uh you can start the loop from one so the time complexity is we go of n space of equal of one so why dynamic programming because what is dynamic programming remembering the past here remembering the minimum throughout so that's why this comes under dynamic programming tag as well but yeah like this is definitely constructive algorithm so guys i hope you have understood the first problem on dp on stocks just in case you did please make sure you like this video and if you're new to the channel please do consider subscribing to us and yeah to continue our tradition make sure you write it right understood in the comment section and with this we will be wrapping up this video let's meet in the next one where we will be doing the second problem on dp on stocks till then bye take care
|
Best Time to Buy and Sell Stock
|
best-time-to-buy-and-sell-stock
|
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock.
Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`.
**Example 1:**
**Input:** prices = \[7,1,5,3,6,4\]
**Output:** 5
**Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
**Example 2:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** In this case, no transactions are done and the max profit = 0.
**Constraints:**
* `1 <= prices.length <= 105`
* `0 <= prices[i] <= 104`
| null |
Array,Dynamic Programming
|
Easy
|
53,122,123,188,309,2138,2144
|
1,834 |
hey everyone welcome back and let's write some more neat code today so today let's solve single threaded cpu this problem actually just came out today and it's a pretty good one i just solved it so we are given n tasks labeled from zero to n minus one and each one of these tasks has two fields or two values one is the enqueue time so this is the time that the task will be added to our queue and the second value is the processing time so that's the amount of time that this task is going to take to be completed this basically tells us that we are going to have some kind of cue structure let's continue reading this problem to understand a little bit more about this cue that we're going to be needing so we have a single threaded cpu meaning it can only process a single task at any given time and so this is the information of how it's going to decide which tasks to process in which order so if there are no available tasks to process the cpu is going to remain idle basically that tells us if our queue over here is empty meaning there's no tasks that are lined up to be processed then our cpu isn't going to do anything makes sense so far so second thing if the cpu is idle and there are available tasks we are always going to choose the tasks with the shortest processing time that means if there were two tasks in our queue let's say one task was one and the other task was two remember that the second value tells us the processing time so in this case which one of these two tasks are we gonna pick we're gonna pick the first one because it has a smaller processing time so this basically hints to us that this q that we're using it should be a priority queue or it should be a min heap because we're always going to be picking the task with the smallest processing time that makes sense that we would want to have a min heap to choose that smallest processing amount task and next once a task is started the cpu will process the entire task without stopping so let's say it's time equals one right and let's say the task takes three units of time that means the task is gonna finish when we are at time equals four units or whatever let's just call it seconds so that's pretty intuitive right that makes sense it's a single threaded cpu it can only stop once the entire task is finished and also the cpu can finish a task and start a new one instantly that also makes sense and look the only thing we want to do is return the order in which the cpu will process the task and when they say the order they mean the original index of the task so take a look at this example over here we're given four tasks right the first task one means that's the time that it's going to be added to our queue over here two means that's how long it's going to take for the task to finish processing so your question might be what time do we start at well we could say we start at time equals zero or we could say we start at the smallest time that's present inside of our task list which in this case is gonna be one so okay it's time equals one what does that mean for us that means we can add any of these tasks that have a s have a queue time of one or less and then add them to our queue our priority queue or our min heap whatever you want to call it so since we're going to be adding tasks to our cube based on the smallest in queue time doesn't it make sense for us to have this task list and then sort it by the first value of each of these pairs because remember the first value is the enqueue time they tell us that up here right the enqueue time is the first value the second value is the processing time so the good thing for us that this is already in sorted order but if it weren't we would want to sort it based on the first value of each of these pairs take a look at this first one we can cross this out and add it to our cue one two so 1 means that it was added at time 1 2 is the amount of time it'll take for it to process so remember we're always taking the shortest processing time from our queue there's only one value in our queue right now so let's cross it out and then let's say we're processing one two right we're processing this right now as you can see it's gonna take two units of time for it to process therefore we're gonna finish when the time is updated and time is now set to three right we added two units of time we updated this to three but don't forget remember what we wanted to return was the order in which the cpu tasks will be processed what do they mean by the order well they mean the original index of each of the tasks so remember this task was index zero so to the result let's put the result down here i'm gonna add zero to the result but the question might be to you how are we gonna remember the original index of each of these pairs well what we're actually going to do in the code is to each of these we're going to add the original index so this value would actually have another value added to it as 0 so this would actually be three values together one two and zero is telling us the original index of this pair now so far we've gotten one task completed now take a look our time is at three right so let's look at our task list take a look at this task 2 4 since this task is added at time 2 and right now we're at time 3 we can cross this out and add it to our queue so we're going to add 2 4 to our cue we're also going to add one more value to it a 1 is telling us the original index of it right so this is 2 4 1 that's what's going to be added to our heap you we can see that there's actually one more value we can add to our heap three two the reason we can add this is our time is three remember the enqueue time of this task is three therefore the condition is met to add this to our queue we'll add three two to our q will also add another value to it too the two tells us the original index of this value so now you can see that there's two values in our queue which remember how are we going to decide which one of these two values to pop from our queue first remember that we are using the time it takes to decide what to pop first so in reality we actually don't need to add this first value to the q right we only need this pair of values the first value tells us the amount of time this task is going to take to process the second value in the pair tells us the original index of that value so these are the values that we actually need now which one are we going to pop first obviously this bottom one right because it takes less time to process the first value is a 2 meaning that it takes 2 units of time to process this task so let's take it out now so we just popped that 2 from our q so two is the original index of it so two is the value we're going to add to our result and remember this task took two units of time to complete therefore we're gonna cross this three out add two to it so now the time that we're at currently is five so now we're at unit five so let's check if there are any more uh tasks that we can add to our min heap there's only one task left and this task is for one that means this task starts or can be added to our queue at time four right now we're at time five therefore this task can be added to our queue four one right so we're kind of running out of space let me just add a little chunk of space so four 1 is being added to our stack i'm going to add one more value to it 3 because 3 is the original index of this value so that's what we're adding and we don't actually need the 4 that's basically unnecessary so the two values that we have are one three it's a little bit messy sorry about that but hopefully you can see it one three the one value tells us that this task takes one unit of time to complete the three tells us that the index of this value was originally three okay so it's a little bit messy sorry about that so we have two values left this four one and this one three which one of these are we gonna pop well which one takes less time to complete the one three of course so let's cross that out pop it from our stack we popped one three the original index of that value was three so that's what we're gonna be adding to our resulting list so we add that three to our list one means that the unit of time this task took to complete was one so we can increment our time by one so we can change it from five now to six i'm just going to write over it right now so it's now six so there's no more tasks you can see our input list is now empty we went through every task so now our queue though has one value left you can see so that makes it easy to decide what to pop from it we pop the four one and remember we only really care about that second value because it's the index so we can take that index which is 1 and add it to our resulting output list so take a look at our output list it's 0 2 3 1. that tells us the order in which the tasks are going to be completed take a look at the example output 0 2 3 1 that's exactly what we wanted that's exactly what we needed so i hope that this kind of gives you a general idea of how we're going to solve this problem we're going to be using a min heap and the exact algorithm or the exact code i'm going to show you right now let's take a look hopefully it'll make more sense okay so the first thing diving into the code that we're going to do is we remember we're going to be taking this task list so tasks dot sort we're going to be sorting this task list right and what's the key that we're going to use to sort it well we're going to use a function a lambda function so we're going to take every single task t how are we going to decide what to sort it by well remember we're going to be sorting it by the enqueue time right so that's going to be the first or the 0th value of that task that's how we're going to be sorting it right so since we're sorting these values we're changing the order of the values which is obvious right but we do want to preserve the original index so how am i going to do that well before we sort it i'm going to go through every task in the task list in python i'm doing a little bit of a trick where we can get the index as well as the task that's what enumerate is doing but i'm taking every single task t and all i'm doing is adding one more value to it the value i'm adding is the index of that of the value i'm taking the index of every single task and adding it to that task so that we can preserve the original ordering in case that we want the original index which we do but so after we add the original indices then we're allowed to change the order because then we can remember the original index let's also declare a couple arrays one resulting so we can return the result of the tasks second the min heap right we do need a heap or a q for this problem it's going to be a minimum heap and a couple more variables i is going to tell us the current task that we have added to our queue time is going to tell us the current time that it is right now so i can initially be zero time can initially be set to the first task or rather basically the task with the smallest in queue time so that's what i'm doing by taking task of zero i'm taking the first task in sorted order with the smallest in queue time and now we're basically just going to keep looping while our minimum heap is not empty or there are still some tasks left to go through that task list if there are still some tasks left in our task list that we have not yet added to our minimum heap then we're going to be adding those tasks right from the minimum heap but we're only going to be adding the tasks that at position i you can see the task if it's in queue time has already been passed right so basically what i'm saying is if the current time is greater than or equal to this tasks in queue time then we can take this task right task at position i we're going to take that task and add it to our min heap so in python we can do that like this heap cue dot heap push to our min heap we're pushing this th this task but remember we only care about two values of this task we care about the tasks uh processing time which is at index one we also care about the tasks index which is at index two so these are the only values that we need to take and actually add to our minimum heap so for any particular task we're only adding the processing time and the index the original index of that task and obviously every time we add a task we want to increment that index i so that we can move on to the next task now there's a couple cases where we do have to handle so one is if the min heap is empty and the other is if the men heap is non-empty if the men heap is non-empty if the men heap is non-empty if the if it's non-empty this is basically the if it's non-empty this is basically the if it's non-empty this is basically the simple case we can take our min heap and pop from it right we're gonna be popping obviously that smallest the task with the smallest processing time and that's going to happen naturally in python so as we pop from this min heap we're going to be getting two values one is going to be the processing time and the second is going to be the index just like those are the two only two values that we ended up adding to our min heap so it makes sense that's what we're going to get so with the processing time what we're going to do is increment our time our global time basically telling us how much time has elapsed since we finished this ta or started this task and then finished it and we're also going to be taking the index and adding that to the result right because since we're finishing this task we can add it to the result and we're basically tracking the order in which we're completing these tasks and so that's the simple case right the else case if the min heap is non-empty obviously if the min heap is non-empty obviously if the min heap is non-empty obviously then we can pop from it now if the heap is empty what are we going to do if the heap is empty what does that tell us that tells us that there's no uh tasks that we're waiting to do that means our cpu is sitting idle so we're not doing anything so then what are we doing well we're waiting for time to pass how much time do we need to pass well let's just look at the next uh task in our task list so tasks at position i and let's get the starting time of it or rather the time that it's going to be enqueued added to our queue this is the time so we have it right here so what should we do with this we can advance time right we don't need to increment time by one we can set time to a this exact value because we're basically skipping we're basically fast forwarding right let's say the time was equal to two but the next task the enqueue time was equal to seven we're not just going to wait right we're not gonna set time equal to two three four five six and then all the way to seven no we can skip that and just fast forward it to in queue seven right that's what we're doing with this one line of code this is the entire algorithm once we're done with this we can return the result that we just got done building and we know once this loop is done executing that means we went through every single task added to our queue or our min heap and then we popped every single task from our min heap added the index of that task to our result and then finally we're returning that result so this is definitely a tricky problem we got some moving parts going on but the main focus of this problem is the min heap and the fast forwarding of time this is pretty necessary for this problem unless you want to waste a lot of time by just incrementing time by one and that probably would not be an efficient solution so i hope that this explanation was helpful and i hope the code is also helpful if you enjoyed please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon
|
Single-Threaded CPU
|
minimum-number-of-people-to-teach
|
You are given `n` tasks labeled from `0` to `n - 1` represented by a 2D integer array `tasks`, where `tasks[i] = [enqueueTimei, processingTimei]` means that the `ith` task will be available to process at `enqueueTimei` and will take `processingTimei` to finish processing.
You have a single-threaded CPU that can process **at most one** task at a time and will act in the following way:
* If the CPU is idle and there are no available tasks to process, the CPU remains idle.
* If the CPU is idle and there are available tasks, the CPU will choose the one with the **shortest processing time**. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
* Once a task is started, the CPU will **process the entire task** without stopping.
* The CPU can finish a task then start a new one instantly.
Return _the order in which the CPU will process the tasks._
**Example 1:**
**Input:** tasks = \[\[1,2\],\[2,4\],\[3,2\],\[4,1\]\]
**Output:** \[0,2,3,1\]
**Explanation:** The events go as follows:
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.
**Example 2:**
**Input:** tasks = \[\[7,10\],\[7,12\],\[7,5\],\[7,4\],\[7,2\]\]
**Output:** \[4,3,2,0,1\]
**Explanation****:** The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.
**Constraints:**
* `tasks.length == n`
* `1 <= n <= 105`
* `1 <= enqueueTimei, processingTimei <= 109`
|
You can just use brute force and find out for each language the number of users you need to teach Note that a user can appear in multiple friendships but you need to teach that user only once
|
Array,Greedy
|
Medium
| null |
105 |
Hello everyone welcome, you have to make me a channel, I have given you these orders and post orders, okay Google asked this question, there is another question similar to this, lead code number is 105, I have made its video, already watch it in my playlist in the penalty playlist. If you feel like watching it, then watch it. It is good for knowledge. So let us come to understand our input and output. Question, what are you saying? Input is to say that only one order has been given to you. These orders and post orders are given to you. If you have to make these two by doing them, then look at the binary, it has been made. Okay, so tell me one thing and I have given you a trick in the output. Okay, so you must have understood the question. Do you understand how we will make it? Okay, then see. Understand well how we will make a route, we need a route, then you decide the left and right side of the route, first of all, what is our tension, brother, we have to find the route, it is possible to find the route, if it is possible to find the route, then how will you know about the inverter, let's go. This is left, this is right, there is a root in the middle, so how do you know whether this one is the middle root or this one, if you do n't know which root it can be, then pay attention to the post. What is the post order? First the left is printed, then the right is printed, then at the very last the root is printed. At the very last the root is printed. What does it mean that if we take mother, I have any tree, I have a very big one, mother. Okay, so if its post order is written, then this is the root of my mother, so first the entire left will be printed, then the entire right, after that the root will be printed at the end. Do you know what it means, this is the last element, isn't this the root of military in Banda? It is clear that we have understood that whenever I get a post order, the last element of it is going to be my root. Okay, so reduce the indexing by one. I am late, this is my post, order this post, okay, we will take two variables, okay, we will take 2 variables, why will we take them, you will know why, don't worry about it, then see, we will give the name here, okay here this What is it brother, first of all I have come to know that the number written on the post order variable is my root, so what will I do first of all, I will say yes brother, I am the root, right? The route is there, brother, the post order of my post order, which I have given, the post index of it, the index of post indo, it will be the route, so come on, I have found out that I have fixed it, brother, please fix it. 2, it's very good, I have understood till now after this, let's think a little about how the root is found, it is 3, now how will we find out its left and right, okay, let's see, we will find out gradually, I have to find out this only. Which band is going to be on its left, which band is going to be on its right, this is what you have to find out, so pay attention to one thing, what I said is that these three are in the root, I know it, okay now. Let's go to these orders and see where these three are present. Okay, I went to the inverter in these orders and I am seeing that this guy who is the three who is root, where is he present here, brother, he is present here, okay he is here. If it is present then its index will be there Maa Lo I Maa, I am late, apply liner search there and find three. All the elements given in the question will be unique. It will not happen that there will be multiple threes. The root is found at the position here, the last element will always be the root. Okay. Which one will be the biggest in Salman, okay, I found it in the inverter too, brother, think for yourself what was there in the inverter, the root was always there, before the left root, the left was completed and after the root, the right was completed. What does this mean? We found out a very good thing that whatever is on the left side of this index will be the left sector and whatever is on the right side of the index will be the right sector because in the inverter. Same thing happens, there is root, there is left, there is A in life, first left, then root, then right, that is, if this is the root, then definitely this must have been on the left, this must have been on the right, let's know this thing. Okay, so I found out about the inverter, now let's pay attention, this is important. Now see what I said, the left is printed before the root. Look, then count. Everything must have been clear till now, okay this is what I said. Removed that brother, I took out the right side, left side and right side, okay and now remember, the same thing happened in the post order also, the root was printed last, I agree, but there was left side as well, there was right side too, so left will be first for sure in the post order. First the left is printed, that is, those who are at the beginning must be left, surely the left ones will be printed, after that the right ones will be printed, after that the root will be printed at the last. Okay, so tell me one thing. So we came to know that brother, how many elements are going to be there in the left side, this is our trick, from here I took out just one and how many elements are going to be there in the right side, this is also three, I came to know from here that this is Its left tree is going to be something which I will make with this sabri. Its right sub tree is going to be something which I will make with this sabri. Okay, so both of them are visible, left trick and right method, both of them are in this order. No, I have taken out these orders because I took out these orders, it is here now, no, 15 20 7, now I would need a post order also, isn't this a left sub trick, nor would I need a post order, okay, why am I saying this? I am already sending the inverter and am also sending the password. Remember, I have also entered the start and end index of this order and the start and post of the post order. If there is anything else that I will make, I will start the inverter of that too, so is it ok? What did I say, I will send the function tomorrow because now we are sending it is obvious that the index will change, now it is okay, after solving the right root of the left root, what we have to do in the last is to do the return root, our tree will be created now. The thing is that this is its instant, its post art is ok, its insert is this, we have to find out, ok, so let's see how we will find out, so ok, we have to find out the left and right connections of the root, we have to know that also tomorrow. It has been started, okay, so remember here, I have found its inverter on the left side of this route. 15 20 7 I am still waiting to find out what will happen, so see, pay attention that this route was there, how many elements are there on its left side. There is one element, okay, so remember here also, left first was printed right, so in inverter, how many elements are there to the left of this root, there is one element, okay, there will be 1 element from post start to post index, so from post. It is okay to take an index, so what will happen to it, okay, here also it will be no, here too there will be only one element because how many elements are there on the right, I will take three elements of this root, I will take it, so see, first remove the left one, it is six. I think for myself about the start of this order and its removal. Okay, so I send this here. Okay, what will happen here? The post has started, but up to which index I have to go, how much further I have to go from the post, how many elements to keep on the left. Okay, so the start of the post will be the beginning and where will be the ending, what will be the starting of the inverter on the right of the route has been found and it has been known how it would have come, then it is also easy to remove 15. See how you know that the post and this is for sure. Okay, and how many elements are there in the right side of the root, which is three, how many elements are there in its right side, there are 3 elements, I had taken out this right side, I had also stored it here, okay, so what else is the post, what is the right size from here? Three is mine, make two, mine is three, how much will it become, isn't it 4 - three, how much will it become, isn't it 4 - three, how much will it become, isn't it 4 - 3, how much will it be, one, okay, so this is what I wanted, starting is this, brother, starting is this, isn't it 15, and what is the ending, mines, right size. How many elements should be kept on the right side? Where was the right side obtained from here? Okay brother, rewind the video again and watch it and while watching the video, write it in your notebook as well. It is okay, it is not necessary to have such postures. Isn't it possible that you can understand everything by watching the video? Watch the video and keep a copy with you. Write in the copy. Okay, yes, this is its index. If you mined the size in it, then it is done. It is necessary to write, otherwise it will not remain in your mind, it is okay. I must have thought to myself at once, I also wrote this in my copy and saw that okay, this is an index, it is moving here, so the date is very important, okay, then the story I have told you will not solve the function. We will send these orders in it. Okay, so when we write the code line by line, we will explain the line balance of what we are writing now. Okay, so let's do this. So let's code this. Sometimes interviews ask freshers. Okay, so let's start. Let's do its code. What did I say that I will write a gold function? Okay, post order is put and tax is indexed. Start of these orders has to be started. Post order in start posting will do a simple function If I get it then I will break it. Correct video. Look, it's okay, that is, from the start of the pose, do minus one on the left side. The index one was just a simple course story, the same is written, let's just run it and let's see after submitting it, let's see the correct comment area, right, help of next. video thank you
|
Construct Binary Tree from Preorder and Inorder Traversal
|
construct-binary-tree-from-preorder-and-inorder-traversal
|
Given two integer arrays `preorder` and `inorder` where `preorder` is the preorder traversal of a binary tree and `inorder` is the inorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** preorder = \[3,9,20,15,7\], inorder = \[9,3,15,20,7\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** preorder = \[-1\], inorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= preorder.length <= 3000`
* `inorder.length == preorder.length`
* `-3000 <= preorder[i], inorder[i] <= 3000`
* `preorder` and `inorder` consist of **unique** values.
* Each value of `inorder` also appears in `preorder`.
* `preorder` is **guaranteed** to be the preorder traversal of the tree.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
| null |
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
|
Medium
|
106
|
523 |
hello and welcome back to another Elite code problem today we're going to be doing problem continuous separate sum and it's definitely an interesting problem and it's quite tricky to solve so we're going to go over it so given an injury nums and an integer okay return true if nums has a good sub rate or false otherwise a good sub Ray is a sub array where its length is at least two and the sum of the elements in the sub array is a mole is a multiple of K note that a sub array is a contiguous part of the array and it enters a multiple of K there exists an integer n such that x equals n times K zero is always a multiple of K okay so let's take a look here so our first example is 23 2 and so we are just trying to find is there a submarine here that's at length at least two and there's a multiple K yes there is this one right here it's okay six this one would not work okay and I think you can have negative numbers here no you cannot okay so now we have so for this one there definitely is a sub array now let's go to the next one 23 36 seven and there is one as well here actually that is a multiple of K and I think there are a couple so like this would be a subarray and then this whole thing is a sub array because that's 42 which is also multiplication there are two sub arrays there okay and then for this third one so you want a multiple of 13 so this is like um yeah so there's nothing here that's continuous anyway but let's just go through this one let's say we try to do this like what would be the brute force of doing this well it would be pretty straightforward we would have to get the sub array starting at every index and then we'd have to get every single possible sub array so like for example let's start here we would have to get all somebody started from this index that are length two or more so right so like the subarray this subarray and this subarray right or 23 and 2 20 32 6 26 23 264 23 267 and so then you would have to do also very same from this index that are two more so this subarray is subarray and this subarray and you can just divide them by 13 and check for remainder zero right then you would do this subarray and then finally the subarray so what would be the tank complexity for something like that well it's going to be N squared right n by n because we are doing pretty much a nested for Loop now let's actually take a look at the constraints of the constraints is the numbers length of 10 to the fifth and so that's not going to work for that because 10 to the fifth Square would be like 10 to the 10th and fairly code problems that's not going to work so we need something more efficient so we need to figure out a way of how do we actually figure out to separate like how do we have a more efficient way of figuring out a subarray so let's think of the what the question is actually asking right so it's saying are is it an Ranger n that's a multiple of K so what does an multiple of k mean right so if you have some n that's a multiple of K what does that mean that means that K times x right equals n so there's some integer X here that k equals n also what another thing it means is this and mod K is zero right and that's what we can use the other thing we're going to be able to use is that we have contiguous sub arrays so that's also going to be important so let's think about a few cases here right so let's say we have some integer and we're going to look at these examples with I think what were the um so stick let's looks like we're six in both of these for example so let's say we do have some integer that is a multiple of K right so we have some K times x equals n okay and so we have some number like let's say we have an array that's like you know the elements add up to six here and then you have some other stuff and then you get some other elements that add up to another multiple of six right so those would be like the easy cases right where if you get anything that adds up to six and then say something else that adds up to 18 or so on then you would know that like this is a subarray as long as this is linked to this whole thing is a sub array so that would be like an easy solution but let's think of other cases and this is pretty much gonna help you understand how mods work so if n mod k is some number like let's just say it's one right so for example what would be a number here that N1 K would be one well something like seven so let's say we have two elements in this subarray that so I'm actually going to delete this is going to help us get some intuition here so if N1 k equals one so let's say we have a sub array and we're trying to get let's say we're trying to get even seven right we have a sub array and then to get seven we would need n to be like eight so let's just say our numbers are like two four so far and so this and so if we're trying if K7 here right then this mod K like this whole sum on K would be one okay now what happens if we get another uh if we get something else in the future that the mo that the remainder of that whole thing is one well how would we do that well will be another number that's like uh that um and mod K would be one well let's think about that right so let's say we have 22 total so let's just say we have like some numbers and all this whole thing ends up this is eight so let's just say we have like a six it's 14 and then we have another eight right so this whole thing is 22 now so the sum of this whole thing is 22. now when we take this subarray right here so this and mod k equals one here right because this would be eight mod seven equals one now if we do this whole array this is uh 22 so now are you 22 mod k so it's going to want seven again equals one so what does that actually mean for us so if we ever get the same remainder like what does that mean for us right and so what it actually means is there has to be a subarray in here that the if you get the same remainder that means there has to be a sub array that if you actually subtract them right so if 22 mod 7 is 1 and 8 mod 7 is one that means if you actually subtract those two sub arrays so 22 minus eight then you get 14. and so if you get two numbers that those two numbers mod seven is one that means those two numbers subtracted from each other mod seven is going to be zero and so if those two numbers mod 7 is 0 that means this 14 sub array is the good sub array that we want so we could do that with other numbers just to give you some more intuition so let's say we're trying to have like five and we have some summary that some sub array that adds up to like seven let's say and then we have some other sub array that adds up to like 27 or something right and so if you think about it and so this is going to be like a prefix sum situation right where like this whole thing adds up to 27 and the small chunk adds up to seven that means this Chunk in the middle has to add up to 20. and so once again you would get the same thing where 20 mod 5 is 0 but 7 mod 5 is 2. and 27 mod 5. 2 so that's really all we're going to be doing is we're going to be going through this array we're going to be maintaining a total and the remainder and we're going to say if we've seen this remainder before that means there is some chunk between where we are now and where we've seen the remainder before where that chunk is a subarray that when you mod it by the number we care about is zero and so hopefully it makes sense yeah so I'll show you first example five like let's say we have the seven right so we have like a two or let's say we have three we have four and then we so we need this part to add up to 20. so we can do that so we can do like 13 7. and so we're going to go over here we're going to say okay well we have a remainder two and we're gonna um we're gonna save these remainders in a hash map and then later on we're gonna look up like did we see this before so when we get to this part then we're gonna see uh that this is like remainder two right so we're gonna say okay we have a total sum of seven so it's actually I'm gonna show you like how this will work in this in some other examples of actually doing like a dry run of it but for now so let's just say this is a remainder so the seven mod two so that's going to be our detection mod but yeah so 7 mod 2 is going to be two we're and we're going to say okay we've seen this two now when we get to this whole sum we're gonna say okay this is 27 mod 2. have we seen that before or is sorry it's not gonna be 27 mod 2 it's going to be 27 mod five yeah because we're looking for five so 27 month five is two have we seen it before yes we have that means that this whole thing minus some previous thing is our sub array so this whole thing minus this chunk is the subway we want and now I don't think that they care about like giving the subarray but we can just know that there is one so let's actually do a dry run of this algorithm for uh let's just say we do that for we do it for this problem right here for this example now we can do for both right we can do for both of these examples okay so let's do that so we have 23 to help you understand it better because I do think I could have explained a little bit better but once we do like a dry run you're going to be able to see what's going on okay so our K is six and what we're going to do initially there's a couple things we need to do to make it work so for one thing they are looking for a raise with length two and so if you just had something that started with a six like let's say your array was like six four or even like six uh I think six would work but if you had something like this you can have something like this you want to make sure this works as well and so the way we're going to make sure arrays like this work is what we're actually going to do is we're going to have a starting index so let's say this is our hash map over remainders we're actually going to set the things where the remainder zero to have a index of negative one therefore if we just have an array like this shouldn't return true because we need elements of size two but if we get something like this or actually if we get something like zero six I think six zero should also work then it would work so we're going to compare the index of the last thing we saw to the current index and as long as they are you know more than one apart that means we have a valid sub array of like two this is going to be like our base case where you know if you have some whole array be a multiple of six we just have to make sure is that our A2 elements are more and if we are at this index that would work right because this is index one so then you would do one minus negative one and that would be two indices away but if it's just this first index then it wouldn't work so if this first index does satisfy it then that would only be a difference of one okay so let's do the dryer in now so first we and remember we're getting all these remainders right so first we look at this and then what's that two mod six so it's pretty straightforward right so two month six is going to be uh zero remainder two right so we're gonna have a two and then remember we're going to store the index where that is so this is index zero I'll try the indices up here real quick two three five okay now we keep adding we so we have a cumulative total so now we have five mod six what's that well that's just five so we have five at remainder one and every single time we get a remainder we're going to say did we see it before so far we don't have any duplicates so we haven't okay now we are over here we're going to add again so five plus four so it's gonna be five plus four nine mod six emails okay and that's gonna be three okay so now we have three and we have it at index ah let's see here so we have an index so I think yeah that should be fine this 2 should be at uh okay so I made a small mistake so this should be not five plus four so we forgot to add this two so let's do that so this should be seven mod six equals one and so let's just add a one in here that's going to be at index two now we add the four so now we get 11. on six you have five and so now we did get a duplicate so we got a five and then we just asked what index are we at and what index was the last five we saw so we're currently index three the last one we saw is that index one are those two more than one index apart yes they are that means like after we got to this point we have a summary and we do have a sub array right it's right here there's two four okay so let's do another one for the second example and we can do one for 13 as well and then we'll be done we can just code it up the code is pretty fast so 23 2 6 4 7 we are looking for six and so our result is going to be once again it's going to be zero negative one here okay so we have a two mod six it's gonna be two so that's gonna be two at index 0. okay we haven't seen that yet so now we go over here five mod six five at index one you can speed this up a bit seven mod six equals one index two then we add a six thirteen mod six equals one at index three so we have seen it but so this is the other case that we need to run into so yes this is like we have seen it but you can see that these are only one index of parts that's not going to work and then what we want to do is we do if we do have the same um if we have the same like value what we want to do is keep the old one so we're actually not even going to use this one we want to keep the old one because we want to make sure that we can have an index length of two or greater and so keeping the old one is more beneficial for us okay so now we're going to add this so this is going to be 17 mod 6. 5 and now we have seen a five so this is that index like four and we have seen a five at index one so now we know that we have a valid solution and let's just make sure and yeah right when we get to this four this is a valid solution but before this four was not a valid solution so it's the same thing and then if you did this for 13 you would never get matching indices so we're not going to actually do that one but you kind of get the point so all so our algorithm is just we go through we check for mods and then we check have you seen this mod before and if we saw the same like if you have the number that has the same mod by the key that means there is a sub array that is a multiple of K by definition of so let's do that so we're going to code this up now um so we're gonna just have like mods maybe equals a hash app and then we are going to have one element in there remember so we're going to have a zero negative one okay and now we are just gonna go through our nums and we are going to maintain a total so foreign we do want the index as well so right there and now what we want to do is we want to say total plus equals V and then we want to say maybe like a mod or something equals total on by K then we want to check if we've seen it before so if mod in mods uh okay and then we just do if I or we want to do the mods mod so that's going to be the old index and this is the new index so we can just do the new index minus the old index is greater or equal to 2 and we can here otherwise so if mod was in there already we don't really want to update the next the new one remember we want to keep the old one to maximize the distance otherwise we want to add it in there so mods mod equals I and yeah if we went through this whole array and we never found anything we can simply return false right I think that's it all right perfect okay so let's think about the time and space here but yeah this is definitely like this question is good I think because it helps you get better with your understanding of mods and like what does it mean if you get the same mod multiple times and that helps you not get the Brute Force solution but it said get the optimal solution so time so for time here uh we are just going through the array one time so that's gonna be a big O of n right this is a linear solution I don't think we can beat a linear solution for this one and for space so technically worst case scenario imagine if your K was really big yes if your K is really big um and all your numbers gave you different results than you would be storing uh and numbers like they would all be unique and in yeah I guess any false solution all your remainders are going to be unique right by definition or they're only going to be like one apart but either way if you have to be storing every single remainder and so that's going to be n space okay so that's all for this problem hopefully you liked it and if you did please like the video and subscribe to the channel and I'll see you in the next one thanks for watching bye
|
Continuous Subarray Sum
|
continuous-subarray-sum
|
Given an integer array nums and an integer k, return `true` _if_ `nums` _has a **good subarray** or_ `false` _otherwise_.
A **good subarray** is a subarray where:
* its length is **at least two**, and
* the sum of the elements of the subarray is a multiple of `k`.
**Note** that:
* A **subarray** is a contiguous part of the array.
* An integer `x` is a multiple of `k` if there exists an integer `n` such that `x = n * k`. `0` is **always** a multiple of `k`.
**Example 1:**
**Input:** nums = \[23,2,4,6,7\], k = 6
**Output:** true
**Explanation:** \[2, 4\] is a continuous subarray of size 2 whose elements sum up to 6.
**Example 2:**
**Input:** nums = \[23,2,6,4,7\], k = 6
**Output:** true
**Explanation:** \[23, 2, 6, 4, 7\] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 \* 6 and 7 is an integer.
**Example 3:**
**Input:** nums = \[23,2,6,4,7\], k = 13
**Output:** false
**Constraints:**
* `1 <= nums.length <= 105`
* `0 <= nums[i] <= 109`
* `0 <= sum(nums[i]) <= 231 - 1`
* `1 <= k <= 231 - 1`
| null |
Array,Hash Table,Math,Prefix Sum
|
Medium
|
560,2119,2240
|
35 |
hey guys in this video we shout out another problem search inside position the given a sorted array of distinct integers and a Target value return the number written the index if the target is found if not written the index where it would be if it were inserted in order so they have given an array which is solid in sorted order and that contains integers and also our Target value our task is to written the index if the target is formed if you found this sale Target value in the array we have to return the index of that Target value in the array if it is not found in such case we have to return the index where we could insert that in the array so in the very first example the target value is Phi and if you look into the array the second if we start from the first element zero one two second index is containing the same Target value so we have to return the index of this element 5 that is nothing but two the second example the target value is 2. so the first element is one zeroth index first index is three then five and six so the it means they have given that uh this array is in the sorted format and the first element is one and second minimum is three so two is not four if two is not found then what shall we do we should return the index where it would be if the inserted in order so we have to return the index in the array so that we can insert the element of the target that should be in a sorted order so after one which is lesser than or equal to 2 which is lesser than 2 hence you move to the next element that is three and three is greater than 2 that means 2 has to be inserted between these two index values that is zero zeroth index value and first index value 12 to insert here if we insert 2 here then what would be the index of the two zero and then one so index of the target value would be the first index so that is the output let's take another example seven first limit is 3 1 is less than seven so move ahead then three again three is less than seven then again then Phi also less than seven again okay then six also less than seven so we have I traded to the entire element of the array and we couldn't find any element that is greater than the target value so that we could insert that Target value in between 1 3 5 6 7. so this element has to be inserted in docket has been set at the end of the array if we don't find the element anywhere else in the array and type all the elements of the array is less than the target value so index would be 0 1 then 2 then 3 and 4 so 4 is the written index where it should be inserted so now let's see the logic here we need to declare variable valves so that you can store the index value here Target index value beginning next you go to the follow for end I equal to 0 I guess till then num start length numbers dot length and I plus foreign return the index if the target is found the first example in the first example you could find the target element in the array right we just need to return index so the follow-up array will correct if follow-up array will correct if follow-up array will correct if Norms of I give some ith element in the array that is imagine it's the ith element here five bits pointing to the Phi equal to the Target value then in such case we just have to initialize Val value to P equal to I that is the same index at which the element orbit element is found in Array that is one case what if we don't find that element in the array in such case if you have to look for sums of I greater than tan if nums of I greater than Target that means you look for 2 here is 2 equal to 1 no then more height is 2 equal to 1 no it's not equal to 1. is 1 greater than the target value no so again no further is 3 greater than 2 value yes it is so if it is found that means you have to insert in between 1 and 3. in between one and three one set two so its index would be 0 and 2 is index will be 1. this index is nothing but the current index value which was said before inserting the element 2 so hey yeah if we get the target value and equal to the nums value then you have to break the loop here itself here in this case also one as you found the position just stop from the loop so if You observe here you can combine these two cases as nums of I equal to the power equal to Target value we just need to initialize the value of ith value to the value so radiant guys understand why I initialize I to the Y value because we have 1 then 3 is greater than the target value that means you have to insert it just before the three if it is just before the rate nothing but three's position itself type between one and three it's nothing but 0 and 1 position so without tools to check after 1 3 so it will be 0 for 3 it will do one plus so and you just break from there stop the titration here and come out of the loop if these both are not the case else if the end of the array what how to handle this case so there are nums of Pi is less than a Target If You observe 7 is the Target and all the elements are lesser than that so numbers of a lesser than the Target and one more condition I equal to now I'm starting minus one that means if I is at the end of the loop then what we have to do we have to insert the 100 value of the next I tell you to the array so 0.23 4 is the I tell you to the array so 0.23 4 is the I tell you to the array so 0.23 4 is the index position 4 is nothing but if length now we start left or you could write I plus 1 answer as well so as I said these two conditions you will combine it if Norm of I greater than or equal to Target and for lesser than or equal to Target with I equal to the end of the array you follow this condition what if terms of I it is lesser than the target and it's not the end of the array that will come in the else part of I lesser than Target I am I is not equal to the end of the array that means you just need to increment the value of I equal to I Plus 1. in this case 1 and 3 1 is lesser than 7. and this I position is not the end of the array so just move further so you need not to write this case if none of this case will match this case will be executed hence the for Loop has the built-in hence the for Loop has the built-in hence the for Loop has the built-in increment value so we shall execute this foreign required to store the index value so let's start with i equal to 0 . and I plus of I greater than equal to Target then value will be equal to 5 times Loop so if numbers are 5 greater than or equal to Target in this case 5 is equal to 5. so that case you just initialize the value file to the value that is the index which you need to where the element is present if number greater than the target so 3 after 1 3 is greater than the 5. the first element third to be greater than 5 that means you have to insert the 2 in between one and three that is nothing but the current index value so value equal to I it is break from the loop as if terms of I lesser than calculate what if Norms of Y lesser than tablet here in this case 1 is lesser than 7 or anything it might be current I equals 10 minus 1 is it the iteration is at the end of the loop so 6 is lesser than 7 and this I value is nothing but num start length minus one that is at the end of the loop this is insert that Target value after the array next index to be last element of the array if none of these cases are passed else part will be there that is not equal to an amsterdament minus 1 in such case you just need to increment the a value which is already happening the next element so at the end equal to yeah we shall submit this year this is pretty easy problem if you guys have any doubts please put down in the comment section and subscribe to the channel will come up with another problem in the next video thank you
|
Search Insert Position
|
search-insert-position
|
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[1,3,5,6\], target = 5
**Output:** 2
**Example 2:**
**Input:** nums = \[1,3,5,6\], target = 2
**Output:** 1
**Example 3:**
**Input:** nums = \[1,3,5,6\], target = 7
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` contains **distinct** values sorted in **ascending** order.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Easy
|
278
|
1,970 |
welcome to Pomodoro Joe for Friday June 30th 2023 today we're doing lead code problem 1970. last day where you can still cross this is a hard problem so there's a one-based interesting this so there's a one-based interesting this so there's a one-based interesting this is one based there's a one-based binary is one based there's a one-based binary is one based there's a one-based binary Matrix where zero represents land and one represents water you are given integers row and column representing the number of rows and columns in The Matrix respectively initially on Day Zero the entire Matrix is land however each day a new cell becomes flooded with water you are given a one-based 2d array cells you are given a one-based 2d array cells you are given a one-based 2d array cells where cells index I is equal to row and column represents that on the Eighth Day the cell on the earth row and the seat column one based coordinates will be covered with water you want to find the last day that it is possible to walk from the top to the bottom by only walking on land cells you can start from any cell in the top row and end it any cell in the bottom row you can only travel in the four cardinal directions that is left right up and down return the last day where it is possible to walk from the top to the bottom by only walking on land cells all right and then we have an example here so we have a bunch of land on one we fill in one with water on day two we have two one oh interesting so there too is the row and one is the column so this is opposite that I'm used to like X and Y so this is 2 1 fills in here one two fills in here and that means we're blocked from going up to down all right we have another example one and then one two all right and then a more complex example oh and this is an interesting case we have to keep track of so in this case you can have diagonal water that blocks you from progressing because you cannot travel diagonally alright so that's something we have to be aware of and then we have some constraints all right so we'll put 25 minutes on our Pomodoro Timer and we will get started so for this one we have to think about what is the end condition the uncondition is when we cannot go from the top to the bottom and how does that happen well there has to be some water that basically blocks our path how does the water block our path so it looks like essentially there is a continuous body of water that occupies every single column all right that makes sense if you had a if you had disparate bodies of water like separate bodies of water like this one they might occupy all the columns but you can still get past but as soon as you fill in this Square here now you have connected bodies of water that occupy all of the columns okay so we have to consider the bodies of water connected if they are even diagonally adjacent all right so I think for this we will go through we will keep track of which cells get turned into water when cells are adjacent to each other we will merge them into one body of water all right and then when we find one body of water that occupies every single column that means we've reached the end you cannot Traverse from the top to the bottom anymore by just going on land cells because we have some body of water that takes up every single column okay so that's our strategy now how do we merge these bodies of water and for that I think I'll use my new favorite algorithm and that is the union find so the union find will essentially let me create sets of separate bodies of water but then when we have some piece of water or some square that gets filled in with water we can now Union these two bodies together into one body of water so that's how this one works all right so let's do that so this will be a variation on the union find algorithm if you're not familiar with that I'll try to leave a link in the description you can also watch my other videos on Union find and you can look it up the union find is new for me so I'm probably going to butcher this but I really like it so let's see if we can make it work all right so we'll start with some result set it to zero and we will return our result at the end all right so since we're using a union Vine let's actually Define our two functions Union and find so let's see we'll Define fine first so for find we'll take in some cell and this will return the group that it's in or the body of water that it's in so essentially how this will work is every body of water will be defined by some group label and in this case that group label will probably just be some cell so some coordinates I don't really know typically you'll have either a greater than label or a less than label in this case it's a little bit different because this will be a coordinate that has both an X and a y or a row and a column so I think I'll just have a label which is a row and a column so the label for our group will be some coordinate we find our cell by looking for this coordinate we need to look up which group it's in so for this I'm actually going to keep a dictionary this is going to be a little bit different than I'm used to so let's see how this works so I will have a group or a cell to group mapping that's what I'll do so I have a cell to group map and that will be a dictionary and let's put a little label here to tell us what it is so the key will be a cell that's I kind of want to say X and Y but it looks like this is row and column so it'll be row and column and the value will be the group label and that's also going to be a row and column all right so we initially have no cells in our cell to group map when we do a find cell all right so we look up our cell in our cell to group map so if cell is in our solid group map so we'll return the cell to group map value at this cell so this will be holding our group all right if the cell is not currently in our cell to group map basically we don't know which group the cell belongs to then we'll make the cell belong to its own group it's just going to be basically the label for itself so the sell the group map for the cell will just equal the cell that's pretty simple cool so that's our find oh I guess we still need to return it here so we'll just return cell all right what's our Union so now our Union will take two cells cell one and cell two and what this needs to do is basically Union the two sets or the two groups that these cells belong to so let's first look up which group these cells belong to so I'll have group one well we have a function for this so we can do find cell one and group two will be find cell two let's just copy and paste now if these two groups are the same then we don't need to do anything so let's check for that first we're just done and we can return cool if they're not the same typically you would have to find the greater or lesser groups do some swap for me I'm going to do this super simply if these are not the same group I'm just going to force group two or a cell two to be in group one and then we'll go through and find all of the other cells in group two and force those cells to be in group one as well this isn't the most efficient but I think it should work so at this point we know the two groups are not the same so I'm going to force cell two and all of the other cells in that group to be in group one so for that we'll grab this so cell 2 will now be in group one all right and now we need to recurse now we need to Union our cell one we could also do group one if we wanted but we can Union our cell one enforce our group two now remember the group labels are just cells so we're forcing group two into cell ones group all right and eventually those will Converge on one group okay so we have our Union and we have our find now we need to go through all of our different cells so every day in our cell list here and add these cells to our groups so we can find which cells belong in which bodies of water so for every cell in our cells well let's see for every cell in our cells look like these are lists now one thing that won't work here for me is a list because I'm using tuples and the reason I'm using tuples is because one of them has to be the key into the dictionary and you cannot use a list as a key so I might need to turn this thing into a tuple so let me call this um chords oh maybe I'll call it cell and I'll call chords and that will be a tuple of this cell uh not Coors cohorts coordinates that'll be a tuple for this cell all right next I need to look at all the adjacent cells that's not just up down left and right but we also have to look at these diagonals to see if there's any water there if there are we need to Union those groups oh man that's a big one so let's see we have some offsets here I'm just going to have a list of offsets and these are going to be up down left right and then up left up right down left down right so these are a set of looks like that'll be three six eight different options all right this is negative one because we're going from here this is our Center we're going negative one so for this we're using their screen coordinates where the upper left is zero so this is row actually I guess technically it's Row one because this is one index so this is Row one this one's row two this is Row three this is column one column two column three so for here we're going down by one row and down by one column for in the center we'll be going zero in our X or in our column Direction I guess that's the row isn't it oh this is confusing we're going zero in the row Direction so that will be this guy put one in the column Direction our negative one in the column direction oh man I am getting I'm confusing myself here oh well I'm just going to do this based on the numbers instead of trying to think about it too hard so this will be one and this will be negative one right and then I'm just going to space these out so we're gonna have negative ones for all of this row this will be a zero let me give a nice space here this one is technically zero so we don't really need this one so I'm just going to skip this middle one let's see this is positive one comma zero I'll be re-spacing these to make a I'll be re-spacing these to make a I'll be re-spacing these to make a little bit more readable no they should go through this should be a one and a one all right let's space these out so they're a little bit more aligned okay so I think this should do it so negative one zero negative one positive one so basically we have a negative one column a zero column and a positive one column same thing here we have a negative one row a zero row and a positive one row so these are all the offsets so these are the different cells around our current cell we need to be checking so let me grab my X and Y out of my current cell I guess this should be row and column let's do this right all right so that's our coordinates here and for every offset in our offsets now we'll be using these offsets to create basically new cells that we need to look at to see if we have to merge these different groups or Union these groups all right so let's see I'll have C for our new cell and that will just be equal to all right our current row plus o at index zero our current column plus Row in or not row offset at index one now we need to check to see if we have exceeded our bounds all right so if this current cell this new cell at index zero this is less than one then we're out of bounds because this is a one in one based array or if our column at uh I shouldn't call this C that's bad yeah I should call this new cell or adjacent cell neighbor how about that there we go so our neighbor so if the neighborhood index 0 is less than one then we're out of bounds all right if our neighbor at index one is less than zero then we're out of bounds or a neighbor at index 0 is greater than this would be a rose I believe or neighbor at index one is greater than columns in any of those cases we are out of bounds and we can't count this or we can't try to merge this so we'll continue all right if we made it this far then it's possible that this neighbor is also water and if it is also water then we want to merge these groups or Union these groups so first let's just check if it's water if neighbor is in one of our groups so if there is an entry for this neighbor in our cell to group map then this is water if it's not in there then this one isn't water we don't need to worry about it so if this is water what do we need to Union them so we'll Union our neighbor actually let's do it the other way around let's Union no let's Union our neighbor so we'll Union our neighbor with our current coordinates so that takes care of our Union now there's a couple things that we're missing here we don't have an initial way to enter our cells into our Union find our dictionary here so basically we're going through we're never going to find anything in the dictionary because we've never put anything in the dictionary so one way to get around that here essentially once we have these chords we know that this is water we can just create an entry in our dictionary right here and one way to do that a simple way to do that is just use our find so we'll just find our chords now this is kind of a hack because we're not really using the find to find it we're mostly just using it for this case here where we're creating an entry in our map all right so we're going to find our coordinates that creates an entry in our map then we'll go through we'll look at all the adjacent cells if there are adjacent cells that are water will merge or Union their two groups now the final piece of this we're not actually checking to see if we've reached the end how do we know when we reached the end well as we discussed at the beginning we know we're at the end when we have one body of water that actually has an entry for every single column in our grid okay so we need to have some way to check to see if this has a column or an entry for every column in the grid so let's create a function for this all right we've added our neighbor we've unioned their two bodies of water so if we're done so it is complete then we can return what do we return uh this is another thing we're missing we're supposed to return what turn or what day we're on now we're not keeping track of days in here so we need to do that here so for every day in and we will enumerate our cells so the enumerate will return the index and the value at this index so the day will be the index the cell will be the value at that index so we'll return the day that we're on that is complete Let's see we could go through all of our groups checking but it would be better if we knew which group we just updated so we only have to check is complete on the updated group so for this we'll just pass in the coordinates all right so now we need to create this is complete function all right so one way to do this is to go through and find out every single cell that's in the same group so we can do a find on this cell and then go through all of the other cells in our solid group map to find out if they're in this group check their column to see if it's already I guess we'd have to keep track of the columns we need a set of columns I have a better idea how about this let's keep track as we're adding our different cells into these different groups let's keep track of all the columns that are in that group so we need a new thing here so we have a group column set this is a group to call a map I guess so for this one the key will be the group and the value will be a set of columns so that makes this one pretty easy so all I have to do is look up this coordinate we have to get the group for this coordinate so first we'll get the group that equals find coordinate and then we need to look up that group in this column map here so the columns for this group will be the grouped column map for this group and then we can just return the length of this columns group if that is equal to the number of columns in our grid all right so this will tell us if we've completed our body of water or the body of water contains every single column in our grid if it does then we are done okay now we still need to update this somewhere this is a little bit ugly so every time we add some cell let's see how does this work this will actually work with our Union every time we Union we'll actually need to take the Union of the two groups of these columns oh man we have two minutes left all right this is going to get ugly I apologize in advance every time we Union well after one group two if they're all the same that's all fine otherwise they're not the same we'll need to grab let's see column set for group one let's call this group one columns I guess since we're merging group two into group one let's grab group two's columns all right so we'll grab group two's columns and then we'll Union them with group ones columns and reassign that to group one's columns this is so ugly all right I have a group one column map just going to be the group one column map Union this is a set operation well you need that with this group two columns okay so now we've unioned those together now we might not want to do this every single time oh we are out of time ah shoot all right we don't want to do this every single time we only want to do this basically the first time we come in here we'll Union those groups and then we don't need to worry about it but that does mean that we'll have to like reset this one ah so we'll have to check to see if this is even in the group all right so first we'll have to say if we have an entry for group two in this column map that's not empty then we'll grab that entry we'll Union it with group one's entry replace group one's entry and then we actually want to set groups to entry to either a set or to none I think we'll just set it to none that'll make it easier that means when we come in here it'll be none and we won't do this a second time all right that takes care of this now we don't have an initial set to begin with so we'll actually have to create a set up here all right so when we create this cell then we need to create a column map for this cell and that will just be a set and that set actually needs to contain this cell's column so that's the Cell at index one and we have to wrap it in a list because a set requires an iterable oh man that is super ugly okay well we are out of time so let's just run this and see if it works and we've got something wrong got something not defined group two columns that's right there we go try this and that works holy smokes all right we'll submit this see if we can pass all the tests you got something wrong none type object has no attribute meaning so that means this group one is missing the set let's see we're creating the group set here but we might be setting it to none here all right so let's see we need to make sure that we actually have a set for group one how do we know that we have a set for group one we could just make this an empty set let's do that it's not my favorite solution but let's see if that works right so this gives us a wrong answer let's use this test case and let's see if we can figure this one out so I think one thing we want to do switch this back to none down here I am doing neighbor first and then coordinates I think I might want to do coordinates and then neighbor now this just means that the coordinates will be the thing that we're merging into and we know that we've just created the coordinates here so this should always have a set that might fix this problem now this does make this really fragile so this is probably not the best answer for this problem okay so that works but it might just be lucky oh and we pass all right so we pass and we actually do pretty well we'd be 89 for runtime and 59 for memory so that's not bad at all now I will say this is fragile it does depend on ordering here which is not really great we definitely wanted to do coordinates first because up in our Union we were always merging into group one so we wanted to pass in this coordinate as our first up there we go or as our first argument because we know we just created this coordinate which means we know it has a set all right pretty fragile not great code but I don't have a lot of time today and that's about all I got so check this one out this one again is Leap code 1970 last day where you can still cross for this I used a union find I really like the union find algorithm but there's probably a better way to do this anyway hope you enjoyed this hope you had fun hope you learned something hope you can go out and write better code
|
Last Day Where You Can Still Cross
|
sorting-the-sentence
|
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively.
Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`).
You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down).
Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_.
**Example 1:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\]
**Output:** 2
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 2.
**Example 2:**
**Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\]
**Output:** 1
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 1.
**Example 3:**
**Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\]
**Output:** 3
**Explanation:** The above image depicts how the matrix changes each day starting from day 0.
The last day where it is possible to cross from top to bottom is on day 3.
**Constraints:**
* `2 <= row, col <= 2 * 104`
* `4 <= row * col <= 2 * 104`
* `cells.length == row * col`
* `1 <= ri <= row`
* `1 <= ci <= col`
* All the values of `cells` are **unique**.
|
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
|
String,Sorting
|
Easy
|
2168
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.