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 |
|---|---|---|---|---|---|---|---|---|
435
|
hey everyone today we are going to subscribe the question non-overlapping subscribe the question non-overlapping subscribe the question non-overlapping intervals so you are given array of intervals where intervals I equals dot I and I return the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping non-overlapping non-overlapping so let's see the example so you are given um this input array so output 3 is 1 because uh um if we remove one three intervals so rest of intervals are non-overlapping so rest of intervals are non-overlapping so rest of intervals are non-overlapping so that's why in this case we should return one before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all details of all questions in the video and you can get the code from GitHub for free so please subscribe my channel hit the like button or leave a comment thank you for your support okay so let me explain with this example so I copy input array from example one so to solve this question I think the easiest way to solve this question is that first of all I um sort intervals with endpoint so that means each index one so like a two three four and then um iterates through one by one so this is a like a PE stands for like a previous uh endpoint and then initialize the first end point two and then this is a return value so that means the minimum number of intervals you need to remove to make the rest of intervals and on mobile IP so um now initialized with these two so I start from here index one so every time compare previous and with current start point if previous endpoint is greater than current start point that means we should remove current intervals so in the case other plus 1 to result variable if not the case just update previous endpoint with current endpoint so let's begin so now we are index one so compare previous endpoint buses um current start point they are same in the case we don't add result uh we don't have the percentage result just update previous endpoint with current endpoint so that means previous endpoint should be 3. and then the next and then next will be the same thing compare previous endpoint 3 with current start point one so 3 is greater than one in the case uh this is a regular overlapping so that's why we should remove this interval so that's why other percentage result variable one and then um so we need to remove this intervals so I don't apply the previous endpoint still three and then move next so we find the three as a start point and the previous and the point is three so they are same in the case we don't add plus one to result variable and just update the previous endpoint with current and point so forth so that's why output H4 and then we finish iteration yeah hola we have to do is that just a return result variable so in this case one yeah so that is our basic idea to solve this question without being said let's get into the code okay so let's write the code first of all initialize the result variable with zero and we need to sort intervals so in the bars Lam Dot and X colon so X and we have to sort and the point so endpoint should be index one and then previous and equal intervals and uh zero and one and then start reading for index in range start from 1 to things of in doubles and then as I explained earlier if Friv and is greater than in the virus so current start point in the case we should add plus 1 to that variable if not the case updated previous endpoint with current endpoint so I and the one yeah so that's it after that just return result variable let me submit it looks good and the time complexity of this solution should be order of n log n where N is a number of intervals in the input list so the Sorting step takes order of analog end time and the loop over the intervals takes one time so resulting in the total time complexity of order of n log n and the space complexity of this solution should be order of one constant time so it only use constant amount of extra space to store the previous in the time like a prevent in the result variable yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Non-overlapping Intervals
|
non-overlapping-intervals
|
Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_.
**Example 1:**
**Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\]
**Output:** 1
**Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping.
**Example 2:**
**Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\]
**Output:** 2
**Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping.
**Example 3:**
**Input:** intervals = \[\[1,2\],\[2,3\]\]
**Output:** 0
**Explanation:** You don't need to remove any of the intervals since they're already non-overlapping.
**Constraints:**
* `1 <= intervals.length <= 105`
* `intervals[i].length == 2`
* `-5 * 104 <= starti < endi <= 5 * 104`
| null |
Array,Dynamic Programming,Greedy,Sorting
|
Medium
|
452
|
363
|
hey everybody this is larry this is the third day of july and therefore the third day of the july league daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's farm maximum rectangle no longer larger than k okay so i usually solve these live um and everything i know i or if i'm googling you'll see it um so if it's a little bit slow feel free to fast forward while watching 2x or whatever or skip ahead whatever you need to do um so this one is going to be a little bit tricky so the first thing i look at is the constraints to kind of see some ideas seems like we have m and n is equal to 100 so yeah let's see i mean i think one of my advantages is that i've seen a similar problem before i don't know if this is this one but hmm but this is a hard problem supposed to say i think that so the first step that i would do is try to think about what happened to me now let's simplify the problem a little bit first right let's start with a max sum of an array no larger than k then what can we do well the thing we can do is by we can do something that is that linear time um you can do something n log n by using prefix sum and then binary searching on the endpoints yeah because i uh is there a sliding window you think i don't know if there's a sliding window thing because the problem with sliding window in this case is that there are negative numbers and with negative numbers i don't know if the monotonically increasing property still holds so like you cannot just move because you may be able to move left but you may take a subset of left and then moving right will maybe give you a better answer as well so that problem is a little bit tricky i do believe you can get n log n by if you're having a prefix summary let's say you have somewhere right let's just take the first okay maybe a little bit longer okay actually this is a one dimensional array but yeah let's say you have something like this and then you have a prefix sum of two uh well let's just start with zero two four three and then for each one you can binary search the closest number to k or something like that so that you can get it for example in this case this is k is 3 so our k is equal to 3 so at zero well there's nothing to the left of it we add it to a set at two we want to search you know basically we are at some we're at some x and we're looking for some y such that it is uh so such that this condition holds right so that means that given x and given k we can actually you know subtract k and then add y on the other side so then we can do a binary search on x minus k in the prefix kind of i don't know if that makes sense because i think this obviously requires a prerequisite and prefix sums um so if you don't if you're not familiar prefix sum i know this is the third day sometimes i go over prefix some of it but in this case i'm not going to go too detail and prefix some because i think this is a pretty tricky problem so definitely practice how to prefix some problems first but basically the idea is that okay let's say we're at this four right and we want to know some segment such that it ends at four and um and the sum of that segment is three right so that means that we want to binary search four minus three so for some number that's less than one you could play around with some binary search idea but that's basically the idea right and here that we found the zero so that mean because two is bigger so if we find zero that means that y is equal to zero so in this case we have four minus three less than equal to zero that means that the sum in this case wait is that true or maybe i did it the other way around sorry actually you want to find a two right because now you have did i do the signs wrong did i mess something up oh yeah no this is right i just kind of plugged in zero silly um and we want to maximize y in this case oops and then now when you plug everything back in you have the smallest sum which is x minus um so 4 minus 2 is less than 3 where k is 3 so then that means that the largest sum is 2 which is the point that ends at 4 right so i don't know that is kind of a good way of explaining but basically you have some idea of maybe i can draw it out a little bit hang on but yeah that's basically the idea is that okay so you have some prefix some oh i don't think i'm showing on screen hang on okay for some reason that's oops was that better okay um so yeah so basically the idea is that okay you have some prefix sum right where the and this is like a pseudo number line or something like that so for in for instance we have 0 2 4 and 3. basically we're trying to figure out uh for a target where the sum of some line segment it's going to be less than or equal to 3 but the closest as possible and basically from here we put we dump all the previous numbers in a in something that we can binary search either a set or whatever and in this case we can quickly but clearly um c find a two here so that's basically the idea um for the 1d um 1d case and then the question becomes okay so we have an idea behind the 1d case right how do we generalize it for a matrix i think for this case given that m and n is 100 you can actually just do a repeat the same algorithm but for a subset rectangle instead and what i mean by that is from brute force because m times n or sorry m and n like the raptor rap raptor because m and n are both 100 then that means that they're n um roughly speaking a hundred choose two possibilities um basically for example you know let um because you can just basically choose any sub um basically you can choose let me change the color you can choose an upper bound or and a lower bound of the indexes so basically that's your height of the thing and then you can effectively treat that is a 1d problem and then do what we did before um and basically and then we take the max out of those basically we only look at this segment for example maybe we want to try j as you go 2 to 1 and then the max j is equal to 10 say right so then now we kind of squeeze that compress that in and then try to do it that way um that's basically what i think i'm going to try to do i'm thinking about complexity for a second this is gonna be a hundred cubed times like a hundred so how much is that 100 cube is going to be about a million and then log 100 is like another 10 so it's gonna be about 10 million hopefully this is fast enough maybe we have to do another optimization but yeah and then the follow-up is what but yeah and then the follow-up is what but yeah and then the follow-up is what if the number of voices much larger than the number of columns because so in that case notice that we did it you know with the rose you could just transpose the um the matrix so that you kind of basically flip it or rotate it or whatever you want to call it so that you can take advantage of it as well because it is going to be m times n times log n or something like that um and in that case you want you if you want to reduce log n to log m or log m to log n then you could just switch to the dimensions um okay so i think that's enough of an idea to let me get started i know that the explanation is a little bit hand-wavy a little bit tricky bit hand-wavy a little bit tricky bit hand-wavy a little bit tricky hopefully um the ideas are there enough that we can get started and yeah hopefully that should be good enough i'm just thinking about explaining it's way tricky because i think it took me a long time to get this the first time i did it like a couple of years ago but um but with that idea i think i might still be wrong though to be honest because i am solving this live so yeah okay so let's see so the first another thing that we have to do i actually forgot to mention one bit how do you kind of reduce this um how do you reduce this thing to a 1d problem right well the way that you would do it is by hmm why is that not showing up why is that showing up a different window hang on so basically the idea is that okay um and this is part of prefix sum which is why i forgot to mention it but this is a 2d version prefix sum sometimes refers prefix matrix so the idea here is that okay so to get an arbitrary um sum of a rectangle which we have in orange we basically pre-calculate the in orange we basically pre-calculate the in orange we basically pre-calculate the sum from the corner upper left corner all the way to that corner and if we do that for every possible corner then the orange box is just going to be equal to this yellow box minus the two green boxes and then you add it back in the purple box because you double subtracted it so that's basically the idea behind this problem as well um and from that you could kind of compress that to one d as you kind of move from left to right that's basically um yeah that's basically i think all the pieces we need even if it's a little bit tricky um to maybe watch it again if you're having trouble or just ask me a question on either the youtube comments below or in discord um okay so let's get started yep yeah so let's start with the prefix sum i know that some people do it different ways but i do it this way um because i don't know it feels more natural to me okay prefix is equal to typing is hard and i always have a have an extra zero row and column to denote nothing basically right like if you don't use it otherwise it's still not that bad but you have to do if statements in a lot of places um so yeah so now let's do the prefix sum whoops um let's see let's do it this way plus matrix of x y does that make sense when i'm at 0 no oh no this is right oops where am i man i'll find one's a heart okay let's say we're at zero we want that to be one into the prefix so yeah okay i think this is a little bit off because we wanna do yeah okay it doesn't really matter and then i do an another while there are a couple ways to do this actually but i don't i find this more intuitive for whatever reason your marriage may vary as i said then we can print it out just to kind of see real quick and in this case you have an extra padding of whatever you have one two uh one negative one should be the sum of the corner which is or the little square so that's true and then three is the sum of all the things so that's two zero degrees so that's good okay and then now we just do the brute force thing okay so for let's call it top is it or maybe bottom depending on how you want to go up or down i don't know doesn't really matter though uh that is good x1 then rows x2 in range of x one rows because it could be the same column okay yeah that makes sense because you can have the same well um just have to be careful about your indexes but yeah so then now we have to do set as you go to it's still um python set by name search i always forget whether you can buy um okay so set doesn't allow you to binary search so we'll just use sorted list for now um basically a sorted list is at least in python a sort of um a tree type thing it's not quite true there are some nuances and you should read about it if you're really interested in it but basically it's a data structure that keeps a sorted list which is what it sounds like and add stuff in roughly speaking log in time and you can do binary search on it because it's sorted yeah so then now how do we do this so now we're given these uh now our height is x1 to x2 inclusive so okay and now we're trying to go from left to right okay so for y in range of yeah from zero to columns okay what do we do so okay so the current prefix sum what is the current prefix sum of this is going to be so x2 is the larger number so the up the lower right corner is going to be something like yeah this plus one because we have to take a count off by once so that's the lowest corner and then we have to subtract that from as we said now in this case i'm just trying to think about how to do it but in this case we only have to subtract the difference between um x1 and why right because we're just subtracting the columns well not the columns but the upper part of that rectangle if you want me to visualize it back here you go um basically right now what we are doing is we want to let's say we have now this is x1 and this is x2 and then basically we want to look at the sum of this chunk so which is equal to the sum of me changing colors which is oh that's not a box which is basically this minus this right so we don't so i think that's a actually a different uh but also still yeezy-ish a different uh but also still yeezy-ish a different uh but also still yeezy-ish formula um which is what i did actually so yeah i think that's this is it for the current prefix sum and then we try to buy binary search from this bisect left so we have as we said current minus some previous less than equal to k so then we minus k plus so minus k is less than some previous and we want to maximize this number wait is that right did i mess that up now we want to minimize this number so that this we want to minimize this so that this is maximized right because we're trying to max current minus previous and the way that we do that is by minimizing previous so we want to minimize previous for which this is true so okay so target is equal to current minus k that's so because we're trying to get the smallest bisect left should be good yep okay target so now this is the current index if index is within length otherwise it means it's our bounds and we don't find a number that then s of index is the smallest number that's bigger so then that's the number that we're looking for that's the previous so then current minus this previous is a target answer um so then let's keep track of the best answer um can it be negative maybe it can be actually right max summer because k could be negative as well so okay so actually this should be say negative some big number okay so then here we just do this and i think that should be okay and then at the way and we want to add to the sorted list um the current prefix sum and that may be roughly it uh might not be correct but i think conceptually that's it maybe i'm missing some weird stuff but let's test some test cases is it sort of containers what did i want from sorted containers uh containers okay so this looks mostly good it's but it's not though um at least it runs but hmm so this finds okay so at the corner three and k is equal to two it tries to find one and instead it finds does it fine all right it's time to do it for some debugging i might have some off by ones because it's very oh actually this is an off by one this should be a y plus one because maybe that's why okay let's run it again okay i mean maybe it's better but in this case it's clearly not better um you think because this one should be pretty straightforward and theory so we have closest to wait or maybe i'm thinking it wrong no that should be right maybe expected answer is three when you have all three and the answer is three at the end and we should be able to binary search for zero oh because i don't add zero as to in the binary search for having no elements in the beginning okay so this looks good um to be honest not gonna lie i'm not super confident about it but this video is already 22 minutes in and it's late at night and i'm going to retire so i'm going to hit yellow submit and then see what happens hopefully it's fast enough because that's the other concern that i might have okay cool so this is fast enough um i do want to i think okay let me think about it for a second what i want to say um yeah so this is good this is instead of using m and n because i always confuse about what's m and m's let's use r and c um so in terms of space you can see that we use o of r and c space and pre uh prefix and in theory assuming that we always free our memory this is only going to be of c so this is all of all r times c in space in terms of time this is o of r times c as you can imagine and as i said this is o of r choose 2 which is r squared roughly times c so r square c times log c so r squared c times logs where r squared c times log c oh that's a mouthful let me just write it out then is the complexity um and of course if r is way bigger than c you just like i said transposed away so that um you get the smaller number on the square point um yeah let me double check that oh no i think i do this very often i forgot to turn but that's fine um i think i didn't really change anything after displaying that um but yeah so to go over it again because i covered the code because i'm an idiot um this is the thing that was in the picture that you stared at for a while because i didn't unblock it um so the target is current minus k um and what i said and hopefully that came through even though i think that this was brought um so we have this where we try to maximize this which means that we want to minimize previous so yeah so that's basically what we did by getting the smallest previous that is greater than target right because that's basically this is the target and we're trying to get the smallest number that's bigger than uh bigger than previous right and then if this is found then we do this best thing and then at the end we added to a set so that uh or a sort of list so that we could search for it later in a binary search kind of way and of course in other languages you may use tree or something like that um yeah that's basically what i have let's peek over the solutions real quick because i wonder if there's an m or a r squared times c solution i feel like there may be but i'm doing it a little bit funky way um this is actually the way that i did it huh that's kind of cool i guess yeah and this is what i said what how is this oh i guess you can do it that way that's a little wacky though of the followers whatever combining with kaden there's a contains album oh no that's the same thing okay same idea okay well i think i'm happy with my solution let me know what you think uh let me know if you have any questions uh come on discord or whatever you know leave a comment in the thing below um i think my code is relatively queen as well and i am solving it live so i'm happy about it um i mean there's some like maybe minor constant thing and space uh so it turns out that the thing you can notice is that we always use this thing so you can actually um pre-process the array differently but um pre-process the array differently but um pre-process the array differently but i think it's fine um yeah so that's all i have for today hope y'all have a great weekend happy fourth of july for if you celebrate it and yeah stay good stay cool to good mental health um we're gonna do some contests later good luck and i'll and we'll do it together uh later bye and to a mental health bye
|
Max Sum of Rectangle No Larger Than K
|
max-sum-of-rectangle-no-larger-than-k
|
Given an `m x n` matrix `matrix` and an integer `k`, return _the max sum of a rectangle in the matrix such that its sum is no larger than_ `k`.
It is **guaranteed** that there will be a rectangle with a sum no larger than `k`.
**Example 1:**
**Input:** matrix = \[\[1,0,1\],\[0,-2,3\]\], k = 2
**Output:** 2
**Explanation:** Because the sum of the blue rectangle \[\[0, 1\], \[-2, 3\]\] is 2, and 2 is the max number no larger than k (k = 2).
**Example 2:**
**Input:** matrix = \[\[2,2,-1\]\], k = 3
**Output:** 3
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 100`
* `-100 <= matrix[i][j] <= 100`
* `-105 <= k <= 105`
**Follow up:** What if the number of rows is much larger than the number of columns?
| null |
Array,Binary Search,Dynamic Programming,Matrix,Ordered Set
|
Hard
| null |
285
|
hello welcome back in the next two videos I will talk about in order successor in BST or binary search tree this question is from Linko which is equivalent to Leo 285 that Leal question is a Leal premium question but you can go to Linko and do this for free I'm not associated with Linko and that this is not an endorsement but it is another resource that one can try some of those legal premium questions with we given a binary search tree and we're given a note in that tree our job is to find the in order successor of that nodes first let's talk about bsts so this is a simple BST you have the root nodes on top and you have a left child and a right child the left child has a smaller value than the root node and the right to has a bigger value so what is an in order successor if we looking for the in order successor of one that will be two if we are looking for the in order successor of two that will be three in this tree and if we're looking for the in order successor three there is none in this tree look at this tree if we are looking for the in order successor of four that is five which is the root of this tree essentially we're looking for the note which has the next larger value a naive solution for this problem would be to do a in order traversal as the name suggested in order traversal will touch notes in increasing order from the notes with the lowest value to the notes with the highest value all we have to do is to Traverse and then once we hit the noes that we're looking for the next one is the one that we wanted to return this would have the runtime complexity of O of n the question here is that can we do better well it depends there is a better solution but whether we can do better it really depends I will explain later but first let's talk about this better solution this is the function definition of the function that we to write we are given a root Noe of the tree and the tree note p and what we have to find is the note that has the next higher value than the note P since we given the root noes we know that we to walk through the tree starting from the root now the decision to make there is that which branch of the trees do we have to go down now there are really three scenarios the first scenario is that the value of p is equal to the root value second scenario is that value of p is greater than the root value and the first scenario is the value of p is less than the root value so first scenario the value of p is the same as value of root where is the in order successor of P well it must be on the right sub tree so in this tree this will be six now this could be other notes on the right sub tree consider this tree is still six but notice where the six is not is here we can say that for scenario one the in order successor must be on the right of tree and what we're looking for is the minimum value on the right sub tree another way of looking at this is that basically we are looking for the inorder successor starting from the right child of the root node so we can do this we using the same function and this we should return the inorder successor for the node P so let's build up the pseudo code for the function for scenario one if the value of p is same as the value for roots we just call the same function but using the right child of root and we're looking for the inorder sucessor of p in a second scenario the value of p is larger than the value of root where is the inorder success for here in this scenario both p and the in order successor of P must be also in the right sub tree not including the root we can just discard this entire portion of the tree again we can call the same function find the in order successor starting with the right child of root now we can add scenario two to the PSE Cod for scenario 3 the value of p is less than the value of root so where is the inorder sucessor here well it should be in this part of the tree including the roots for example if you're looking for the inorder sessor three then is four if we looking for the know successor four then is the root itself hence we can discard this part of the tree and focus on the left hand side of the tree and the root node on the left hand side of the tree we can break this into two parts there is the left sub tree and there's the root node now one can imagine we can use the same in order successor function and we can search the successor in the left sub tree and if we don't find the inorder successor there we know the inorder successor must be the root node now we add scenario 3 to the pseudo code for the function now you can see that scenario one and scenario two are the same we can just combine these two and here because we're returning we can take out the else here so now we can use this and convert to real call in the language of your choice and test this Java implementation is available in the GitHub links below everything here is very similar to the P Cod I showed earlier we start with the base case this is very important if Roots equal no then return no I always include this line for all the recursive function I write for trees and this line here just covers scenario one and scenario two and these two lines covers scenario 3 before we test this let's talk about the runtime should be big all of height of the tree depends on what kind of trees we given if it's a unbalanced tree for example we can have a very long one-sided a very long one-sided a very long one-sided sube then the run times big all n that's why when I said earlier whether we can have a Improvement compared to the in order traversal solution it really depends on whether the tree is balanced now if the tree is balanced the runtime will be big all of L end now let's test see if this works and looks good next time we will do another question on inor successor of a binary search tree if you want to support this Channel please like subscribe leave a comment I will see you next time
|
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
|
286
|
welcome back everyone we're gonna be solving Lee code 286 walls and Gates so we're given an M by n grid called rooms initialized with three possible values negative one for a wall or an obstacle a zero for a gate and Infinity for an empty room we need to fill each empty room with the distance to its nearest gate if it's impossible to reach a gate we should fill it with infinity so we are going to use breadth first search to solve this and what we'll do is we'll initially Loop through our grid we will find all of the gate positions and add those positions into an array which will be used for holding the gates for further processing after we have those positions we will then run breadth first search on each of those positions and just update each empty cell accordingly so again breadth first search so we'll Implement Our Deck from collections uh first thing we need to do is create an array we will call it to process and we will Loop through our grid so we'll say for Row in range length of our grid and four column in range length of our grid at row zero okay once we've done that what are we going to do we're gonna check if Grid at the current row and the current column if that is equal to a zero it means it is a gate so what do we want to append that gate onto our processing array but we don't just want to append the row and column we're also going to want to give it an initial distance value of zero so we will say to process dot append the row column and an initial distance of zero so let's print out our two process array so we can see what we're working with and as we can see we have a gate at row 0 column two which is this one right here and we gave it an initial distance of zero so when we run our breadth first search from this gate the this cell will have a distance of one this one will have a distance of one right just like it has in the picture and we have another gate at Row three column zero which would be this one right here and then initial distance of zero so now that we have our gates inside of an array now we just have to run a breath for a search so we'll say four gate in two process what are we going to do we are going to run breadth first search so we will say Q dot append that gate actually we have to initialize a queue first so we'll say Q is going to be equal to a DQ with our gate on it and we are also going to have a visited set to hold all of the grid positions that we have visited already all right now we can run our breath first search so we'll say while the length of our cue is not equal to zero what are we going to do we are going to pop off the row column and the distance from our q dot pop left now what do we have to check and make sure that the current position we are at and make sure it is not a gate and not an obstacle so we will say if grid of row column if that is not equal to a gate and grid of row column is not equal to an obstacle what do we want to check and see if we can potentially update the distance how can we do that we will say if grid of row column if the distance value is less than the current value at that row column position right because if it's an empty cell it's filled with infinity so if distance is less than that we are just going to update the grid of the row column position to be equal to the distance now once we've done that we still have to check all of the other cells within our grid from that point right so how can we do that we need the next row down the previous row before whatever cell we're at and then we also need the right and left columns so we will have to check all right well if our row plus one right if that is greater than or equal to zero and less than the length of the grid that means we are we have a valid position within our grid for the row and we will have to do the same for the columns so if the column is greater than or equal to zero and less than the length of our grid at the first row so if this is true we also have to do something else we'll also have to check and make sure that okay well is the position of the next row current column is that invisited or not we want to make sure it's not invisited and we want to make sure the Grid at the row the next row of the current column is not equal to a gate and the Grid at the next row current column is not equal to a wall or obstacle right if this All Passes we're going to do something what are we going to do we are going to add the Row the next row current column to our visited set and we will add the next row current column and increase the Distance by one to our Q so we can process that next one so for this gate this first gate of 0 2 that means this cell right here would be one right we would append this cell onto our q and then go through the processing and we would hit this and we would turn this cell as distance to one right now we have to do the same thing for the other three directions so instead of going to the next row we want to check the previous row so instead of our plus one we will have our minus one everywhere here minus one now we need to check the next column so anywhere you see our plus one we can get rid of that all right plus one R plus one and our plus one now we need to check the next column so let's hit this one here and here it'll all change that to plus one now we need to check the previous column so let's change all of this to minus one and minus one okay so now we are not returning anything because we are doing this in place so we should be good to go let's run this invalid syntax what did I do here R plus one is less than the grid and aha right here column should be less than the length of our grid all right so let's rerun this again I probably did that everywhere too didn't I yep I did plus one like okay now we should be good awesome perfect so we pass up both test cases so let's submit this awesome and it does run so time and space complexity for this uh time complexity is going to be o of M times n where we are processing every uh cell within our grid and the space complexity is going to be the same we have to have every cell in our grid um onto our queue right all right that'll do it for leeco 286
|
Walls and Gates
|
walls-and-gates
|
You are given an `m x n` grid `rooms` initialized with these three possible values.
* `-1` A wall or an obstacle.
* `0` A gate.
* `INF` Infinity means an empty room. We use the value `231 - 1 = 2147483647` to represent `INF` as you may assume that the distance to a gate is less than `2147483647`.
Fill each empty room with the distance to _its nearest gate_. If it is impossible to reach a gate, it should be filled with `INF`.
**Example 1:**
**Input:** rooms = \[\[2147483647,-1,0,2147483647\],\[2147483647,2147483647,2147483647,-1\],\[2147483647,-1,2147483647,-1\],\[0,-1,2147483647,2147483647\]\]
**Output:** \[\[3,-1,0,1\],\[2,2,1,-1\],\[1,-1,2,-1\],\[0,-1,3,4\]\]
**Example 2:**
**Input:** rooms = \[\[-1\]\]
**Output:** \[\[-1\]\]
**Constraints:**
* `m == rooms.length`
* `n == rooms[i].length`
* `1 <= m, n <= 250`
* `rooms[i][j]` is `-1`, `0`, or `231 - 1`.
| null |
Array,Breadth-First Search,Matrix
|
Medium
|
130,200,317,865,1036
|
141
|
hello and welcome to another video in this video we're going to be working on a link list cycle and this problem you're given the head of a link list and you want to determine if the link list has a cycle and then you want to say true if it does and false if it doesn't and so you're given the head of a list then you're given this position thing and this is kind of telling you where the tail connects to the node but you don't really have to worry about it you can essentially Traverse it like a link list and then there would be some under the hood stuff to do that part so essentially you can treat it like a normal link list and basically you need to see if there's a cycle so in the first example clearly you can see a cycle and a cycle just means there's like a circular path so here there's one and here there's not so how would we do this right like let's say we have three 2 0 4 how would we determine if there's a cycle there's a few ways and some are better than others so obviously one thing you could do is you could just go through the list and you can maybe like store each node in a hashmap and then if you visit it again you would say if there's a cycle right so youd go through the list you start here and you would store because all these nodes are stored in memory they'd be stored in different memory so even if you have repeating values like if you store this node three and then there's another node three they would be stored at a different memory address so they wouldn't be equal so how do we like how would we do this and how would we do a better thing right so but yeah it's pretty straightforward essentially you just have a hash map and you just store the node so you're like at this node you store node three you're at this node you store node two in your hash map technically I guess you could store like a hash uh set probably but either way you would store zero you would store four then you would go back to two and you'd say like oh two is in my hash set so therefore I need to return it we're not really going to talk about this solution because this one is not as good now let's talk about something else so it tells you that there are 10 to the four nodes maximum so another solution you could say like okay well if there's only 10 the four nodes maximum why don't I just Traverse 10 four times or 10 the whatever 10 4 + 1 times and if there is whatever 10 4 + 1 times and if there is whatever 10 4 + 1 times and if there is a cycle then I'm just going to repeat like right so let's say I Traverse this to the four times I would just be going in a circle and if there wasn't a cycle I'd be out of bounds so that's another way you could do you could just say Traverse 10 to the you know whatever maximum thing you could do 10 4 plus one let's say and then if you get out of bounds ever then there is no cycle right CU you got to the end so you're literally just saying like it would be an example of you know let's say this is a road and the longest the road could be is like 10 miles right and there might be a loop in the road so you could just say like okay well I'm just going to go 10 miles and I either you know go in this Loop a bunch or I get out of bounds eventually because the longest the road can be is 10 miles so that could work but that's not the best solution but that could work right so essentially if you had no cycle you would just have a 10 mile road or a 10 to the fourth uh number of nodes and you just get out of bounds that could work but the problem is for something like this it would take 10 the fourth operations right which isn't great so yes technically you know that's the maximum it can take but it's always going to take that and this should only take like four or five so is there a better way and it turns out there is a better way and the way to there is actually a cycle detection algorithm and obviously if you haven't really heard of it's kind of hard to come up with on your own but essentially what you have is you have a slow pointer and you have a fast pointer and pretty much all you do is so let me draw these out different colors so let's say this is our slow pointer this is our fast pointer let's actually draw them out into different colors and let's actually draw them over here so I can erase them later so slow start at the same place fast they start at zero and you just have them go and then either one of them goes out of bounds the fast pointer right because so the fast pointer is going to move two nodes at a time and the slow pointer is going to move one node at a time right so the fast pointer will go like one two and so on and the slow pointer will move one and pretty much you just say let them keep moving and then if they ever intersect again then there's a cycle and if you think about it if you have a straight road and you have like two cars let's say and one's going 60 M hour and one's going 30 m hour obviously they will never intersect again if it's a straight road that just leads to the end but if it's a loop then they're both going to be in the loop and then they're going to intersect eventually right because one car is going faster than the other one so that's kind of like a good way to think about it right like if you have a road and this road is 10 miles and this car is one's going 60 and one's going 30 then they will never really intersect after the starting point the 60 mph car will just go faster and we'll get to the end but if it was five miles and then it was just like a five mile Loop right so five miles of Road and then a 5 Mile Loop that just kept going and going then yes the faster car would get there faster but eventually they'd both be in the circle and then the faster car would keep running into the slower car right it's like if you're on a track and one person's faster than the other you're just going to keep lapping him and mapping them right so that's kind of the same thing here so if we take a look they start here and let's just kind of walk through this so in the first uh iteration the vast pointer will move two right so it'll go here and then here so it'll be over here and the slow pointer will move over here right it only moves one and let's actually delete this now okay and so in the second iteration the fast pointer will move two again so it'll go one and then loop around here so the fast pointer will be over here we can delete this and the slow pointer will move over here right it'll only move one iteration so slow pointer will move over here and then one more so the fast pointer will move over here so I'm just going to draw in the same color just for the sake of time but fast pointer will move two and slow pointer will move one and now they have crossed right so that means there is a cycle and no matter what they're always going to cross like you can try this for all kinds of things but essentially they're always going to cross and if it was just a linear road with no cycle right if there was no if there was nothing here then the fast pointer would just always be ahead of the slow pointer and then it would just get out of bounds so that's kind of what you do is you just keep moving them forward and then if the fast pointer ever goes out of bounds then you have no cycle because obviously you can never be out of bounds in a cycle it just a circle and if they doesn't get out of bounds and they hit each other then there is a cycle so that's essentially what we're going to be doing so that's all we need and now we can code it up so essentially we're going to make a slow and a fast pointer they're both going to start at the head and there is a it looks like there is also a thing for no nodes to be in the list but we're going to account for this so that's fine so we're going to say let's just and here's a link list in here as it looks like right so it has a value and has a next but essentially we're going to say slow equals head so we can actually set slow fast we're going to make them both equal to head up the list and then we're going to say while fast and fast. next right because the fast mode will move up two nodes so in order for it to move up two nodes let's say it's here in order for it to move up two nodes the node after it has to exist right if this doesn't exist then it can't move up two nodes and then you'll be out of bounds right you can't say like fast do next because there is no fast. next so fast has to exist and fast. next has to exist in order for it to move up so we're going to say fast and fast. next then we're going to say fast equals fast. next and slow is only going to move up one and we never have to check if slow. next exists because fast should be way ahead of the slow so fast exists slow will always exist then we just check if fast equals slow if these are equal then we can return true otherwise if we have a break out of this Loop that means a fast ran out of bounds then we can return false and that's pretty much it so we just have a fast and a slow and the fast moves up two and the slow moves up one and if they're equal then you have a loop so let's try that and it looks like it worked and you can see it's pretty efficient as far as the space um yeah I mean maybe you could do this with like using not to node somehow yeah you definitely could do in one node with the thing that I suggested right where you just have one node and it just keeps going like 10 to the fifth times we can try that solution actually but like I said it's going to be slower on average so we can literally say like okay let's just say fast slow or whatever just like Cur equals head and then we could say like for I in range say 10 the 5th or 10 4th plus 2 or something right we just want to make sure we do it enough times and then we just say like if not Cur return false otherwise C equals c. next and then finally we can return true here as well so I think this should theoretically work yeah but you notice it's going to be a lot slower right so this is more space efficient because we're only using one node but this is a lot slower so we're going to go back to the other one but that's just another way you could do it to only use one node and there we go okay so this is going to be our solution and let's think about the time and space for this one so for the time we are essentially going through this list and we can go through it multiple times but we're not going to go through it like too many times this is still o n because yeah you could go through the looop a few times but it's still going to be like a you know roughly oen you're not going to go through like some quadratic number of times or anything you might have to go through this Loop yeah like a few times and you can try like bigger loops and smaller Loops you know but pretty much ENT time and for the space all we did was use a fast and a slow pointer which are just two variables they're not like arrays or anything and we're only going to use two regardless of the size of the list so if the list is like 10 to the fourth nodes we're still only going to have a fast and SLI so it's going to be o one times o n and yeah it's going to be it for this problem pretty easy one um but if you didn't know the Floyd St in the hair cycle detection thing it's definitely not something you can come up with on your own I would say but it's definitely good to know for other problems and you can also use this to figure out the entry point of a cycle and so on so if you want to look into that you can look into that like you can actually calculate where this cycle entry point is which I did do in some other problems um and you can also look into that okay but that's going to be it for this and 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
|
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
|
378
|
hey yo what's up my little coders let me show you in this tutorial how to solve the lethal question number 378 kate's smallest element in assorted matrix basically we're given an n by n matrix where each of the rows and columns are sorted in the ascending order and we need to return the gates smallest element in the matrix and also note guys that it's the gate smallest element in the sorted order not just for the gates distinct element here's one example right that's the input matrix i also have the initial representation of it as the input matrix since k is equal to eight so we want to return like the k smallest element it doesn't mean that you just take this matrix and then after that you just count one two three four five six seven eight oh here's the eighth element you just returned straight away no it doesn't work like that even though actually in this case the answer would be the same but the logic is a bit different you know this matrix sorted by rows and the columns but it's not sorted all the way through if you just iterate through it 1 5 9 10 11 13 yeah until this point is like perfectly sorted but after 13 you get 12 so it's only like rows and columns but not the whole matrix the idea is that if you take this whole elements from this matrix and if you just sort them in this case yes you can take the eighth one and just return it after that would be like the one of the ways to solve this problem but yeah anyway i think it's clear now what we need to do however it's not clear probably if you're watching this video how to do it right let me first of all start with the brute force solution and i will quickly explain it and after the brute force one i will move to it more better way of solving this problem as well let me just write the code now okey dokey my little coders here's our brute force solution it's a very simple one i have a picture for that first of all we just create one dimensional array to store all the values from the matrix initially all the values in one dimensional array would be equal to zero when we created then after that would iterate through all the elements from the matrix in the same order as they appear we would put all these elements at the right indexes to the one dimensional array here we go after we've done that we would sort this like one dimensional array and in the end we just would return the case element from it right and this would work but let me actually submit it yeah it would pass all the test cases however it's a brute force solution and it can be improved a bit and one of the ways to improve the solution is to use the binary search if you're not sure how to use the binary search in this case and you want to figure out that and you want to understand that just stay with me i will quickly write the code now and then i will go through it with you in more details alright let me explain you what will be like the better way of solving this problem using the binary search which will be more efficient first of all by the definition of the matrix because all the rows and columns are sorted we definitely know that the minimum element in this matrix will be located at index 0 that's why we defined it here and also we know that the element at the bottom right would be the maximum element in this matrix this is because the rows and columns are sorted we also define it here then while the mean is not equal to max we'll perform some binary search here and to perform the binary search of course we need to first of all get the middle element and the middle element is equal to the mean plus the max minus min in the brackets divided by two and on the first iteration it will be equal to eight and sometimes the same mid element it might be presented in the matrix but sometimes it will not be in this case we don't have the element which is equal to eight right so it's just like the mid between the min and max not like the exact element from the matrix but okay you will understand why it works in this way just in a few minutes keep watching guys after that you will count right you will take the mid element and we would count how many elements before this like mid value are less for equal than this mid element you would go inside this function here it is which is called countless or equal then first of all we would define some variables so the count to just like keep track how many elements are less than the middle one less recall then the comb initially we would consider the most right comb right like in this case it will be this column and we will start with the first row then we would go inside the while loop and while the row is less than the length of the matrix and at the same time while the column is like greater or equal than zero which means that like while we are still inside the matrix and not outside the matrix you will perform some operations here the first one would be to check if the current value so nine right if it's less or equal than the mid value which is like eight nine is not less or equal than eight that's why we would not go inside this if statement we would go inside the else statement and we would decrement our column right so now we would consider only this column because we checked this value and because the columns are sorted it means that all the elements below this value all the elements in the same column the oldest value they cannot be else less or equal than the mid value because they will be definitely greater than this element that's the yeah we basically decrement the column and now we will consider this element and here we go five is actually a lesser equal than eight right so we'll go inside this if statement and we can update our counter and we don't just say like counter plus one you can say counter plus the column and then plus one because basically if this element is less riku than the mid value we know that all the elements in this row all the elements on the left side would be elsa lesser equal than the mid value we can just like take all of them and after that go straight away to the next row right that's what you would do then this element it's not less record in the mid value so we decrement the column then 10 is not less frequent than the mid value so we decrement the column and yeah here we go we went outside the matrix this condition because the column is equal to -1 now this condition is equal to -1 now this condition is equal to -1 now this condition doesn't work anymore so we would go outside the value and it would return our count is equal to 2 which means that like two elements in this matrix are less or equal than the mid value right perfect having this count value we can check something right if the count is less than the k value so if you found less elements than the k value and in this case we actually did because count is equal to two and k is equal to eight in this case we can update our minimum right because there's no point to consider anymore the mid value is the which is equal to eight because we definitely know that like this mid value will not give us a right answer because they're just like only two elements less than this mid value it means that we can increase our mean value so that like in the next iteration our mid value would increase as well that's why we just update the min value now it would be equal to nine which will mean that like and we'll go on the next iteration of the while loop we would have a new mid value which would be equal to 12 and the mean value here it would be equal to nine now not the one okay so now we can basically check how many elements are less or equal in the matrix given a new updated mid value you would go inside this function again basically you know this logic would give a six to us because there are six elements which are less than or equal than the mid value and here having that we would check if the current count value is less than the k so six is still less than k that means that's okay we need to increment our mean value again because we need to go further so we increment it and now it becomes 13 so we would consider another range right we would go on the next iteration of the while loop and now basically we already reduced the problem a lot so right now our minus 13 our max is 15 so basically we have only three candidates for the answer right so we're close already but you know not there yet okay having this like three elements minus 13 minus 14 max is 15 again you would go inside the count we already like know me and you know that for example because we know the answer right the answer should be thirteen we know that for example uh a number which is equal to fifteen it would it's like the ninth element but because 14 is not presented in our matrix it still would be like the eighth one because the mid is 14 and in theory even though we don't have it in the matrix it's like the eighth element but the answer should be 13 right because we don't have 14 in our matrix so let's see what the program will do with that basically we would go again inside this wake function now we will see that oh actually there are now eight elements which are less or equal than the mid value which means that okay there's no point to consider this element but now we would not update the mean value we would update the max value right now max will be equal to 14 not the 15 anymore and now we will go in the next situation of the while loop and now we will just consider two elements 13 and 14 even though we know that yeah we don't have 14 in our matrix let's to see how the program will sort it out so okay having that we have a new mid element which is equal to 13. you would go inside this function again here we will see that okay actually there are eight elements which are less record than the k perfect in this case we would update our max value so now it will be equal to the mid element so now it will be equal to 13 and in this case the min right now 13 is equal to the new max 13 so in this case we would go outside the while loop and would return the mean value or else we can enter the max value doesn't matter because this while loop only breaks when the min and max are equal so in this case we would return our answer and yeah this is how it works guys let me just run it works let me submit yeah as you can see here now the runtime is zero millisecond it's like better than with the brush resolution and this way is more efficient than the brute force solution so if you enjoyed this tutorial guys please give it a like and subscribe challenge your friends to see if they can solve this question efficiently or not and i will see you next video guys good luck
|
Kth Smallest Element in a Sorted Matrix
|
kth-smallest-element-in-a-sorted-matrix
|
Given an `n x n` `matrix` where each of the rows and columns is sorted in ascending order, return _the_ `kth` _smallest element in the matrix_.
Note that it is the `kth` smallest element **in the sorted order**, not the `kth` **distinct** element.
You must find a solution with a memory complexity better than `O(n2)`.
**Example 1:**
**Input:** matrix = \[\[1,5,9\],\[10,11,13\],\[12,13,15\]\], k = 8
**Output:** 13
**Explanation:** The elements in the matrix are \[1,5,9,10,11,12,13,**13**,15\], and the 8th smallest number is 13
**Example 2:**
**Input:** matrix = \[\[-5\]\], k = 1
**Output:** -5
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 300`
* `-109 <= matrix[i][j] <= 109`
* All the rows and columns of `matrix` are **guaranteed** to be sorted in **non-decreasing order**.
* `1 <= k <= n2`
**Follow up:**
* Could you solve the problem with a constant memory (i.e., `O(1)` memory complexity)?
* Could you solve the problem in `O(n)` time complexity? The solution may be too advanced for an interview but you may find reading [this paper](http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf) fun.
| null |
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
|
Medium
|
373,668,719,802
|
454
|
el. address tutorial for basic for interface us suan us story mode of the pools of us weekly and that force one in the input and for sale in hand made for her them, etc. the one here it is one is for pure and Libra af-1 for in the hydra pure and Libra af-1 for in the hydra pure and Libra af-1 for in the hydra cell double agent one for her and ensure that you guys and footbed for each package interface and check if you intend to for their sake caught it here posted with Kay recession and files admit you get the time out exception here are 7 seconds I his ears ocean fishing and power for sale in white and black and white and let me show and the hulk blows kais actually like a sorcerer she chats in ligature luxury singing and bad thing to stay with me guys okey-dokey prayers to the beat of the heart road to okey-dokey prayers to the beat of the heart road to okey-dokey prayers to the beat of the heart road to force of all we define us out war ii would be created was the whole world Mr. Turnbull which are going to incoming we find hanging ward queiris went half baked himself of that we define b-hush on and naviny.by of that we define b-hush on and naviny.by of that we define b-hush on and naviny.by ft island of one wants to put on inside a nightmare with such a connection and I’ll decide it myself connection and I’ll decide it myself connection and I’ll decide it myself forbes us Sloane simple and mike osmosis itself mars one in plasma news and plasma Ruslan and the path without Samsin Sabiha Schnapsu if i have seen by four and effort you put Iseru model in mind plos one here in distress here we have agreed by one zero people here by one which is one i put on her right one and basic and in the way here and files of the forums and for all stories and her update from the site via otg you dh map exist in ten in old & wise old & wise old & wise this is a fact and goats one offender nightmare - - one of the key nightmare - - one of the key nightmare - - one of the key insides already map and her nice if this is an act one zero people in disk d times one can dance now if i feel and one for other people to zero dan balan Indian one end of nations and for a cage map and himself and forex place with a vulture gas went bought Indian Internet name if not and default seconds and Zaire they autour des for upskirt after all Andrey name is sample Oersted guys in from the sword of the country know if it works whom give here mi soo bin guys he learn from experts and simply is bad guys if you enjoy this tutorial close of 9 consumes caleb than the hell francis bacon soldier cord not and his sex video gans co2
|
4Sum II
|
4sum-ii
|
Given four integer arrays `nums1`, `nums2`, `nums3`, and `nums4` all of length `n`, return the number of tuples `(i, j, k, l)` such that:
* `0 <= i, j, k, l < n`
* `nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0`
**Example 1:**
**Input:** nums1 = \[1,2\], nums2 = \[-2,-1\], nums3 = \[-1,2\], nums4 = \[0,2\]
**Output:** 2
**Explanation:**
The two tuples are:
1. (0, 0, 0, 1) -> nums1\[0\] + nums2\[0\] + nums3\[0\] + nums4\[1\] = 1 + (-2) + (-1) + 2 = 0
2. (1, 1, 0, 0) -> nums1\[1\] + nums2\[1\] + nums3\[0\] + nums4\[0\] = 2 + (-1) + (-1) + 0 = 0
**Example 2:**
**Input:** nums1 = \[0\], nums2 = \[0\], nums3 = \[0\], nums4 = \[0\]
**Output:** 1
**Constraints:**
* `n == nums1.length`
* `n == nums2.length`
* `n == nums3.length`
* `n == nums4.length`
* `1 <= n <= 200`
* `-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228`
| null |
Array,Hash Table
|
Medium
|
18
|
31
|
today we will solve leak code 31 this code demonstrates the next permutation algorithm which generates the next lexicographically greater permutation of a sequence of numbers the function NP takes a vector of integers and implements the logic it begins by finding the first index I from the right where the sequence stops being in descending order then it identifies the rightmost element larger than the value at index I these two elements are swapped finally the sequence from index I +1 finally the sequence from index I +1 finally the sequence from index I +1 onwards is reversed to create the smallest possible permutation after the swap in the main function a vector is used as an example it's printed before and after calling the NP function to showcase the permutation change this code efficiently computes the next permutation
|
Next Permutation
|
next-permutation
|
A **permutation** of an array of integers is an arrangement of its members into a sequence or linear order.
* For example, for `arr = [1,2,3]`, the following are all the permutations of `arr`: `[1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1]`.
The **next permutation** of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the **next permutation** of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).
* For example, the next permutation of `arr = [1,2,3]` is `[1,3,2]`.
* Similarly, the next permutation of `arr = [2,3,1]` is `[3,1,2]`.
* While the next permutation of `arr = [3,2,1]` is `[1,2,3]` because `[3,2,1]` does not have a lexicographical larger rearrangement.
Given an array of integers `nums`, _find the next permutation of_ `nums`.
The replacement must be **[in place](http://en.wikipedia.org/wiki/In-place_algorithm)** and use only constant extra memory.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[1,3,2\]
**Example 2:**
**Input:** nums = \[3,2,1\]
**Output:** \[1,2,3\]
**Example 3:**
**Input:** nums = \[1,1,5\]
**Output:** \[1,5,1\]
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 100`
| null |
Array,Two Pointers
|
Medium
|
46,47,60,267,1978
|
111
|
question one of leaked code minimum depth of binary tree so given a binary tree find its minimum depth the minimum depth is the number of nodes along the shortest path from root node down to the nearest leaf node a leaf is a node with no children so we have this tree here nine for example is going to be pointing its children are gonna be pointing to null so that is a leaf node so we need to find the shortest path so in this case the minimum depth would be three and nine so that would be two now there are a number of different ways that you can solve this when a question asks for the minimum depth or the shortest path we think of breadth first search so let's look into that solution so with breakfast search we have a queue so first in first out basis we'll have a current which we use when we shift off of q and we'll also have a minimum depth which we can initialize as one so with breadth of search we go level by level so we look at this level then we go to this level and then finally we go to this level but what's going to happen here is once we reach this level we'll check to see if the children are both null in the case of this and if it is then we're just going to return min depth at this position so it makes this solution much more optimized and it's counterpart dfs so let's walk through this one and see how it works out so we're at this level we push three into q we check to see if there are any more values in this level there aren't so now we can start shift q we pass three into current we check currents children so we check left and right we pass those values into q and then that's this level done so we can remove current there we can increment min depth by one so that will go to two and remember the initial minimum depth is one because that accounts for this level we've just moved on to this level so we need to increment here so this needs to be two so that's why we have min depth initially set to one now with breakfast search in this case what we're going to do with our solution is we're going to go from we're going to check left and then right so we check left child so this comes out of q goes into current we check its children at this point to see if they're both equal to null in this case they are both equal to null so we can just return minimum depth because there's no need to go down the right side of the tree the minimum depth has already been found so that's the basic idea of dissolution with regards to time and space complexity time complexity is on where in the worst case we have to traverse the entire tree and space complexity is also on because we have to store the values of this tree within the queue so firstly we do a sanity check to check whether root is initially set to null and if it is we can return zero because we know the min depth will be zero we initialize min depth as one because we want to take into account the first level we initialize q with root and then we can carry out our bfs solution here so while q dot length is equal to true so there is something within q so basically what we're doing here is we're going to be looping over the tree then we need to loop through the levels so we need to create another while loop so while level size is true so whilst there is a value within the level we can grab the current value which is going to be q dot shift we say shift because bfs is first in first out so it's going to be push and shift if current dot left is equal to null and current dot right is also equal to null and we can return min depth so we're setting the condition here that checks the child or checks both the children of the current node and we check to see whether those are equal to null and if it is then that is a leaf node so the first leaf node we come to is going to be the end of this solution so we can return min depth at this point else if there is a child within the left subtree or if there was a child within the right we can just push that into q and carry out the process then we need to decrement level size here because we're using a while loop we don't enter an infinite loop and outside of level size while loop we need to increment min depth and finally we can return min let's give this go it's been accepted let's submit it and there you have it
|
Minimum Depth of Binary Tree
|
minimum-depth-of-binary-tree
|
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
**Note:** A leaf is a node with no children.
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** 2
**Example 2:**
**Input:** root = \[2,null,3,null,4,null,5,null,6\]
**Output:** 5
**Constraints:**
* The number of nodes in the tree is in the range `[0, 105]`.
* `-1000 <= Node.val <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
102,104
|
230
|
welcome back everyone we're gonna be solving leeco 230 kth smallest element in the BST so we're given the root of a binary search tree and an integer K we need to return the kth smallest value one indexed of all the values of the nodes in the tree so example one right we're given this tree of three one four and two with a value of K so the first smallest element in the tree that we come across is going to be one right so how well let's take a look at example two because we have an output of three for example two we have a k of three and three is the third smallest value in the tree right it goes one two and then three so how can we solve this well we can use uh depth first search to solve this and what we're going to do is we'll Traverse the tree but we're going to Traverse the tree uh doing an in-order traversal when we uh doing an in-order traversal when we uh doing an in-order traversal when we do an in-order traversal we'll start do an in-order traversal we'll start do an in-order traversal we'll start here right we'll start at the leftmost sub tree and we'll keep going up so doing an in order traversal on example two we'll get one two three four five and then six so now that we know how to do the inorder traversal right I just told you how the nodes are going to pan out in this traversal we can just take K right and every time we move up we'll just subtract 1 from K and then whenever K is equal to one that means we found the node that we're looking for and we can just return the value so let's get our first search set up we know it uses a stack so we'll say stack is equal to an array on this array is going to be the root and a visited status of false initially and we only have to return the node value so we don't need an output array so we'll say well the length of our stack is not equal to zero what are we going to do we're going to grab the node and the visited status with stack.pop now we're going to check with stack.pop now we're going to check with stack.pop now we're going to check if our node is not none what are we going to do we're also going to check if the visited status is true so if visited is true then we want to do something what do we want to do well we want to check to see if K is equal to 1. so we'll say if K is equal to 1 if it is then we can return the node so we could say return node.val say return node.val say return node.val otherwise what are we going to do it means we're not at the node so we have to decrement K by one right so we'll say k minus equals one okay now if we have not visited this node what are we going to do we'll say else and we will say if node dot right is not none right we have to check the children well do a stack dot append the node dot right along with a visited status of false initially now here we can append the node and visited status of our original working node right this is going to be in order so in order has to go before we do the left side so we'll say stack dot append the current working node and we will change the visited status to true now we can check the left child so if node to the left is not none we are going to say stack dot append node.left along with a visited status of node.left along with a visited status of node.left along with a visited status of false so that is the entire code for this problem so let's run this perfect we pass both test cases so we'll submit awesome and it does run so uh time and space complexity time complexity is going to be o of n for this problem and the space complexity is also going to be o of n right we have to Traverse at most all of the nodes in the tree and our stack can grow to the height of our tree all right that'll do it for Lee code 230.
|
Kth Smallest Element in a BST
|
kth-smallest-element-in-a-bst
|
Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_.
**Example 1:**
**Input:** root = \[3,1,4,null,2\], k = 1
**Output:** 1
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,null,1\], k = 3
**Output:** 3
**Constraints:**
* The number of nodes in the tree is `n`.
* `1 <= k <= n <= 104`
* `0 <= Node.val <= 104`
**Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
|
Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).
|
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
|
94,671
|
252
|
another day another problem solid solve hello guys I hope you are all doing well today in this video we'll show you how to solve one of the premium problem meeting rooms so let's get started so the problem gave us an array of meetings times interval consisting of start and end times and they ask us if the person can attend all the men so let's say we have to array each array has two values the first value is the time that the meeting store and the second value are the time that the meeting ends so for example the meetings start at 7 00 am and end at 7 00 am and the second meeting starts at 2 pm and end at 5 PM so in this example the person can attend the two meetings but what if we have the first meeting start at nine and end at 6 pm and the second amazing start at 2 pm and end at 10 pm so here the person cannot attend the two meetings so this problem is referred as interval scheduling problem means when we have a period of time between two events and those two events interrupt each other others so how do we gonna solve the problem so we're going to use a Grady algorithm technique to check if either there is any conflict between the two marine or the three meetings and we're going to return false indicating that is not possible to ascend all of the meetings otherwise we will return true after iterating throughout the lists of amazing and the Canon that is possible to attend all of the meetings so let's say we have this import list of meeting times first we take all the missing start time and put them inside one list and sort them and also we take all the meeting ends time and sort them in an ascending order then we're gonna iterate throughout the sorted list of the start time because we want to attend the meeting with earliest start times to check if we can attend the earliest meeting each at each iteration so we check if the star of the second mirroring does not conflict with any previous or next meeting so here we have the start of the end of the first minute at 3 pm and the second meeting starts at 2 pm means we cannot Ascend the two meetings so we turn false so that's it guys uh I think it's easy problem not a hard problem so let's jump at coding the solution so first we create a two empty list start at the end to start that to start the start and the end time of the meetings and we iterate over the intervals less with the for Loop and for each iteration extract the start and end times of the current meeting from the sub array and append them to the start and end list after that we sort the start and endless in ascending order we accurate over the star list with another for Loop so for each iteration we check if whether the start time of the next mission is before the end time of the curing mirroring if it's true we return false indicating that it is not possible to attend all of the meeting complete without returning false will turn through at the end of the function to indicate that it's possible to attend all of the meeting so the time complexity is often login because the function performed two Mains operations that have a Time complexity of often in Logan first we sort the start and add less using the Bolton Source function and we iterate over the start list with a for Loop the acceleration have an often time complexity and the sourcing algorithm take off and login so in complexity analysis we know that we drop the less significant terms mean we dropped off and we keep off and login so the space complexity of the function is often because we create two lists start and end with the size of n to store the start and the end times of the meetings so that's it guys I hope you find this video helpful subscribe like and comment thanks for watching see you in the next video
|
Meeting Rooms
|
meeting-rooms
|
Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** false
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** true
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 106`
| null |
Array,Sorting
|
Easy
|
56,253
|
785
|
hello guys now I try to solve the is graph bipartite even an undirected graph return true if and only if it's a bipartite we call that a graph is bipartite if we can split its set of nodes into two dependent independent success a and B such that every edge in the graph has one node in a and an anode in P the graph is given following from graph I is a list of index J for which the age between notes inj exists each node is an integer between 0 and the graph lensman minus 1 there are not self age of parallel edges graph I does not contain and it's done content and the elements toys actually this program is easy but only after you understand what the graph is represent rent dented let us see their input what does this input mean actually it means there is ages between 0 & 1 means there is ages between 0 & 1 means there is ages between 0 & 1 in between 0 & 3 because 0 is the index in between 0 & 3 because 0 is the index in between 0 & 3 because 0 is the index and which means such a this is index 0 right these elements means the nodes have edges between the index and this node so they can see 0 & 1 head H 0 this node so they can see 0 & 1 head H 0 this node so they can see 0 & 1 head H 0 and the 3 had H and this the index is 1 right 1 heading the shoe index with 0 & right 1 heading the shoe index with 0 & right 1 heading the shoe index with 0 & 1 heading decks which I have aged with too so now you understand how this graph it works down here we can do it by coloring or try to color in the notes how because if you can color this graph into two colors such as blue and red you can split this graph into two you know para tight that's the idea so how to do that we can use BFS above BFS or DFS and in this solution we use DFS I will try to color the node if we take an color such as we can cut into blue then we will try to colorize neighbors into rate if we cannot color them which means this cannot be split into two parts which means they cannot is not bipartite okay so we need them first knows how many nose is graph here okay it's nodes and we will try to color them right colors internodes okay and the for enjoying choose there are less than notes I press pass okay if colors I equal to 0 which me no haven't color this node and TFS bra colors we will try to cut it into one which means red and the blue will be negative one and this note is alright if we cannot correct we just return fourth and finally will return true ok let's write the TFS boolean TFS this will be graph and this will be colors this will be the color and this will be the node okay if the nodes the null have been color not equal to 0 will just return this color if the same color as the color we want to call it yeah to ask them if we have cut this node before it is should be the color data I want you collide okay else if having a bean color I will cut this node into the color okay then for inter neighbor would be the graph no which means to the neighbors we will try to collect it into another color right DFS graph but we just use negative color which I mean opposite color and the neighbor okay if we cannot collect right with just a return for if we can color all these notes we sink retention okay so yes will be done okay thank you for watching happy coding
|
Is Graph Bipartite?
|
basic-calculator-iii
|
There is an **undirected** graph with `n` nodes, where each node is numbered between `0` and `n - 1`. You are given a 2D array `graph`, where `graph[u]` is an array of nodes that node `u` is adjacent to. More formally, for each `v` in `graph[u]`, there is an undirected edge between node `u` and node `v`. The graph has the following properties:
* There are no self-edges (`graph[u]` does not contain `u`).
* There are no parallel edges (`graph[u]` does not contain duplicate values).
* If `v` is in `graph[u]`, then `u` is in `graph[v]` (the graph is undirected).
* The graph may not be connected, meaning there may be two nodes `u` and `v` such that there is no path between them.
A graph is **bipartite** if the nodes can be partitioned into two independent sets `A` and `B` such that **every** edge in the graph connects a node in set `A` and a node in set `B`.
Return `true` _if and only if it is **bipartite**_.
**Example 1:**
**Input:** graph = \[\[1,2,3\],\[0,2\],\[0,1,3\],\[0,2\]\]
**Output:** false
**Explanation:** There is no way to partition the nodes into two independent sets such that every edge connects a node in one and a node in the other.
**Example 2:**
**Input:** graph = \[\[1,3\],\[0,2\],\[1,3\],\[0,2\]\]
**Output:** true
**Explanation:** We can partition the nodes into two sets: {0, 2} and {1, 3}.
**Constraints:**
* `graph.length == n`
* `1 <= n <= 100`
* `0 <= graph[u].length < n`
* `0 <= graph[u][i] <= n - 1`
* `graph[u]` does not contain `u`.
* All the values of `graph[u]` are **unique**.
* If `graph[u]` contains `v`, then `graph[v]` contains `u`.
| null |
Math,String,Stack,Recursion
|
Hard
|
224,227,781,1736
|
669
|
welcome to february's leeco challenge today's problem is trim a binary search tree given the root of a binary search tree and the lowest and highest boundaries as low and high trim the tree so that all its elements lies within low and high trimming the tree should not change the relative structure of the elements that will remain in the tree and it can be proven that there is a unique answer return the root of the trimmed binary search tree so it also says note that the root may change depending on the given bounds so the very first thought might be to just traverse our tree however and if we find that the node is not within bounds we could just get rid of it make it a none and that would work for something like this but what about a tree that looks like this if we just set this to none and returned we would be losing the 2 1 here so think about how a binary search tree is structured we know that everything on its right is greater than the node value and everything to its left is less than its value so what we might do is check at the node value to see if it's within bounds if it's lower than the lowest bound then we want to get rid of this node but return everything to its right now everything to its left we know that we can get rid of those because every if it's if this number is less than the lowest bound then we know everything to its left is also out of bounds but we don't know about the right so what we'll have to do is return the rights node value if it exists and just do this recursively and it should take care of the algorithm so what we'll do is traverse our binary search tree check to see if it's within balance if it's less then we will return everything to its right uh if it's greater than the highest bound we'll return everything to its left and we'll return the let's say the parent node and it's almost like you're considering this to be the new root so we'll just keep returning the root whatever that may be so what i'll do is write a helper function with that first search we just need to pass in the node value so typical thing is if not node we just return none otherwise we want to set the left and right so we can say node.left is going to be equal to node.left is going to be equal to node.left is going to be equal to whatever gets returned by no dot left and node.right is equal to and node.right is equal to and node.right is equal to everything that's whatever is going to be returned by node.right be returned by node.right be returned by node.right now we want to check to see our conditions so if the no dot value if it's less than low what we want to do we want to return everything on its right otherwise if it's greater than high we want to return everything to the left otherwise just return the node and this should take care of the restructuring of the tree while we're traversing it so finally we just need to return whatever gets returned here with the root let's make sure this works okay that didn't work uh let's see trying to stop roots all right i have to return the node silly me okay so that looks like it's working let's go and submit it and there we go accepted so with time complexity of n and um i guess space complexity is also of n because we're doing recursion um there are some other ways you can do this but this was the solution that i came up with and i was very happy to see that it was exactly the same as the solution given to us so all right thanks for watching my channel and remember do not trust me i know nothing
|
Trim a Binary Search Tree
|
trim-a-binary-search-tree
|
Given the `root` of a binary search tree and the lowest and highest boundaries as `low` and `high`, trim the tree so that all its elements lies in `[low, high]`. Trimming the tree should **not** change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a **unique answer**.
Return _the root of the trimmed binary search tree_. Note that the root may change depending on the given bounds.
**Example 1:**
**Input:** root = \[1,0,2\], low = 1, high = 2
**Output:** \[1,null,2\]
**Example 2:**
**Input:** root = \[3,0,4,null,2,null,null,1\], low = 1, high = 3
**Output:** \[3,2,null,1\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `0 <= Node.val <= 104`
* The value of each node in the tree is **unique**.
* `root` is guaranteed to be a valid binary search tree.
* `0 <= low <= high <= 104`
| null |
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
| null |
271
|
hello friends we are not employed by a fan company so let's not stop lead coding till we get there today we are going to do encode and decode strings lead code problem and as you can see this is actually a lead code premium problem if we see some of the companies who have already asked this question where i want to get a job there are companies like facebook linkedin google square uber microsoft and apple so all of my favorite companies have asked this question so that's why i'm paying my utmost attention i hope you also enjoy the video so this is the lead code medium problem and basically we are given a list of strings now we need to design an algorithm where we are actually encoding this given list of strings into a single string then we are told that single string is supposed to be sent over a network and then when we get back to the second machine we need to decode that given string into the original list of strings so let's try to understand this with an example so suppose we are given a string s where we are given bunch of different strings that looks like this so after this we will actually create an encoded string now this encoded string is combination of all of these four items and it is just a single string so let's say that this is the encoded string we have created now after getting this encoded string we need to write a function to decode the string as well and after we decode the string we should get a response that exactly looks like this and this would be the original decoded string we would get and this is what we need to return so we need to return the algorithm to encode the string and also an algorithm to decode the string so let's see that what would be the different approaches we can take okay suppose this is the original string we are given and we need to encode the string and decode the string the idea is we are actually going to use an extra character and where we are going to use an extra character we would put it where one string ends before other string starts and we will keep on repeating the same process and all we have to do is so that would be the way to encode the string after encoding the string when we have to decode we will just simply take that character and the moment we reach that particular character we would know that okay this is the place where one string ends so we would create a new string for that and then we will repeat the same process so let's see that in action so first of all suppose we take this character that looks like this hash right i'm just taking any random character the idea is you can discuss with your interviewer that what kind of character you can take so suppose i take this ash now i do encoding string so the encoded string is going to be a b then uh the moment i identify that the strings ends over here i would put a hash and i would keep a continuous string now i realize that okay this is a new string b so i would add a value b again i would put a hash now again this value is c again i would put a hash and again at the end i would find this value abc and that would be the end of the string so now i have created an encoded string now if i want to decode the string uh the decoding would work like this so first of all i am iterating until i find that this is a valid string so valid string is a b now i realize that okay this is the hash and hash is the character that i put it x as an extra character as an encoding mechanism so i would remove this hash and i would treat this as a single string now i would again start creating a new string so again i find this value b the moment i encounter the string hash i would read this b to be a separate string again i would encounter this value c and again i would encounter this value abc and this is the way we will we are going to encode and decode the string and this solution would work as expected if we see the time complexity in this case the time complexity is actually going to be big o of n why because we will have to iterate over all the characters that are present inside this given string s to n first of all encode and then d code so overall it would be 2n but we can generically write it to be big o of n now if we see the space complexity in this case the space complexity is actually not that much because we anyways we will have to create an encoded string and decoded string and all we are doing is just using an extra space to solve this problem so this is pretty simple to me okay suppose this is the string we are given and the idea is we are actually going to add four bits that are going to store the length of any given uh sub substring and then we are going to keep on repeating the same process and we are going to create the encoded string so let me quickly show you what i am suggesting first of all we would have an encoded string where first four character is actually going to store the information that what is the next length of substring that is coming that we are going to iterate over so in this case this is actually length 3 so if we add it in binary it's represent as 0 1 so we are actually going to have 0 1 to be the length and then we are going to store these three characters as a b c okay now we are done with that again and now this ends this first substring so now this is of length two so length two becomes zero one zero now we are going to do the same thing and then we are going to store this value a b and now this is also of length 2 so again we will repeat the same process and we are going to store the value of x and y and this is the encoded string what we have done basically is we have actually created block of four bits that keeps the information that okay in the next subsequent value these are the three characters that you will have to iterate over and that is how we are going to decode it so let's see the decoded string in action in the decoded string first of all we are going to iterate over this given encoded string now we iterate over these four characters and we find that okay value is actually three which means that next three characters are the characters of one of the substrings that we will have to separate so we will iterate over these three and put it in a substring and we will get a substring like abc again we will iterate over these four characters and we realize that the value is actually two so because two we will have to iterate over these two elements and we would get the value a b now again we would iterate over this next four bits and we find that value is actually three or two again so we will iterate over two more characters and we will get the value x y and then we would have a decoded string so this is also another way to store all the values now this solution also works as expected but i don't think that anyone is able to come up with this in the interview so i just showed you this approach just for the explanation purposes but actually i'm going to in the coding i'm going to show you the first approach that i solved earlier so first of all we are going to do the encode function so lets take care of some edge cases first if that is not the case we are actually going to take a random variable that is not part of this original given string so we are given the condition that there could be 256 characters uh inside the ascii character for this given string i so what we are going to do is we are going to take the 257th character as the character that is a separator between any two strings so first of all let's just create a string called a separate and we are going to assign the character 257 to it now we will start building our string now we will iterate over this given list of strings so first of all we are going to append the value of whatever the string we are iterating over and the moment the string ends we are going to add the separate character once this loop ends basically we should have done with encoding our string now all we have to do is just delete the last character because that would be an additional room and once that is done all we have to do is just simply return this given just new string builder we have created so now we are done with encoding our string let's decode our string if this given string s is actually of size uh whatever the located at 258 which means we are dealing with an empty string list so in that case we will simply return a new error list and we should be done if that is not the case which means that we have a separated string so let's just assign a new character all we have to do is just return an error list where we are going to separate based on this given separate character and that's it let's try to run this code okay seems like our solution is working as expected let's submit this code and our solution is actually pretty fast compared to a lot of other solution it's not most optimal because i did not choose the approach to and let me know if you want to see the code for approach 2 as well thank you
|
Encode and Decode Strings
|
encode-and-decode-strings
|
Design an algorithm to encode **a list of strings** to **a string**. The encoded string is then sent over the network and is decoded back to the original list of strings.
Machine 1 (sender) has the function:
string encode(vector strs) {
// ... your code
return encoded\_string;
}
Machine 2 (receiver) has the function:
vector decode(string s) {
//... your code
return strs;
}
So Machine 1 does:
string encoded\_string = encode(strs);
and Machine 2 does:
vector strs2 = decode(encoded\_string);
`strs2` in Machine 2 should be the same as `strs` in Machine 1.
Implement the `encode` and `decode` methods.
You are not allowed to solve the problem using any serialize methods (such as `eval`).
**Example 1:**
**Input:** dummy\_input = \[ "Hello ", "World "\]
**Output:** \[ "Hello ", "World "\]
**Explanation:**
Machine 1:
Codec encoder = new Codec();
String msg = encoder.encode(strs);
Machine 1 ---msg---> Machine 2
Machine 2:
Codec decoder = new Codec();
String\[\] strs = decoder.decode(msg);
**Example 2:**
**Input:** dummy\_input = \[ " "\]
**Output:** \[ " "\]
**Constraints:**
* `1 <= strs.length <= 200`
* `0 <= strs[i].length <= 200`
* `strs[i]` contains any possible characters out of `256` valid ASCII characters.
**Follow up:** Could you write a generalized algorithm to work on any possible set of characters?
| null |
Array,String,Design
|
Medium
|
38,297,443,696
|
1,799
|
okay so welcome back in this another daily go prom so today it's called maximum score after n operations and it's a hard level dynamic programming problem and so basically you're given an array here with a list of like n different numbers and you want to calculate the maximum score that you can receive after like n operations now at every step an operation is basically you select any two numbers within the array can be like at any index and you want to take the greatest common denominator of those two numbers and to do that like if it's an easy level problem typically you have to actually like write out the code to implement it but in this case since it's a hard level problem and the whole point isn't really to create that or to like create that method you can just import from the math Library um like the actual greatest common denominator uh function Okay so from there you want to actually multiply at every step when I once you calculate degrees common denominator between those two numbers you just multiply it by the current operation that you're on and it starts with one and so when you say if you grab one and five in this case one and five you calculate the greatest common denominator then you multiply it by one since that's the first operation that you just did but when you grab the second pair of numbers say two and four then you multiply it by two and do the next pair you multiply by three and so forth and the only other thing that you have to realize here is once you use like two numbers you can't use them again so then you're forced to select a second pair like two and four and then you're left with just three and six okay so once again we want to calculate the maximum score so this is the maximization problem now this is going to be used with like dynamic programming because if you don't actually Implement any caching this will actually end up becoming like an N to the exponent n solution which is very bad it's pretty much as bad as you can get but with using caching what you can get is first the greatest common denominator function runs in log of the maximum of those two numbers like uh say I and J oh I and J so that's the time complexity of this method here but then you also want to multiply it by N squared and you get N squared because that is the number of pairs that you can have in a array of size n so you want to calculate and you're going to have to calculate all the different possible combinations that you can make in this array but then you're also going to have to multiply this time complexity for a 2 to the exponent n and that's because at every step of these operations that you're going to have two choices and that's kind of like it you're basically creating a decision tree where for the height of the tree at every step you're going to have two different decisions and those decisions are I can either include this number in my grace common denominator calculation or I can say I don't want to include it okay so this is actually the time complexity that we're implementing which is huge it's a huge time complexity but it's just a very complex problem and so you're forced to have this so yes let's go ahead and implement it and we are going to also import from the collections Library the default dictionary method and that's going to be used so that we can have our uh all of one like look up um using a hash map so let's go ahead and have that so we can just call this cache and we're going to call this uh or we're going to use that default dictionary with an integer so that's going to be a bit wise key that we're going to implement where it will be something like this where for this particular array say at this step here at this point in time we will have used just two numbers so far and so our key is going to look like one zero and what this represents is that the zeros mean we haven't used it so far and the ones mean we have used that number and so all that's happened so far is we've used one in five and so the number one here for the first index just represents okay if we use this number and then for number five we have one to represent that we've used that number okay and so this is just used to uniquely Define or uniquely identify at this particular like permutation we can have this maximum score okay and so by using like bitwise way is just very simple to uniquely identify like this particular permutation or choice that we've made okay and so we're going to want to return the result of our like DP top down approach and so we're first going to want to pass in zero which will be the start of our bitmask that we're going to have so initially none of these have been used so it's basically zero and then from that we're also going to want to have one and one's going to represent the current operation that we're on and we're starting at one since it's one indexed okay so let's go ahead and Define that function call it DP and we're going to first say bit mask and then the Ops just represent the operation that we're on and so typically the first thing that you're going to want to do for the memorization approach is you just want to see have already pre-computed this to see have already pre-computed this to see have already pre-computed this particular set so we just say okay if this particular bit mask is already in our cache then let's just return that result otherwise we haven't already pre-computed this and let's go ahead and pre-computed this and let's go ahead and pre-computed this and let's go ahead and calculate it and so in that case we're going to want to update our cache with the U result but in order to do that we want to go through all the different possible combinations which is where we had that like N squared time complexity it's all the combinations that would be 4i in the range of the length of our nums array and then same thing here we'll just use J we want to start at I plus 1 just because you can't say use one and one when you're calculating the greatest common denominator you have to choose two different numbers and so what we're first going to want to check is that we haven't actually used those two numbers before so verify I and J have not yet been used and to do this because this bid mask represents you know one as we've used it so far and zero as we haven't used it so far we can just check that bit masking to verify that we haven't used either of those numbers and so we just say okay if one shifted I times ended with our current bit mask and I'll explain this in a sec with one shifted J times and then ended with our bit mask and so if you're not familiar what this is it can be definitely confusing but basically what we're doing is say our bitmask is 0 1 and so say if I is equal to like one right now or say it's equal to 2 right now and so then we're just going to say okay we're going to shift one to like the left here two times and so then it's going to be okay one move it and then move it and so we put a one here so it's basically one zero and so when we do this and operation it just verifies that okay is this are these both ones no that we put zero here are these both ones no then we put zero are these both ones yes we put one and so this just verifies that okay we're going to want to return um let's see we're going to want to turn true if these are both one here and so if either of these have been used we're going to skip it so in this case this represents that yes this particular number has actually been used before so we're going to want to skip it and to do that you can just do um continue and we just duplicate this logic just because we also want to check at the jth position have we actually used that particular number that bit before okay so from here what we're going to want to do is calculate our new bit mask and so if we pass this particular check we just say okay in order to calculate this we're going to want to update our bit mask to actually have those bits set as one and so it's very similar object here where we're going to shift our one to the left I times and then we also ore it with our bit mask and so this will actually update those particular bits to be set to one and then we do the exact same thing with j okay and so from here we're going to want to actually calculate our score that we received by having this new masking and so it's just going to be you know say score and it's going to be set to our operation since we want to multiply it by I multiplied by our greatest common denominator of the number at index I and J so we just use our nums array at I and nums at J okay and so finally all that we're going to want to do is compute the new cache result and return it and so all that we want to do here is at the end of this we're going to turn cash at this particular bit mask I'll just move me over here and we're going to want to calculate it so the cash at this bit mask is going to be equal to the maximum since this is a maximization problem of whatever's currently at this bit mask compared to the score added with the recursive call to our function here with the do masking and so this just says okay what's better what we've already calculated one of the different possible scenarios that we found so far or do we want to use the new score with the new masking and see if we can get something better okay and so not sure oh and we also want to increment our number of operations by one since this will be considered a new operation let's go ahead and run this oh uh none type so I think this DP array is returning none here and that's because our return is within this for Loop but we want to put outside the for Loop and I think that's success so that's uh today's algorithm so it's definitely a hard problem it uses dynamic programming and bit masking and like uh you know caching so definitely challenging and I definitely recommend all can add a few tutorials in a different a couple of different solutions to figure this out um but once again the time complexity is N squared since we want to go through all the different possible like permutations and then we also want to multiply it by the time complexity of this gcd com function which is like log of the maximum of those two numbers so I'll go with Max of like the number at I and the number at J and then you just sorry about my writing it was so bad uh J and then multiplied by uh what else here 2 to the exponent n because our decision tree at every step you can either include that number or not include that number in our gcd function so yeah I hope that helped and good luck with the rest of your algorithms thanks for watching
|
Maximize Score After N Operations
|
minimum-incompatibility
|
You are given `nums`, an array of positive integers of size `2 * n`. You must perform `n` operations on this array.
In the `ith` operation **(1-indexed)**, you will:
* Choose two elements, `x` and `y`.
* Receive a score of `i * gcd(x, y)`.
* Remove `x` and `y` from `nums`.
Return _the maximum score you can receive after performing_ `n` _operations._
The function `gcd(x, y)` is the greatest common divisor of `x` and `y`.
**Example 1:**
**Input:** nums = \[1,2\]
**Output:** 1
**Explanation:** The optimal choice of operations is:
(1 \* gcd(1, 2)) = 1
**Example 2:**
**Input:** nums = \[3,4,6,8\]
**Output:** 11
**Explanation:** The optimal choice of operations is:
(1 \* gcd(3, 6)) + (2 \* gcd(4, 8)) = 3 + 8 = 11
**Example 3:**
**Input:** nums = \[1,2,3,4,5,6\]
**Output:** 14
**Explanation:** The optimal choice of operations is:
(1 \* gcd(1, 5)) + (2 \* gcd(2, 4)) + (3 \* gcd(3, 6)) = 1 + 4 + 9 = 14
**Constraints:**
* `1 <= n <= 7`
* `nums.length == 2 * n`
* `1 <= nums[i] <= 106`
|
The constraints are small enough for a backtrack solution but not any backtrack solution If we use a naive n^k don't you think it can be optimized
|
Array,Dynamic Programming,Bit Manipulation,Bitmask
|
Hard
| null |
1,930
|
hello and welcome to another video in this problem we're going to be working on unique link three pound dromic subsequences and in the problem you're given a string s and you want to return the number of unique P DRS of length three that are a subsequence of S note that there are multiple ways to obtain it and it's only counted once and this is a little bit tricky because we can't do our like I don't know if you've seen my other problem where you build palr you can't just build from the middle like you can't just be like okay let's just start here and let's build it out from the middle because the problem is you can skip letters so as you can see in these examples you can take letters that are anywhere in the word so you can't just like build in a linear way so in this first example we have ABA AAA and ACA and in the second one there are none and in the third one there is BBB BCB and they show you here bab and ABA so the question is like how do we do this efficiently and the way we're actually going to do this is relatively straightforward what we're actually going to do is we're going to go through the string and then we are going to get the leftmost and rightmost location of every character so let's just say we have this string and I actually brought this example up because I actually had a problem with this and this is like one of the test cases that I had an issue with because I was trying really hard to uh I was trying really hard to get a solution that wouldn't have to iterate through the string a bunch but I couldn't really find a way around that so we're going to do a few characters here we're not going to do like every single one of these but we're going to do a few characters so let's say we take the character D for example right we are going to we are actually going to do our logic is just going to we're going to go through the string and then we are going to have two dictionaries now you can do it another way but essentially we're going to have two dictionaries so we're going to have one dictionary called left and then we're going to have one dictionary called right and the left will store the leftmost location of a character so the character will be the key and the location will be the value and right will be the rightmost location and so we can go through a few characters just to kind of see what this is going to look like so let's take some characters that a pure a bunch now obviously I'm not going to Index this out so we'll just make up some index just to kind of see how this works so let's say we're going through this and we reach this letter T at index two first we're going to check is that character in left if it's not in left then this is the leftmost location so in that case for the left we'll call this like left or something left we're going to add T and its Index this index is two then when we reach it again let's say this index is like 20 I'm just making this up then we're going to see okay if it's in left then what we need to do is we need to put it in right because the leftmost location is the first one and if we already have it in there already then we need to put in right so we'll add it to the right T and we'll make it 20 and then let's say we reach it again then we can just override the rightmost index right the left most index is going to be the first time you see it and then the rightmost we can just keep overriding so we'll see it we'll override over here and then we'll see it again and maybe this like 30 whatever right so what I was trying really hard to do was once I get these two I was trying really hard to just like get a letter get the leftmost and rightmost index and then see like can I just check other letters leftmost and rightmost index and then can I check if it's in between them right so for example if T has a left most of Two and a rightmost of 30 I would just be like okay let me go through all the other letters and just check like if the left or the rightmost index of that letter is in between here then I have it but the problem is there are a lot of cases where that's not like that and so the case that I ran into that actually was an issue was so let's say instead of storing t i store the letter e so the letter e will have some index here and some index here so let's call this leftmost index 10 and let's call this rightmost index like 30 the problem is T will have a leftmost index of Two and a rightmost index of let's call this 40 maybe uh and so it will say that t is not in between here but it really is right there is a t here so the problem is like if I just greedily take the new index and make it the rightmost index there might be a t actually in between these e that is a paland drum but I'm not recording it so we can't do like that because that would have simple that would have made my code a lot faster because then I wouldn't have to Loop through the string I would have to uh I would be able to just L look through the dictionaries but anyway once we get the left and the right let's go back to this example so for this letter e once we get the left and the right so let's say it's 10 say 30 then all we have to do and notice there's only 26 characters and this is what we're going to take advantage of there's only 26 characters and we can get the leftmost and the rightmost index of every single letter in one iteration right so we can just like Loop through this and get the leftmost and the rightmost index of every letter then we will Loop through our letters and for example for letter e we'll say if left is so what do we need for a pound drum we need three characters right so we're going to say if the character is in left so we'll just like Loop through all the characters in left it has to be in right as well right because the p Drome has to start and end with the same letter so we'll say like if it's in left and it's in right then Loop through every character between the values and add those to a set right so essentially we're going to have a p that's going to be like e and then a bunch of letters here and the nice thing is because we add them to a set can only have 26 letters so let's say obviously we're not going to go through all these characters but let's say the set contains something like a EO right then what do we do well then for every single character in The set we can make a palindrome with E and then the letter in the set and then e so we can simply Loop we can simply get the set of all the characters between all the unique characters between and we could say okay the number of characters number of palindromes with E and then some uh character here and E is the length of the set and we can do this for every single character right so we could say for E let's Loop through it for a let's do Loop through it and the nice thing is since there's only 26 characters worst case SC we're basically looping through this string 26 times in reality uh you know not all the characters will be in left and right and also we're not going to Loop through the entire string but worst case scenario it's basically 26 * n which is it's basically 26 * n which is it's basically 26 * n which is oen and we're also not storing any uh anything big because the set is only 26 characters right this set is only 26 characters this left and right dictionary will only have 26 characters this is 01 space because this will be 01 this will be over one that's kind of the that's the logic for essentially you get the left and the right most of every single character in one Loop and then after that you just loop from the start and end index of all those characters you get all the unique characters in the middle and then for each one of those that can be uh that can be a pound room right so it'll start with some letter that's in the left it'll end with some letter that's in the right and then every single character in the midro can be can form a p Dr and so that's what we're going to do we're going to Loop through all the characters in the left we're going to say if it's in the right then let's do this like set of all the characters in the middle and then the number of pounds we can make with those two characters is the length of the set and the number of pounds total is let's take every single left character if there's the right character let's add up all these sets essentially and so that's going to be our solution so pretty straightforward um I did try to make it better like I said I wasn't able to do it so if someone is able to make it with just using the dictionaries that is kind of cool uh but yeah the problem is like in order to do it at least the way I see it is like you'd have to store the location of every single letter and then that kind becomes kind of expensive right so if there's like a bunch of T's you'd have to store the location of like every single te and check like if any one of them is between those and then you're kind of like basically looping through your string so it's like also you are your space will not be over one in that case cuz you're going to be storing the location of every single letter which will be o in space so this is I think as good as it gets for this one so let's actually code it up so we're going to have this like left boundary dictionary and a right boundary dictionary and yeah I was trying to debug it for a long time and then I realized my issue was yeah like I the reason I can't check if the left and right boundaries in between other ones is because it might be at first but then I update it so then it's not so it Tak me a while to I can do that so essentially we're going to Loop through our string so we'll just say like four OD Char in enumerate s so we'll say if the Char is in left then this has to be the rightmost boundary now right so we're just going to keep updating our rightmost boundary to this so we'll say right Char equals I otherwise if we've never encountered it before this is the leftmost boundary so now that we have the left and rightmost Boundary we can actually go through all of them so we'll say four character and left so it has to be in left and in right to make a valid palindrome so if character in right then let's just take all of the letters in between those and then every single letter in between those so let's say like we have a in left and in right we'll just say okay we'll have those indices and every single character in between those we'll throw into a new set and the length of that set is a number of pound RS because they will have a as the left and a as the right and then some character in the middle for example if the character is a and we do that for every character that we have so we'll say character equal set and for I in range left character one because we don't want to have inclusive we want to have it between these so between these we just do this we add it to the character set and simply the number of PS starting and ending with that character is the length of this set so result plus equals length of characters can return the result let's and it seems fine so there we go and about an average solution I think most people are going to have like an solution so for the time it is oen because we're basically looping through the string once here and then we are looping through the string once for every single character but there's only 26 characters so it's like 26n this is n space is of1 because um the left and right only have 26 characters so they're capped at 26 characters so that's 01 and same thing with the set it can only have 26 characters because you can only have uh a through z and yeah that's going to be all for this one so if you did like this one please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
|
Unique Length-3 Palindromic Subsequences
|
maximum-number-of-consecutive-values-you-can-make
|
Given a string `s`, return _the number of **unique palindromes of length three** that are a **subsequence** of_ `s`.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted **once**.
A **palindrome** is a string that reads the same forwards and backwards.
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
* For example, `"ace "` is a subsequence of `"abcde "`.
**Example 1:**
**Input:** s = "aabca "
**Output:** 3
**Explanation:** The 3 palindromic subsequences of length 3 are:
- "aba " (subsequence of "aabca ")
- "aaa " (subsequence of "aabca ")
- "aca " (subsequence of "aabca ")
**Example 2:**
**Input:** s = "adc "
**Output:** 0
**Explanation:** There are no palindromic subsequences of length 3 in "adc ".
**Example 3:**
**Input:** s = "bbcbaba "
**Output:** 4
**Explanation:** The 4 palindromic subsequences of length 3 are:
- "bbb " (subsequence of "bbcbaba ")
- "bcb " (subsequence of "bbcbaba ")
- "bab " (subsequence of "bbcbaba ")
- "aba " (subsequence of "bbcbaba ")
**Constraints:**
* `3 <= s.length <= 105`
* `s` consists of only lowercase English letters.
|
If you can make the first x values and you have a value v, then you can make all the values ≤ v + x Sort the array of coins. You can always make the value 0 so you can start with x = 0. Process the values starting from the smallest and stop when there is a value that cannot be achieved with the current x.
|
Array,Greedy
|
Medium
|
330
|
594
|
welcome to february's leeco challenge today's problem is longest harmonious subsequence we define a harmonious array as an array where the difference between its max and min is exactly one given an integer array we turn the length of its longest harmonious subsequence among all possible subsequences now subsequence is an array that can be draw arrived from the array by deleting some or no elements without changing the order here with this example the longest harmonic sequence is going to be 3 2 3 with a length of 5. we can also see that 1 2 counts as a harmonious subsequence but that's only a length of 4. here with this example um one we might think at first oh this should be a length of four but actually this is zero because the min and max value are both ones and the difference is going to be zero not one so here there's only gonna be there's not gonna be a subsequence that counts okay so if we did this straightforward brute force that's actually not that bad right we start at the first position and what should count in here as something that would be a harmonious subsequence basically a number of two and a number of zero right so this number plus one minus one um if we check to go down our array and see hey does a zero or two exist uh if we see a two then we could say yes let's start counting up how many twos and ones we can find from this point and same thing with the zero if we see a zero we'll say okay great how many ones and zeros do we have and we can just do that for this sequence and then start the second position do the same thing so on and so forth until we find our longest subsequence so that would work but it's very inefficient could we do this in one task we do this like greedily right because you normally with these problems you want to think greedily now the problem uh with greedy solution or here with this greedy solution is we basically want to move through our array and once we get our information like forget about it right but you can see that's kind of an issue here because once we get to like two we need to know how many ones and how many threes have we seen before uh and that is hard to carry over because we don't know how many we're going to have so just having one integer being carried over doesn't make sense we have to have some sort of hash right so let's do that let's start off by thinking about how we could store our information here and the very first approach i went with was all right well let's think about if we had a lookup of some sort i'm going to call it c and we'll make this a default dict and integers as its value so for n in nums what do we want to check well you can think about these subsequences as two numbers right and they're going to have a difference of ones and let's just create a key where we'll say all right n and n plus one this is going to be one of the keys as well as n minus 1 and this is also another key so we will use this as a key and just increase however many times we can possibly see the these pairs so if we had like our initial example here we might see that we get these pairs and we can see that 2 and 3 has a length of 5. right so that would be our answer you can see that um i think one and two had like the four so we just returned the max of these and that would be it right well initially you might think that but there's an issue here but what if we have all ones right and the problem with all ones is we create ranges of one and two with zero and one length of four but these actually don't exist because zeros and twos aren't inside of our number so we need to account for that as well we could just do a straightforward and what i'll do is create a set of all the nums and what we'll do is just look go through our hash and say all right if these are two keys of tuple right so if the first value is in the set and the second value is in the set then we know that this key can count so we will store that value in some sort of output so we can start with an output of zero and we'll say store the max of output and value as long as they both exist after that we just return our output so would this work let's take a look and it does so we account for these situations where um we have all one values and we can't count that as a harmonic subsequence now can we do better than this um yeah well if you think about start thinking about this a little bit more one of the things we might realize is even though they imply that the order matters it actually doesn't like if we sorted this the answer comes out to be the same and because the difference can only be one like if we count accounted for the three up front or at the very end it doesn't really matter like what we check for is these two pairs on n and n plus one and basically what we're doing is just summing up the number of times they appear as long as both these numbers are inside there then we just count up like sum up the two and that's actually going to be the length so rather than using this default dictionary why don't we just use a counter object we'll just count up all of our nums and rather than having a set here we'll move through our value and what we'll do is say hey this key that is the k plus 1 also in our counter object because we have to make sure that both these numbers exist and if they do then all we can all we need to do is just um add the value for k and add the value for k plus one and that would give us the same answer time complexity wise it's the same but it ends up being a little cleaner a little bit faster we can even go further here and do this in a one-liner in a one-liner in a one-liner what i'll do is let's see i'll create a list comprehension i'll say if keyplus one in c then we will add up these two like this and we'll just return the max from this list here and this will work as well but we also need to account for when there's a zero because this could easily return a no value so we'll have to account for that by adding a zero here so let's make sure this runs and this should work as well it's the same thing but it's just a it's actually a two-liner i suppose a two-liner i suppose a two-liner i suppose but hey that's pretty cool all right thanks for watching my channel and remember do not trust me i know nothing
|
Longest Harmonious Subsequence
|
longest-harmonious-subsequence
|
We define a harmonious array as an array where the difference between its maximum value and its minimum value is **exactly** `1`.
Given an integer array `nums`, return _the length of its longest harmonious subsequence among all its possible subsequences_.
A **subsequence** of array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.
**Example 1:**
**Input:** nums = \[1,3,2,2,5,2,3,7\]
**Output:** 5
**Explanation:** The longest harmonious subsequence is \[3,2,2,2,3\].
**Example 2:**
**Input:** nums = \[1,2,3,4\]
**Output:** 2
**Example 3:**
**Input:** nums = \[1,1,1,1\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-109 <= nums[i] <= 109`
| null |
Array,Hash Table,Sorting
|
Easy
| null |
1,945
|
welcome back everyone we're gonna be solving Lee code 1945 sum of digits of string after convert so we're given a string s which consists of lowercase English letters and an integer k we first need to convert that string into an integer by replacing every letter with it with its position in the alphabet so a would be 1 B would be 2 all the way to Z which is 26 so it's going to be one indexed then they want us to transform the integer by replacing it with the sum of its digits and we need to repeat this transformation K times in total so let's take a look at our examples example one they give us I is the ninth character in the alphabet there's four of them here we first transform it into this long number and then we add all the nines up which gives us 36 and we're only doing this transform one time so the output is 36. okay so we know we're going to need a mapping for this we should map the letter to the corresponding Index right so we can use a hash map and the enumerate method to do this so we'll say our mapping is going to be equal to a hash map what is going to be inside this it is going to be the letter mapped to the corresponding index and we want it to be uh one index so we'll add one to this and we want these To Be Strings so let's do this conversion right now for every index and letter in enumerate uh what do we need the alphabet how can we get that we can just say string dot as key underscore lowercase because we are working with lowercase characters and let's print this out so everyone can see print mapping run okay so now we have our mapping a starts at 1 Z ends at 26 perfect now what do we need to convert our original string s into the number that we are going to initially start with so let's create an array we will say conversion is going to be equal to this array what is going to be inside this array well we need the mapping character right so if we have I we need to go inside of our mapping and get the number right which would be 9. so we want 9 here uh for character in uh what do we have string so this is just saying you know for every character in our string say I for example one we're going to go inside this mapping we're going to retrieve I where is it at right here when we are going to retrieve the number and put it inside this conversion array so let's print out conversion and there we have it we have nine Okay so now we can say our number is going to be equal to the string join of our conversion all right this will give us our converted number so now what do we need to do now we need to run these transform operations and how many times we need to do it K times so this is perfect for a while loop we could say while K is greater than zero meaning we have more transformations to do what are we going to do we are going to want to keep track of some sort of number right so let's say number is going to be equal to zero and we are going to Loop through our string number right so we'll say four character in our string number we need to say number plus equals the integer of that current character we are at right because these are all nines right so we need to convert this nine from a string to an integer add it to this number when we're all done with that we can just say our string number is now going to be equal to the string of the number we just created and then what do we have to do that means we've done one transformation so now we have to decrement K by one and at the end of this we can just return our string do they want a string as a return they want a I think they want an integer return yeah return the resulting integer so we are going to have to return a um we're gonna have to convert this to an integer at the end so if we run this we pass all three test cases so let's submit see if it still works and it does so let's go back to the description what is the runtime and space complexity of this problem while creating this mapping is going to be uh o of n we have a essentially a list comprehension this is going to be o of n um we are doing a string join here that's going to be o of n as well uh we okay so here we go we're doing a for Loop inside which is O of n and we are doing it K times so this whole while loop is going to be o of n uh times K which is greater than anything we've seen so far so that is going to give us a Time complexity of o of n times k and the space complexity is going to be well our mapping is always going to be 26 characters long so that's of one our conversion is going to our conversion array is going to depend on the length of our string and our number um we have a string here so it's going to depend on the length of this as well so our space complexity is going to be o of the conversion length conversion.length plus the number length conversion.length plus the number length conversion.length plus the number length plus the num dot length and that'll do it for Lee code 1945.
|
Sum of Digits of String After Convert
|
finding-the-users-active-minutes
|
You are given a string `s` consisting of lowercase English letters, and an integer `k`.
First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum of its digits**. Repeat the **transform** operation `k` **times** in total.
For example, if `s = "zbax "` and `k = 2`, then the resulting integer would be `8` by the following operations:
* **Convert**: `"zbax " ➝ "(26)(2)(1)(24) " ➝ "262124 " ➝ 262124`
* **Transform #1**: `262124 ➝ 2 + 6 + 2 + 1 + 2 + 4 ➝ 17`
* **Transform #2**: `17 ➝ 1 + 7 ➝ 8`
Return _the resulting integer after performing the operations described above_.
**Example 1:**
**Input:** s = "iiii ", k = 1
**Output:** 36
**Explanation:** The operations are as follows:
- Convert: "iiii " ➝ "(9)(9)(9)(9) " ➝ "9999 " ➝ 9999
- Transform #1: 9999 ➝ 9 + 9 + 9 + 9 ➝ 36
Thus the resulting integer is 36.
**Example 2:**
**Input:** s = "leetcode ", k = 2
**Output:** 6
**Explanation:** The operations are as follows:
- Convert: "leetcode " ➝ "(12)(5)(5)(20)(3)(15)(4)(5) " ➝ "12552031545 " ➝ 12552031545
- Transform #1: 12552031545 ➝ 1 + 2 + 5 + 5 + 2 + 0 + 3 + 1 + 5 + 4 + 5 ➝ 33
- Transform #2: 33 ➝ 3 + 3 ➝ 6
Thus the resulting integer is 6.
**Example 3:**
**Input:** s = "zbax ", k = 2
**Output:** 8
**Constraints:**
* `1 <= s.length <= 100`
* `1 <= k <= 10`
* `s` consists of lowercase English letters.
|
Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user.
|
Array,Hash Table
|
Medium
| null |
706
|
hey everyone welcome back and today we'll be doing another lead code problem uh 706 designer hash map this is an easy one given a hashmap without using any built-in Library uh designer hashmap built-in Library uh designer hashmap built-in Library uh designer hashmap without using any built-in hash table without using any built-in hash table without using any built-in hash table libraries implement the hashmap class so it have a put method in which we have a key and a value insert it and uh get method we can which we can pass the key but we can get the value of that key and remove that just remove the key from the headset a hashmap so we'll be making a list which will be having none and resist its length is going to be what are our constraints let me see 10 is to power 6 so it will be like six zeros one two three four another one I think okay so we have we are going to put values so it will be like uh self Dot list add key is equal to data which will be well okay so in the get part we are going to get the value so value will be equal to self dot list at a key and just return well if Val is not none so we are going to check if it is existing or not and in the else case return -1 and in the else case return -1 and in the else case return -1 or here return we are going to remove so basically it is going to have none so self Dot the key is going to be none so list add key is going to be pointing to none that's it oh man invalid syntax return okay we are going to remove we are not going to return okay that's it hmm it sucks
|
Design HashMap
|
design-hashmap
|
Design a HashMap without using any built-in hash table libraries.
Implement the `MyHashMap` class:
* `MyHashMap()` initializes the object with an empty map.
* `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`.
* `int get(int key)` returns the `value` to which the specified `key` is mapped, or `-1` if this map contains no mapping for the `key`.
* `void remove(key)` removes the `key` and its corresponding `value` if the map contains the mapping for the `key`.
**Example 1:**
**Input**
\[ "MyHashMap ", "put ", "put ", "get ", "get ", "put ", "get ", "remove ", "get "\]
\[\[\], \[1, 1\], \[2, 2\], \[1\], \[3\], \[2, 1\], \[2\], \[2\], \[2\]\]
**Output**
\[null, null, null, 1, -1, null, 1, null, -1\]
**Explanation**
MyHashMap myHashMap = new MyHashMap();
myHashMap.put(1, 1); // The map is now \[\[1,1\]\]
myHashMap.put(2, 2); // The map is now \[\[1,1\], \[2,2\]\]
myHashMap.get(1); // return 1, The map is now \[\[1,1\], \[2,2\]\]
myHashMap.get(3); // return -1 (i.e., not found), The map is now \[\[1,1\], \[2,2\]\]
myHashMap.put(2, 1); // The map is now \[\[1,1\], \[2,1\]\] (i.e., update the existing value)
myHashMap.get(2); // return 1, The map is now \[\[1,1\], \[2,1\]\]
myHashMap.remove(2); // remove the mapping for 2, The map is now \[\[1,1\]\]
myHashMap.get(2); // return -1 (i.e., not found), The map is now \[\[1,1\]\]
**Constraints:**
* `0 <= key, value <= 106`
* At most `104` calls will be made to `put`, `get`, and `remove`.
| null | null |
Easy
| null |
424
|
hello and welcome back Fila colors this is godman sequest and we've got another exciting coding challenge line up for you today it's going to be a fun ride so let's Dive Right In and see how it works now let's figure out the problem statement here you are given a string s and an integer K and you can choose any character of the string and change it to any other uppercase English track and you can perform this operation at most K times at the end we should return the length of the longest substring containing the same letter you can get after performing the above operation right so let's figure out how this you know operation work in example number one if we get an input like a b and k equal to 2 we should return four because we can change um you know let's say two a letters to B and generate 4B which is the longest substring content in the same letter right but for example number two if we got this input a b a and k equal to one we can change this you know the first b letter and create for a letter in a sequence right so we should return for and you can always find the question constraint at the end of the you know page so now let's uh come back to the visual studio code and try to solve this problem and let's define the function signature and try to solve this problem so let's say funk character replacement two parameter S and K and then return tab which is integer since you want to Traverse over the crackers of this input string let's make an array from this string so let's say array equal to array from s right and we need to have the number of characters in this input and for this purpose we need to define a dictionary so let's say Char count equal to in a dictionary from characters to integers and it's empty by default and to find out the maximum length let's Define a variable for it so let's say bar Max lens is 0 by default and at the end of this function we want to return this value so let's write down the return statement at this phase as well so let's say return Max lens all right to solve this problem I want to use Windows sliding method and for this method we need to have the starting point and endpoint of this window so let's say we need one variable for the windows turning point so let's say bar window star is zero by default and then let's make a for Loop and say for window and in 0 to right in each iteration of this for Loop we are going to face with the new characters and we need to increase the number of this character in the dictionary so let's say count for array so actually square bracket array window and should be increased by one and the default value for this dictionary is going to be zero as well default is zero right now for this Windows third and window n uh we need to find out whether we can change some characters at most K times right and create a word that contains only one character for this purpose let me say why the lens of a window which is window and minus Windows start plus one minus chart account values Max which is 0 by default is greater than K this means that we cannot change at most K character and create an output with the same characters right so we should move our Windows starting pointer so let's say we want to decrease the character of window start in the dictionary by one so let's say chart account for array Windows start exclamation mark here because it's optional should be decreased by one and Windows start should be increased by one right so plus equals to one and at the end of this while loop we should say Max lens is going to be Max between the current value and the lens of the window so let's say window and minus window start plus one all right and this should be the solution for this problem but to make sure everything is working let's come to browser copy this example change back to the Visual Studio code and try to run our function with this input so let's say print character replacement a b and K is 2 and we should get 4 as the output right so let's say if problem that's if it's for as the last job let's submit our solution to let go change the browser one more time paste it here cleaner and then hit the submit button perfect here's the solution for this question thank you um
|
Longest Repeating Character Replacement
|
longest-repeating-character-replacement
|
You are given a string `s` and an integer `k`. You can choose any character of the string and change it to any other uppercase English character. You can perform this operation at most `k` times.
Return _the length of the longest substring containing the same letter you can get after performing the above operations_.
**Example 1:**
**Input:** s = "ABAB ", k = 2
**Output:** 4
**Explanation:** Replace the two 'A's with two 'B's or vice versa.
**Example 2:**
**Input:** s = "AABABBA ", k = 1
**Output:** 4
**Explanation:** Replace the one 'A' in the middle with 'B' and form "AABBBBA ".
The substring "BBBB " has the longest repeating letters, which is 4.
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists of only uppercase English letters.
* `0 <= k <= s.length`
| null |
Hash Table,String,Sliding Window
|
Medium
|
340,1046,2119,2134,2319
|
7
|
let us now discuss about reversing a number let's say we have a number like 1 2 3. so reversing means it should become 3 2 1. so Here If You observe 1 2 3 is nothing bad 100 plus 20 plus three so it gives 123. so here it is 300 plus 20 Plus 1. 321 so here the unit digit is 3 unit digit 10th digit 100 digit so this unit digit is multiplied by 100 here and the 10th digit is multiplied by 10 and the 100th digit is not multiplied so that is the logic in reversing so now what we can do is let's say we have a number like 1 5 7. first we can take the unit digit so and store it in the Reversed value so let's say this is the original value and this is the Reversed value so you take the unit digit and bring it to the reversed so now you divide by 10 when you are dividing by 10 it will not give you 15.7 dividing by 10 it will not give you 15.7 dividing by 10 it will not give you 15.7 but it will give you 15 because it is integer arithmetic so when you divide by 10 it will become 50 but now you should not just take the unit digit and add it to 7. you should multiply the 7 by 10 so it is 70 and then add so plus 5 is equal to 75. now you divide by 10. so 15 becomes 1 because the unit digit will be removed so this is 75 here okay 75 here now you take the unit digit and add it here but before that multiply by 10 so 750 plus 1 is equal to 7 5 1. so now you can see the value has been reversed so let's consider one more example we will have four zero five zero now you are taking the unit digit and adding it so it is 0 you divide by 10 so this becomes four zero five so now you multiply this zero with the 10 0 into 10 plus the current unit digit 5. so it is equal to 5 because anything multiplied with 0 is 0. so now you divide by 10 so this goes off so you have 40 and 5. now whatever the value you multiply by 10 and add the unit digit here plus 0 equal to 50. so you are going to divide by 10 so this becomes 4. so now you are going to multiply this value whatever is here okay 50 into 10 plus 4. and you are going to divide this by 10 so this 4 when it is divided by 10 it will become 0 okay so in the right side the value will be 504 because 50 into 10 is 500 so 500 plus 4 gives you 504 so now you can observe when four zero five zero is reversed it gives 0 5 0 4 the 0 in the most significant places okay it will not have value so the value is 504 so this is the logic we should follow so the logic we follow is suppose we have a number n the Reversed value how to get it so let's say the Reversed value is 0 so you are going to say the inner loop you are going to iterate till n becomes 0 the steps to be followed are reverse into 10 plus n modulo 10 that is the unit digit so this is the first step Second Step you are going to say n is equal to n by 10 you are going to divide by 10 so when n becomes 0 stop then finally whatever the value in the Reversed it will be the Reversed value so let us follow this okay so let's have two variables we will have n and then reversed so initially reversed is equal to 0 let's say n is equal to 7 2 4 0 okay 7240 so step one you follow reverse into 10 plus n modulo 10. so 0 into 10 plus n modulo 10 so 0 into 10 plus 0 this is 0 only then n is equal to n by 10 n is 724 is n0 no so again repeat step one so reverse into 10 0 into 10 plus n modulo 10 what is n mod Lot 10 4. so it becomes 4 what is the Second Step n is equal to n by 10 n becomes 72 is n 0 no then repeat step 1. reverse into 10 4 into 10 plus n modulo 10 2. equal to 42 okay so Second Step n is equal to n by 10 you divide n becomes 7 yes n 0 no so repeat the steps so 42 into 10 plus n modulo 10 7. so this becomes 427. so now Step 2 N is equal to n by 10 so 7 by 10 will give you 0. now n s becomes 0 so stop the following the steps so now what is the final value 427 so 7240 when reversed it will give 0 4 2 7 0 in the most significant place it doesn't have any value so it will give you 427. so now let us implement the logic so we are going to accept the value in n so we are going to initialize the reverse value is equal to 0. so we are going to check while n not equal to 0 what are the steps to be followed reverse is equal to reverse into 10 plus the unit digit of n so unit digit you will get is n modulo 10. then the second step what is it you have to divide n by 10. right so when you come out of this Loop whatever the value of reverse okay that should be printed so now let us execute the program I am going to give one two five six as the input 6521 is the output so now let me give some values with the trailing zeros 50600 the output must be 6.5 50600 the output must be 6.5 50600 the output must be 6.5 So based on our discussion please try to solve this program and thanks for watching
|
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
|
133
|
Jhaal Hello Hi Guys Welcome To Code Virus Today's Question Is Clone Graph In This Question Yagya One Arrested Under The Grass And Will Give Directions Mode Resident Means New Delhi Bihar Ke Mandir Force Note Anju Singh Dodiya And Travels Switch Off This Notes Hindi Graph Now Doing This Question Has Written Reddy Copy Of The Graft And Birthday To Medium Invillable Look Edit Later Now This Structure Of Snow Deposit Is Valuable Contents That Will Not End Another Day But This List Which Contains Content Only This But I Will Not Give One To Three Four Wheel Chair And Are Known To One And All The Best Of All Of The All Of These 10 Female Actresses Copy This Graph In Another Location Dominant Value Of North And Order Of Soil Remains In That Is The Independence 12345 With White Widow 1234 But Not Address Of December 19 2019 And Subscribe To This Video In Another Location In Word Format 1234 Customer Turn Off O Mary Chandni Singh Right Will Not Be Accepted Because This Is To Soft Copy And Economists Have You To Copy This Group And Share New Location A Hai Arey Teri My Flight This Singer The Forest The Is 1234 Classification 12345 1234 Only But In This Case E English 9909 Se Withdrawal 1234 Order Notes 200 151 Starting Note Also Increase Starting Notes And Starting Not Have To Values For City Starting Not Have To Values For City Starting Not Have To Values For City Will Not End Easy List Office Never Forget Not Under Developed From Vitamin E Node Vitamin E Starting Not Opted For Pick-Me-Up Returns Is Note Office Copy Pick-Me-Up Returns Is Note Office Copy Pick-Me-Up Returns Is Note Office Copy Sudesh Bhosle And Share Question No Will Look At The Approach Now This Question Is Question Can Be Done In Two Approach Towards Difficulty And Another One Is Face Approach In This Video Is Talking About The Edifice Approach 9 Looty App Launch Not Supposed To Be Given Due Importance To Return With Difficult Jise Graph Bane Zoom Laddu Subscribe Button Practical Man A Is Vidhi Original Will Look Like This Is Not And With Members For Students And Enable One To Similarly For This Tree Na Mind But Practically This Is This Aa Jati Thi Deewani Si Bollywood Download And List Will Contain Any Too So Much Needed To And Three Members Objective Ranaut Chauhan Withdraw Support Will Explain You Main Abhi Explain if approach using code selection let's get started record sources of main function day test imported this reference note input device reference produce in which we can are using which we can find t&d copy na usi using which we can find t&d copy na usi using which we can find t&d copy na usi vanshi to find it is that this one which one will again Again From Different Location And Will Do It Well And Will Not Give You And Jeevan Divya Bandh Nau Being Given There Valuable But Will Also Give Relief Ne Bigg Boss Video Hindi Original Graph Ne 252 Will Go To Will Not Want To Say A Sorry E in this form and the lord that bill time send two notes edit value suppose a gift from the new note bittu asset value a note via jogging notice to end emergency vitamin A B 2012 sleep fashionable this dynasty will go to one but being end Direct Positive Form-21 Subha Can't From Another Not With Form-21 Subha Can't From Another Not With Form-21 Subha Can't From Another Not With Disabilities 121 Doob Will Also Maintain His Map Water But He Will Do It Well Taylor Wisdom Patti Le Incent Witch Not Be Had From Softwares For The First Note Shoot Me Address Its Policy Address Of Original Not Why And Address Of The Note Which Form Edit Officer Hardware Store Rates Will Juice That Is Equal To Note Star Address Of The Original Road And Value Edition Business Days Note Star Class 8 Minutes Value Will Is Divine Of The Being Copied One Mode From Here Like ex-iaf chief and here address for From Here Like ex-iaf chief and here address for From Here Like ex-iaf chief and here address for short and why is the president of second sweet is relaxed and when you will read by swapnil dhayar map mid-1960s map did by swapnil dhayar map mid-1960s map did by swapnil dhayar map mid-1960s map did not inform 02 and they will not simply that dangal simply add 1st neighbor in this Nod And Move Ahead And Didn't Mean That I Know This New Swapnil Here It 12183 Sleep B.Ed First Year Here It 12183 Sleep B.Ed First Year Here It 12183 Sleep B.Ed First Year 10.1 Study Belong To Should Not Be 10.1 Study Belong To Should Not Be 10.1 Study Belong To Should Not Be Considered One Long Snap Swimming That Is Tattoo Reddy Ne Bindi To Zet But Another In Abduction And Considered This notice map world you will form e will laugh and not with jatin normal note pimple oo and when will not disturb and morning-evening app will return the and will not end with me but does morning-evening app will return the and will not end with me but does morning-evening app will return the and will not end with me but does not seem to be declared her a dispute type Notes 4 to Notes48 Restore Dwivedi's Method Table and the Original Graph and Value Meena Address of the Deposit Graph Will Be MP3 Mein Naav Doobi Quality of His Approach To End Address What Will You Do Function and Will Power the Current Node Android App Flash Lights And Adventure It Will Be Note 4 Only Birthday Written Updates Is Note Sir Its Nod British Key Reference Mode Of Audi Copy Election Will Be Town DSP Positive Itana Point At One Odd End Nine Wickets RDF Support Note 4 Davis Hain It Will Accept you are the match become day node other is the note of unwanted map in android app to star note 4 Italy pass that reference removed then make changes in developed calls 888 basic acid base how date day notice no delusional is note value is null But will do that uk town null from near this note 112 null a bengali dance and null only oo ki naav hai but ab notice not null it means that we can do not see initially rd copy is mp exit poll snowden develop plane which was code That so many albums because it's working Sony CID Comedy Group De Officer Anti A I Just Son Minute 180 Initial Edifice MTV Award Will First Form New Note Sun Notes4 Ka Plan Dinesh New Notice Clone New Note And You Will Not This Not Wish MSD The British Embassy Note 4 How to copy seat from the main function business from not available water testing and starting and not visible is point into the first is point uie first mode of the original graph dipped to remedies copy and will do hair oil e will form a dick Achievement note with same value were British and this knowledge node office of bantu12 and suno came from the note ribbon suno dendu itself but equal to anode a well of the snow fall from unit lines after you not able to modi to address this new note And rapid tours of the and is note daily audio MP3 original node is equal to that lone a ACE node person stop imo load and can represent was represented difficult note strong also how did not inform and they will be updated supposed to relax and Evaluate this basic and did not know what do you know and the Dogra looks like this is not with name and form and then ten list of nibus issues will do it see what will oo will try to and New Zealand think all this and will try to Year Enables Of The Current Nodule Should Not Do Nothing Just I C Which Foreign Investment Is Not Enabled System Ko Mat Reduced And With A Particular And Heart Valve Illitrate Period Particular Never Be Disappointed Tours Now C1 Is One Should Never Exist In The Current S Naipaul V 180 A Meanwhile A Badmaash Ne Bigg Boss Sindhi Hai Don't Exist In The Contacts E Joe Hair Wash Bhanot And To Three Aadesh Never Know When Creating Awareness Be Thrown At You For Sharing And To 9 Inch A Basis To Belong Sign Shall not be considered in her only one belongs to you NSC Current Note And Ambitious Map Rate Will Return Types Notes Politics Written Notes Se Aaj Se Main Bhar Only Saraini That's Why Political Will It How This Course Will See Quality Of This Again In The Current Government Should Not Viewers Welcome To Do That Aaj Here But I this only consider maps only filled with date form date that they again for become not call to know this lineup and will run at mp notification it means that suppose that reach the address for these original notes by all these cannot share posts by email that today the health effects and health will be boy To e was capital saudi address also present acid what is capital by hand with map g value of being closed se connaught travel tours and from this note this why nobody will do cup 2010 party to dr bank dominant know what will happen will try to uniform Ne 20 Per Gram Not Possibly 115 11th Check Weather She Gasp And Not Be Considered As A First Year First Ever Already Exist In Disgusting An Incident Without Anything Just Simply This Vidya Shatru Simply Add Husband Value Nearby Office List Dentist C A R Not Boss Clone A clan that just said Om Ne Bigg Boss Anduco held the Bloody Mary list and just to add daughters back, paid floral tribute Dvedi I sat asking this address 54 This will ask staff15 Will find address of this 150 Address of which was the address of Who is the Lord And such address half follow note white flower back in this not regret poochhe ke not fennel will push back sunil main naseeb but pooch baithe kuch battery defiantly of this person pooch baithe value of address what does not end address on this notice x dash Dash notice advertisement method this map to the original and is channel graph notice one so will push back see will push back mp of nc fear and represents the meaning and representatives in number show vinod adjoin to administrator to afford in history start address of one Original one address this and details in map 2802 given address what this plant one node for web he tweet pooch baithi address of MP after and decided employed with a small Hai MP Apna Has Been Done To Be Vidron From Her Return Clan The Clan Is The New Nodi Sperm Subha Vitamin A Diplomat Arrest But See Watering Developed Call Some One Else But When They Remind Noida One And Edit One In A Hindi List Of To Interest Vikram Know it Vikram a little distance from one no again on the beaver trading period saved be taken to one and all one notice over now they are getting hot scene nor will check weather the three belongs to years she cold not be considered Hai 1992 Hai Snap To Ignorance And To Will Again Maker Dad Call Return Per Vitamin Period Return Alsi This Topic Craft Decorative And Cordiff Information For Not Paying Back Cutting Back Withdraw From Difficulties In Life Has Been Withdraw From This Call Gives And Tire Give Quickly And Tied a cloth and join us actresses dad this office returning us on this day year total this returning more benefit college vitamin d copy of the remaining notes of from one with head cold this affair zooming backlit storm the copy and restaurant speed set at the same time Some Work And This Particular Not So 133 It's At All Regiment Back Gear In This Point A Jaati Said Received A Call From The Best Option Not Know What Do Pizza Step2 Simply Clone On The Arrangement Of Simply The Benefits Of Simply Any Other Never Gets Pushed back that NCI Sudesh Disawar disposed of doing but doing what will not and human question will return 80d cup laptop note Sombir work to this post no death and where issued notice to the notes24 and free that Bihar has been written to be copyrighted question Sudeshpal Knowledgeable Court No Let's [ __ ] Code A Yes This A Compiler User Note Nibbles Ok Subah To Use Of Her Hair That This Notice Period Dance Arnold Samridhi Ko And A I Fan Ho Gaye Zilla's Video Thank You Don't Understand This Video Please Go Back And Water Animals Definitely Understand What Is And Everything Is Doing Please Like Me Video And Subscribe The Channel Par For More Updates Thank You
|
Clone Graph
|
clone-graph
|
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.
class Node {
public int val;
public List neighbors;
}
**Test case format:**
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.
**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.
**Example 1:**
**Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Explanation:** There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
**Example 2:**
**Input:** adjList = \[\[\]\]
**Output:** \[\[\]\]
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
**Example 3:**
**Input:** adjList = \[\]
**Output:** \[\]
**Explanation:** This an empty graph, it does not have any nodes.
**Constraints:**
* The number of nodes in the graph is in the range `[0, 100]`.
* `1 <= Node.val <= 100`
* `Node.val` is unique for each node.
* There are no repeated edges and no self-loops in the graph.
* The Graph is connected and all nodes can be visited starting from the given node.
| null |
Hash Table,Depth-First Search,Breadth-First Search,Graph
|
Medium
|
138,1624,1634
|
1,002
|
hey there how are you I hope you're fine today we are going to learn about finding common characters in a list of words let's first look at what the question asks so we are given a list of words we simply have to find out what characters are common in each word given in the list also we have to keep in mind that how many times a unique character is present in all words for example as given in the example one we see that L is present to times in all of those words so we must return L for two times now we have understood the question and let's start solving it first we should return the word itself if there is only one word in the given list so we use if condition to check if there is only word and then return that word without going further anywhere now we would take the first word as our sample for checking its character's presence in the rest of the words because we have to find common letters in all words the first word must contain those common characters excluding in that first word cannot be considered common we will take on unique of those characters in first word so we converted the list to a set because we will run Loop for each character or letter so we wouldn't want to run Loop for the same letter twice we will create an empty list to store those common letters we name it as letters now for each letter and first word we run for Loop we created a temporary list in which we count the letter of first word for which we run Loop then we take the minimum count and store it to an variable because if there is no letter for any word then the list would contain zero elements hence zero would be stored to invariable for that particular letter now if the variable n is greater than zero then we add those letters to our Letter's list if n is 2 then we add two times same letter to that list finally we return our Letter's list congratulations we did it if you find this solution helpful then please like the video and subscribe to our Channel rubber dog thanks
|
Find Common Characters
|
maximum-width-ramp
|
Given a string array `words`, return _an array of all characters that show up in all strings within the_ `words` _(including duplicates)_. You may return the answer in **any order**.
**Example 1:**
**Input:** words = \["bella","label","roller"\]
**Output:** \["e","l","l"\]
**Example 2:**
**Input:** words = \["cool","lock","cook"\]
**Output:** \["c","o"\]
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of lowercase English letters.
| null |
Array,Stack,Monotonic Stack
|
Medium
| null |
1,812
|
let's solve lead code 1812 determine color of a chess board Square so given a chess so the input would be coordinates of the chess board A1 for example right A1 or H3 or C7 so the first character represents the x axis right and the second character represents the y- represents the y- represents the y- axis okay so the numerical character represents the y- axis the alphabetical represents the y- axis the alphabetical represents the y- axis the alphabetical character represents the x-axis we need character represents the x-axis we need character represents the x-axis we need to tell if the coordinates provided is that a dark colored cell or a light colored cell so if it's a light colored cell we are going to return true if it's a dark colored cell we are going to return false so what am I going to do is I'm going to Simply do ANL Loop if it uh if the first character is in a c e g and second character in 1 3 57 then return false because it's a dark color cell else if uh if the Chara else check if the numbers are in 2 4 6 and 8 then will return two because it's a white colored cell let's write that in code if coordinate zero so zero means the first character if the first character is in BD FH b or d or F or H and the second character is in coordinates at 1 it's in 2 4 6 and 8 which means it's a dark colored cell right B2 that's a dark colored cell D four that's a dark color cell so in that case I'll return false else I'll return true for all the even numbers with BD FH those are white so return true and then I'll check if it is not it does not the first character does not belong to BDF which means it belongs to a c e g in that case I'll check if the second character belongs to 1 3 5 or 7 in that case I'll return false because that's a dark colored squar and else I'll return true because all the other squares are bright light colored Square so that could be one way of doing it that's an explicit using F statement it works in the test cases let's submit and see and that worked the other way that I like is I would you do is in a little mathematical way so what I can do is I comment this out and what I'll do is I'll convert this AB C D E F G H whatever character I get into new numbers so I'll convert that into 1 2 3 4 5 6 7 8 depending on what character I get okay and I'll convert it into their uh respective number and then I'll add this first character that I get converted into number with the second character I get so I'll add these two numbers and check if they are an odd number if they add up to be an odd number which means it's a light colored cell if you see 1 + 2 gives me cell if you see 1 + 2 gives me cell if you see 1 + 2 gives me 3 1 + 4 gives me 5 or 2 + 3 gives 3 1 + 4 gives me 5 or 2 + 3 gives 3 1 + 4 gives me 5 or 2 + 3 gives me this one S 2 + 3 gives me 5 2 + 1 me this one S 2 + 3 gives me 5 2 + 1 me this one S 2 + 3 gives me 5 2 + 1 gives me 3 so all the odd numbered cells are uh the sum if the sum is odd then they are bright colored cell otherwise they are dark colored cells so I'll write that down I'm taking the first character taking the ask value of it subtracting 96 from it that converts it into basically that converts a into 1 B into 2 C into 3 g into 4 e into 5 F into 6 g into 7 and H into 8 once I have that number I'll add the integer version of the second Char character I'll take the second character convert it into an integer and add these two numbers if they turn out to be an odd number and one is a way to figure out if it's OD okay if it ends with an odd number so if it is an odd number it will return true because that's a bright color itself if it's an odd number the sum is odd else it will return false let's run and see that worked and that's submitted and that worked too so that's how you solve this problem 1812 deter color of CHP Square
|
Determine Color of a Chessboard Square
|
reformat-phone-number
|
You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.
Return `true` _if the square is white, and_ `false` _if the square is black_.
The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.
**Example 1:**
**Input:** coordinates = "a1 "
**Output:** false
**Explanation:** From the chessboard above, the square with coordinates "a1 " is black, so return false.
**Example 2:**
**Input:** coordinates = "h3 "
**Output:** true
**Explanation:** From the chessboard above, the square with coordinates "h3 " is white, so return true.
**Example 3:**
**Input:** coordinates = "c7 "
**Output:** false
**Constraints:**
* `coordinates.length == 2`
* `'a' <= coordinates[0] <= 'h'`
* `'1' <= coordinates[1] <= '8'`
|
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
|
String
|
Easy
| null |
89
|
to my legal suffering section so this problem is called the gray code great code so this problem is uh really important that because we will use these results uh in the other videos so the grade code is a binary numerical system whose word to consecutive accounts excessive other successive values differ in only one bit so another problem is that a given non-negative integer n represent a given non-negative integer n represent a given non-negative integer n represent the total number of bits in the code print a sequence of gray code a critical sequence must begin with zero okay so uh two and that means we need to return four numbers so basically zero one three two so the sequence is basically a zero star zero ones one three one zero two so the important is that uh the successes one only contains one bit one oh one only different atmos one beast only different one bit okay so zero uh and the zero one different one bits and then zero one d forty speed and that is two uh different speed okay yeah so uh okay so let me just show you the how to do this okay so uh suppose an equals to one then we know that we should return zero to one right so you see zero one okay so this is zero this is one how about equal to two okay and we already know the answer right but uh you we need to somehow like us think or what's the uh recursion okay so basically you see uh if you add two to zero one if you just add two right if you add two then in binary representation you just both add 2 here that's here right so if you have 0 1 0 if you add 1 at 2 then you this become the one zero one and this is two this is three okay so now you come up with the idea that if i put three uh to be an x of one then i put two to be the next episode three two here then this is the answer okay so unequal to three is similar uh i have a zero one three two if i add four i get four five uh seven six then i again so you see uh at least two right these two is one right this six is one zero uh oh sorry z two is uh zero uh one zero right so six is one zero and this three is one this is one and then this is zero one right and then pi five is one zero one so you see you just put these close to this so you get six seven five four so this is the answer so now you know the answer uh for n equals to k and n equal to k plus one suppose you already know an equals to k right you just add uh and add maybe uh 2 to the k minus 1 to all of these number right and you just reverse this number and uh put here right so basically you reverse this number reverse and then you put here you push here okay so now we have this algorithm okay so we can see the answer an equal zero just returns zero and uh we got the previous code basically self grade code minus one and it's very easy that we just let the previous code plus uh 2 times 2 to the power -1 i already proved plus 2 to the power -1 i already proved plus 2 to the power -1 i already proved plus x for x in the reverse okay so basically you just reverse all the reverse order uh string and you add these two and plus one plus x and then you put concatenate into previous code so basically this is uh this process basically is all i proof here and you can try n equals to one and equal to 2 to n equals 4 to get a feeling right and the reason is very simple because if you added the 2k plus i've added a power of 2k plus 1 and it will only add one here so the remaining different only be one djs this condition still satisfied okay so you can submit okay that's it and uh please be sure to uh subscribe to my channel i will see you guys in the next videos
|
Gray Code
|
gray-code
|
An **n-bit gray code sequence** is a sequence of `2n` integers where:
* Every integer is in the **inclusive** range `[0, 2n - 1]`,
* The first integer is `0`,
* An integer appears **no more than once** in the sequence,
* The binary representation of every pair of **adjacent** integers differs by **exactly one bit**, and
* The binary representation of the **first** and **last** integers differs by **exactly one bit**.
Given an integer `n`, return _any valid **n-bit gray code sequence**_.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,3,2\]
**Explanation:**
The binary representation of \[0,1,3,2\] is \[00,01,11,10\].
- 00 and 01 differ by one bit
- 01 and 11 differ by one bit
- 11 and 10 differ by one bit
- 10 and 00 differ by one bit
\[0,2,3,1\] is also a valid gray code sequence, whose binary representation is \[00,10,11,01\].
- 00 and 10 differ by one bit
- 10 and 11 differ by one bit
- 11 and 01 differ by one bit
- 01 and 00 differ by one bit
**Example 2:**
**Input:** n = 1
**Output:** \[0,1\]
**Constraints:**
* `1 <= n <= 16`
| null |
Math,Backtracking,Bit Manipulation
|
Medium
|
717
|
207
|
hey everyone today we'll be going over course schedule so the problem statement is as follows we have a total of num courses that we wanna tweak and they're labeled from 0 to num courses minus 1 so if I have 5 courses I want to take the courses would be labeled from 0 to 4 now some courses may have requirements so I can't take courses 0 until I take course 1 for example and that is expressed as a pair 0 1 now given a total number of courses and the list of prerequisite pairs is it possible for us to finish all the courses so there are three main steps we're going to take to solve this question first we're going to think about how best to model this problem then we're going to think about how exactly we come up with a potential ordering for these classes and finally given an ordering of classes how do we make sure that this ordering is going to actually meet the requirements so first up we're gonna think about how best to model this problem so our input is a number of courses and then a list of course and prerequisite for the course so we should immediately think of graphs because we can represent a edge as a prerequisite node pointing to the course that we can take after taking that prerequisite and then we should think about well what is the best way to actually explore this graph so now I'm gonna walk through a couple of examples so say we are given 1 0 which means that in order to take course 1 we would have to take a course 0 first and well there is an ordering here we can just take class through and then take class 1 so we return true and here's another example in order to take class 1 we have to first take class 0 in order to take class 2 we need to take class 1 and we can just take the classes in order from 0 1 to 2 and that would be a successful ring so we'll return true so now we're going to go into some examples where we can't find a solution so this is an interesting model error we have to take course arrow before we can take course one but then we also have to take course one before we can take course zero so there's no way to figure out an ordering here this one's kind of similar except well we can take course arrow and then course one but then we run into the same question as before where there's no way to order one and two such that the ordering would work so let's really dive into the way that we can order these classes so for starters which courses can I take first it should be the ones without a requirement right and then how do I know which ones don't have a requirement well we can check how many prerequisites are required for each course then how do I know when a course has completed all of its prerequisites when the number of prerequisites required for the course becomes zero and say a course initially has some number of prerequisites how do I get that number to zero so every time we take a prerequisite for a course we can decrease the number of prerequisites required for that course so now let's take a look at how we determine whether or not we actually found a right answer so how do I know if I can successfully complete all the courses well there just cannot be a cycle and say I do generate a list of classes how do I know that this is all the courses well we can just simply check that the length of the list is equal to num courses which is one of the input values so now that we've built up some intuition around the solution let's come up with the algorithm so first we're going to count the number of prerequisites required for each course we create a map of prerequisite to the next courses that we can take and then we'll initialize an empty stack for each course if there are no prerequisites required then we can just insert that course into the stack so that's saying if a course doesn't have any requirements we know that we can take it and we can explore those nodes first we'll run a DFS we can pop the course off the stack we know that we can take this course so we'll add it to our ordering and then for each of the next courses or the list of edges in our map of prerequisite to courses we are going to decrement the number of required courses by one now once that number hits zero that means we can take the course and then we will add that course to the stack finally we check whether this ordering we came up with has size equal to num courses and that's essentially saying is the number of courses that I took equal to the number of courses available and this algorithm is also known as a topological sort now let's translate that into code so that we initialize our values and we iterate through the prerequisites we increment the number of required courses the in degree map and then we also append course to the edges dictionary for the key prerequisite now for each of the courses we're going to see whether or not we can take it first and that means we'll just append it to our stack then we run our DFS and this is a pretty traditional DFS except notice that when we explore the next courses we decrement the number of requirements by one and if now there are no courses that are required we can append the course to the stack and finally we return whether or not the length of the ordering is equal to the number of courses so let's quickly walk through some examples this was a case where we do have a successful watering so in degree holds one does there's only one course required to take course one and then edges holds zero to a list containing the element one so our stack contains the element to zero because there are no prerequisites required for course zero we will pop it from the stack added to our ordering one is the next course now we decrement in degree map with key value one by one so now that's saying well we've taken that is it so now we can take course one and then eventually one ends up and our ordering no more edges to explore exit the while loop and the key part here is that well we actually do have two classes in our ordering and that's a number of classes that's available so we can return true so now let's look at a case where we don't have a successful ordering so are in degree map one Maps two to two maps to one here is the list of edges so initially we can only take course zero because zero has no prerequisites we add 0 to our ordering and one is in the list of edges with key equal to zero so we will decrease the number of courses required to take one by one so now it's saying that there's only one course required to take course 1 however this means that we don't depend it to our stack because there's still courses I have to take in order to append one to the stack so our ordering ends up being only the elements 0 and obviously since we've only taken one class and set up the required three we will return false here so hopefully this video was helpful feel free to leave a comment if you have a question thanks
|
Course Schedule
|
course-schedule
|
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return `true` if you can finish all courses. Otherwise, return `false`.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** true
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= 5000`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* All the pairs prerequisites\[i\] are **unique**.
|
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
210,261,310,630
|
1,792
|
hey what's up guys uh this is chung here again so uh design 1792 maximum average pass ratio okay so there's a school has a classes of students and each class will be having a final exam and you basically you're given like a 2d integer array classes here where the uh there are two elements in it the first one is the pass number and the second one is the total number and basically this means that in each of the class you have this kind of total students and this past number of students will pass the exam and then you're also given like an integer of actual students uh who are really breeding students right and this these actual students are guaranteeing to pass the exam of any class they're assigned to and you want to assign each of the actual students to a class in a way that the ma the average pass ratio across all the classes is maximum its max size is its maximum so the pass ratio of a class equal to the number of student of the class to pass the exam divided by the total number of students right an average pass ratio across all the classes is a summary of the path ratio of each class and divided by the number of classes okay and we need to return the maximum right so for example we have three classes here right in class one uh out of two students one will pass so in class two out of five students we have three students will pass and out of three the third one basically all students will pass the exam and then the actual student is two okay so i mean so for this problem you know so we have some observations that we need to make first we need to make right so obviously you know it doesn't make sense to add actual students to the class that all the students will pass right because they already the pass ratio for this one is already 100 well it's already one right and if we add one student to this class so two divided by two equals to three divided by three so the pass ratio will not change right so which means that you know we want to add this students to a class that can increase the pass ratio and the second observation is that you know it doesn't really matter as long as we add the like extra student to any of the class you know the pass ratio for that class will always increase because you know for example if we add this one student to the first class so the path ratio will become from one divided by two will become to two divided by three right and if we add one more right so this one becomes three divided by four right and the pass ratio this is 0.5 right and the pass ratio this is 0.5 right and the pass ratio this is 0.5 0.666 0.666 0.666 and this is 0.7 right it's always and this is 0.7 right it's always and this is 0.7 right it's always increasing basically right but the percentage of increase is different basically the percentage of the increase is decreasing so now the problem is that you know it's this limited actual student which class we can add we want to add it to because let's say for example this one we have a class one and two right we can choose either add to class one or class two in this case we should we add these two students to class one that's why the total number the total the final answer is this one after adding two students into class one we have uh we have three divided by four right and then plus three divided by five plus one divided by three we have this number okay and the constraint is like this right we have 10 to the power of 5. so i think it's kind of obvious that you know the subs problem we some we somehow we also need to use a greedy approach here basically you know every time when we assign this uh actual students with current access student if we can find the class that we increase the most by adding one of these upgrading students then that's the class we want to sign this actual students right and so how do we know that you know the uh then what's going to be the increase right by assigning the current student so for that you know we can use a priority queue right so in python we use a priority queue basically the key of the priority queue will be the increase right of the current class right by uh by accepting by having one of the breeding students right and we want to use basically a max priority queue in that sense because we want to get the we won't find the class who can increase the most right and to do that we have to use uh some negative values right in python to do that because in python the product queue by default is a mini queue so now we have our approach here basically you know we initiate the priority queue right by looping through the by each class all right then we add the increase to the priority along with the p and the t for each class and when we calculate the increase of the rate right so for example so how do we calculate so the increase of the rate is what let's say for example for class one here it's going to be a at the beginning we have one two so the next stage will be one plus one divided by two plus one right which will be this one minus one divided by two right so this is the increase the potential in the potential increase after ratio by having one more uh brilliant student right and then we simply just need to store this information uh we in the priority queue and since we are going to use an active values to get the max value we can simply reverse these two right yeah i think that will be the idea here you know we use the priority queue to maintain the uh the potential increase the ratio increase for each of the class and then we uh we loop through we do a we do actual students times of after priority push and pop and in the end we can simply uh summarize what's left right uh in the what's left in the product queue and then we summarize that divided by the total number of classes okay cool so let's start coding here so we have priority queue here you know to populate the product queue right so we have a p and t right in for each of the classes for each of the class right and then we do a heap q dot uh heap push right to the priority queue like i said the values of that is going to be the key of the value the key of the uh where the sorting or the first element of the product q will be the uh would be the potential increase right and since we're going to store the negative values we do a product p divided by t minus p plus one right so because that's going to be the next state right and then t plus one and then we also need to store the p and t along with it because we will need that to calculate the next stage right so this one basically and as you guys can see so this p plus 1 divided by t plus 1 will always be greater than this one no that's why this one will give us like an active values when which it's exactly what we need in this case because we need a max queue in this case okay so now the next thing is that you know y axis we're going to basically assign each student to the class right when what's one is greater than zero right so we're going to do a hip pop right so the first one is we don't need actually so p and t all we need is p and t hit q dot heap pop right and then priority queue here basically this hip hop will give us the class that we can uh increase the most right by having one more one actual students and after doing that we have a p plus one right and then we have a t plus one right because you know we need we will increase and after that we push it back to the product queue right here push basically this is the new state of the current class right similarly i we just need to copy and paste this one okay and then don't forget to decrease actual students by one right okay and after that you know we just need to return right first let's do a length of the classes right and we can simply return the uh the total sum of the pass ratio right we can use this pnt right to calculate that so we have a sum of the p divided by t right for uh this one p t right in the product q right and then we divided by n right because i because uh after this while loop you know what's left in the product here will be the final state right after assigning the actual student by using this greedy approach right and then we simply just summarize the path ratio for each of the class and then divide it by the number of classes so accept it yeah so passed right and so the time complexity for this one and yeah so we have extra students here right and so let's see we have n classes here you know so this is n right and plus what and plus this one the actual students let's see the actual student is m here right and here we have n here so m plus m times log n right yeah there's another n here but you know okay it's a 2n basically but still it's n plus m times log n so this is going to be the total time complexity for this problem right and the space is all often right so we have a priority prodigy um yep so i think that's it right for this problem you know it's just uh you just have to be able to figure out you know to figure out to use the priority queue to track the basically the current optimal uh solutions right and then you use and then we just use that same approach to assign each of the access to brilliant students to each of the class right so i would say it's a priority or plus grading approach right and other than that i don't think i have anything else we want to talk about here and so i'll just stop here okay thank you for watching this video guys and stay tuned see you guys soon bye
|
Maximum Average Pass Ratio
|
find-the-most-competitive-subsequence
|
There is a school that has classes of students and each class will be having a final exam. You are given a 2D integer array `classes`, where `classes[i] = [passi, totali]`. You know beforehand that in the `ith` class, there are `totali` total students, but only `passi` number of students will pass the exam.
You are also given an integer `extraStudents`. There are another `extraStudents` brilliant students that are **guaranteed** to pass the exam of any class they are assigned to. You want to assign each of the `extraStudents` students to a class in a way that **maximizes** the **average** pass ratio across **all** the classes.
The **pass ratio** of a class is equal to the number of students of the class that will pass the exam divided by the total number of students of the class. The **average pass ratio** is the sum of pass ratios of all the classes divided by the number of the classes.
Return _the **maximum** possible average pass ratio after assigning the_ `extraStudents` _students._ Answers within `10-5` of the actual answer will be accepted.
**Example 1:**
**Input:** classes = \[\[1,2\],\[3,5\],\[2,2\]\], `extraStudents` = 2
**Output:** 0.78333
**Explanation:** You can assign the two extra students to the first class. The average pass ratio will be equal to (3/4 + 3/5 + 2/2) / 3 = 0.78333.
**Example 2:**
**Input:** classes = \[\[2,4\],\[3,9\],\[4,5\],\[2,10\]\], `extraStudents` = 4
**Output:** 0.53485
**Constraints:**
* `1 <= classes.length <= 105`
* `classes[i].length == 2`
* `1 <= passi <= totali <= 105`
* `1 <= extraStudents <= 105`
|
In lexicographical order, the elements to the left have higher priority than those that come after. Can you think of a strategy that incrementally builds the answer from left to right?
|
Array,Stack,Greedy,Monotonic Stack
|
Medium
|
402,1159
|
45
|
Hello Everyone and Welcome Back to my Channel Algorithm A Today I am going to write the code and also explain to you all the algorithm to solve this jump game part two problem which is there in lead code it is a medium level problem and we are Going to solve it using the Gerry algorithm also this problem can be considered as an extension of jump game problem which is also there in lead code it itself so I will provide a link to the solution of that particular problem because it is just a tension. And it would be good for you guys and easier for you guys to understand this problem if you are familiar with that particular problem so please go and watch that too and then continue with this particular problem now let's start it with the name of street cushion. In this problem, people have been given an array named numbers, the indexes in the numbers are representing the positions and the values given in it are values given in it are values given in it are representing from that index to A and as many as we move ahead. We can increase the steps or jump to the next step, okay, like if we look at the row at the index, then two is given, that means, we can go up to the index 0 + 2, that is again two, means, we can go up to the index 0 + 2, that is again two, means, we can go up to the index 0 + 2, that is again two, okay, then if the maximum and then We can go till the first also, okay, then after that, the first index is given on three, so we can jump to 1 + 3, that is the index is given on three, so we can jump to 1 + 3, that is the index is given on three, so we can jump to 1 + 3, that is the maximum, we can jump till the fourth index. Starting from the first index is okay and before that too, any index. That means we can jump on all three, okay 2 3 4, on any one, then if we look for its next, that is the second index, then we are getting to know that we can jump on the third index only. If we can, then by doing this we will find out the maximum jumping capacity of any particular index. It will be that index plus the value present on that index. Okay, then this will be the maximum jumping capacity, but when we solve this problem, then the maximum jumping capacity of any particular index. Along with this, we will keep a track of how much maximum capacity has been reached so far, that means we have any such index beyond which we could have reached the maximum so far through any index. Okay, so like if we If we start taking it from here, then zero will come for the eighth index. Okay, then what will come for the first index is four. But if we start taking out the second index, then again only four will come. The maximum till now will be four and itself. Which is the maximum speed and the off course is three. Okay, so once we have taken out these two things, then after this we will do that if we start with zero eth index, then from zero eth index we will adjust it in such a way that its maximum jumping capacity. That is, we have jumped till there and then from there till where we have jumped, how far can we jump again, which is the maximum till now, okay, we are not going to do this practically but we are just learning this. Now why are we doing this because the number of jumps in both is going to be same like if we look for this then the maximum jumping capacity is coming to zero for eth index so we will jump till here first and By the time we jump till we reach here, we will know that the maximum index till now, that is, the maximum we have till now is coming, that is the fourth index, so we will say that from here we have taken from here, meaning from the fourth index. Jumped to the second index and then jumped from the second index to the last index which is the fourth index, but we are not doing this in reality because if we jump to the second index then we will go to the third index. Ca n't go to fourth index, okay, but we are doing this because we could go from zeroth index to first index true and then from first index we could go directly to fourth index according to its capacity, so if we Going from the zeroth index to the first index and from there to the fourth or from the zeroth index to the second index and from there to the fourth. In both the number of jumps is two, which is fine. Two is coming because from here we could have jumped to the maximum or even before that, so let's say we have jumped somewhere in that entire window which is ours and From there we are able to jump again till the maximum. Okay, if we are able to jump till the next maximum then that means the number of jumps will always be the same in this case even if we jump till the maximum and if we jump a little less than the maximum then The number of jumps will also be the same, but if we assume that it is jumping directly from here to the last index, then it is not practically possible, but we are trying to do this so that our code becomes easy and we To make this question a little easier to understand, let's try it by dry running it. To understand this, we are going to take three variables, that is max and count max is representing the maximum that has come so far. Okay, and represents which index we are going to jump from the particular index where we are currently standing. Okay, that is the maximum. It itself is okay, but the end will be updated less time. Maximum will be updated every time whenever we get a Big A max will be found, okay, and the count is representing how many times the end is updated, okay, so to dry run it, whatever value we have on the zeroth index, we will consider it as max and that itself we will consider as end, okay And the count will be our initial zero, okay, then after that, if we start jumping from here, okay, then we will not do that we will go directly from here, that is, we will go to the end only, we will calculate the maximum of each index point. So we went from zeroth index to the first index and on the first index we saw that max can be updated from two to four, okay so from two to if four can be this, then we updated it but we did not update the end. And why not updated because right now we are in the air, we have not reached there yet, okay after jumping, when will we reach now, when we come to the second index, now when we come to the second index, our maximum is Ca n't be updated because its maximum value is three which is the particular index that is two and plus one which is the value on it then three is a which is less than the max so it will not be updated but in this case And whatever is, it will be updated to max because when we reach whatever f was our target and that is the second index, then again this will be equal to max. From this we will go to the next index which is the third index. The max that comes on this will again come to four, so we will not update the max because it is only four, it is okay and if we do not update the end, then we will not update the count. It is okay when and update. Then only we will update the count, that is and it is changing, that means we have taken one more jump, okay, so now we come to the last index, if we calculate the max for the last index, then it is coming to 8, okay. And we have reached the end, okay, but if we look at the last index of the last index, then the end will also be updated here. Okay, because we have reached from one particular target to another particular target, so if the end is updated, then the count. will also be updated and will become two and in this way we will get our answer because it will end here, okay this will end, then we will return this answer and two will be its answer, okay, now let's code it quickly. Its code is not so tough, but yes, understanding it a bit and taking it intuitively is a bit tough, but it is okay, if we do the questions of greedy algorithm regularly then it will be solved easily. It is okay if two is the length of the array or more. If it is less then what will we return, it means that the number is its length minus the number, okay, why are we doing this, if the length of the array is two, then it is okay, then it will take one jump, it is okay, if there is a length, then there will be some jump. If not then we will return names dot length minus what is zero. Okay, now from here we take a variable max which will be name zero and then we take one count which will again be zero and then we take an int and which That will remain again numbers zero, now let's start looping from here aa int aa will start from ev will not start from zero aa lesson names dot length my aa ps plus then we will update the max every time whenever the new max is given to us You will get the names of i p if i becomes equal to our end that is we have reached the first target meaning first or any target is reached then again we will replace the end with max and increase the count by one and the last I will return the count. Let's run it and see that the answer is wrong. Okay, here's the minus and I have taken it. Let's run it again and see that the sample test cases are running. Let's submit and see that the color answer has come. So let us understand why this color answer is coming, if we see here, if we jump from zero index then its maximum will come first index is fine and if we jump from first index then maximum will come second index but in this the output is coming. One and is expected to be two. This is coming because our Max is getting updated so many times. Max is getting updated three times. It is okay, that means it will be updated only on these three but the one and is getting updated. It is being updated only here, when we are coming to one, that is, when we are starting, then just when the count is zero, then the end of ours is becoming one once and then here, when first When we reach the index, we will calculate its capacity and it will come out as three. Okay, so three is not present anywhere in this array, so the end is getting updated only once. That means it is counting only one jump. Okay, so what we will do to correct that is that we will assume one jump in advance. Okay, and come here, we will take the numbers dot length - 1. That means we will It does take the numbers dot length - 1. That means we will It does n't matter to us whether the last index is updated or not, we will always count the jumps, and then we are doing this because sometimes it will happen that the update that was going to happen on the last index is fine. There will be no end, meaning our end will not be the last index, therefore our end which was supposed to be updated will never be updated and hence our count will be one less than the answer. Okay, that's why we are here. But what we are doing is that we are already taking the count as one, we are already considering the one in which the update was to be done on the last index and without considering the last index, we are taking the loop here from one. Running till the last second index. Okay, now let's run it and see how it is submitted. Now it has been successfully submitted. Before leaving, please like the video and subscribe to my channel. Also share it with your friends if you like. Find This Helpful Thatchy
|
Jump Game II
|
jump-game-ii
|
You are given a **0-indexed** array of integers `nums` of length `n`. You are initially positioned at `nums[0]`.
Each element `nums[i]` represents the maximum length of a forward jump from index `i`. In other words, if you are at `nums[i]`, you can jump to any `nums[i + j]` where:
* `0 <= j <= nums[i]` and
* `i + j < n`
Return _the minimum number of jumps to reach_ `nums[n - 1]`. The test cases are generated such that you can reach `nums[n - 1]`.
**Example 1:**
**Input:** nums = \[2,3,1,1,4\]
**Output:** 2
**Explanation:** The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
**Example 2:**
**Input:** nums = \[2,3,0,1,4\]
**Output:** 2
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 1000`
* It's guaranteed that you can reach `nums[n - 1]`.
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
55,1428,2001
|
120
|
hey everyone today we are going to solve the little question triangle you are given triangle array written the minimum path sum from top to bottom for each step you may move to adjacent number of the row below more formally if you are on the index I on the current row you may move to either index I or index I plus 1 on the next row so let's see the example so you are given this triangle array so minimum paths sum from top to bottom is two plus three plus five plus one so two plus three plus five plus one like this and then a minimum plus sum should be 11 in this case yeah very simple question so let me explain how to solve this question before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all details of all questions in the video and you can get the code from GitHub for free so please subscribe my channel hit the like button or leave a comment thank you for your support okay so let me explain with this example so um all numbers has like two arrows like a left arrow in the right arrow and uh every time we have to calculate the like a left number and the right number so let's say from three uh we have to calculate the three plus six and the three plus five from four and uh four plus five and the four plus seven yeah so looks like a tree structure butter um actually it's not like three because uh from right left number and the right number the it's kind of like a sharing numbers in this case five like from three plus five from four plus five so it's not tracker three so how can we solve this question so to solve this question um so around all arrows are like a goes down but uh I start from bottom to top um because um like on the bottom side um we have a lot of numbers like a very bottom like four numbers and the three numbers and the two numbers and one number so I think it's easy to handle like out of bounds um so that's why I start from bottom so every time so in the like I'm operas I see I start from bottom minus one because uh we don't have to calculate the bottom numbers like a four one five IHC and uh from six um first of all six plus four and ten six plus one and seven so which is a smaller it's easy seven right so minimum number seven and then from five plus one and six five plus eight thirteen so six is a smaller and the A and seven plus eight fifteen seven plus three and ten so tens are smaller up and uh let's um calculate from uh second row so three plus seven and ten three plus six and nine so nine is a smaller and as 4 plus 6 and 10 4 plus 10 and 14 and 10 is a smaller and then um finally uh two plus nine and the two plus ten so two plus nine is a smaller so that's why in this case our output is 11. so yeah that is a basic idea so how can we um I could create a uh this solution so um to solve this question like this um I use a like a dynamic programming so okay um white so create a um so first of all I create uh like a copy of the very bottom um East so like this and the phone number two three and then first of all I copy the bottom row like a full one eight three and then I'll start from sad row and in the subtle um so six is index 0 and the five is index one and the Seven is index two right so um so from 6 we have to calculate the like of six plus four and six plus one so four and one so this list always has like a result of Mega current row so um we have to calculate the same index in this case Zero plus and the number at the current index plus one so which is one in this case so in this case um 6 plus 4 and 6 plus 1 and which is a smaller so definitely six plus one so in this case we change these four to seven because this is index zero and then move next so we find five and in this case uh same index is one so one plus not Plus or one current num current index plus one so which is a index two eight so compare one plus five plus one and then five plus eight and uh total six is a like a smaller than 13 total starting so in this case uh update 1 to 6 because this five is index one so six and then next um this is our index two so I use the same index number and current number plus one so eight and three so seven plus eight fifteen seven plus three ten so 10 is smaller update uh sevens index two so update index 2 to 10. and then finish the iteration on the third row so next go up so we don't have to care about the D3 anymore and then from three so this is a three is index 0 and therefore is the index one so we do the same thing um when we are in the external we use a like a index sterile or plus one in index in this case one so three plus seven or three plus six so which is smaller three plus six so update D7 with nine and then move next um so we find four so four is index one so use index one and the plus one number so 10 so four plus six or four plus 10 so which is smaller so clearly four plus six right so total ten so that's why update six uh to think and then we finish iteration on the second row and so we don't have to care about this tank anymore and then um finally we reach the top in the 11 and not 11 2 and compare uh two plus nine and the 2 plus 10 and 2 plus 9 is a smaller so which is 11 so update index 0 to 11. and then finally um we just returned um index zero in the list this one yeah so that is a basic idea to solve this question so with that being said let's get into the code okay so let's write the code first of all let me copy the triangle array I think it helps you understand what I'm doing and the first of all gets the number of row so row equal rings of triangle and next copy the bottom row so let's say memo equal try angle and uh low minus one dot copy and then start looping um this so we use a two for Loop and that this one is row so I in so let's say rope in length and uh um so start we want to in this case we want to start from sad row and which is our index two zero one two so and the total number of row is four so that's why um start from row minus two and then minus one and the minus one and oh another for Loop is a column in range and uh lens should be low plus one so in the third row which is index 2 so R should be two so if we just add 2 for range um column room just execute it twice but look at the third row we have three numbers so we want to like three Loops so that's why I added plus one so that we can execute column Loop like three times and uh in the for Loop memo and uh Chrome equal first of all take a minimum number so as I explained earlier and the number at the same index number so memo and the column or memo Quran plus one so compare other Json number in them plus triangle and their low and the column yeah that's it after that just a dumb memo and zero yeah so let me delete this one yeah let me submit it okay so it looks good and the time complexity of this solution should be order or any Square because I use nested group here and the space complexity is a order of n so N is a length of bottom row this one so in this case 4 but in other words uh now n is another number of law in input array so one two three four and uh actually I didn't realize um like there is a follow-up question so um like there is a follow-up question so um like there is a follow-up question so could you do this uh using only on extra space when where N is a total number of row in the Triangle so yeah I think uh I did so I think uh this solution works for discussion uh this for like a follow-up question this for like a follow-up question this for like a follow-up question yeah that's all I have for you today if you like it please subscribe Channel hit the like button or leave a comment I'll see you in the next question
|
Triangle
|
triangle
|
Given a `triangle` array, return _the minimum path sum from top to bottom_.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row.
**Example 1:**
**Input:** triangle = \[\[2\],\[3,4\],\[6,5,7\],\[4,1,8,3\]\]
**Output:** 11
**Explanation:** The triangle looks like:
2
3 4
6 5 7
4 1 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
**Example 2:**
**Input:** triangle = \[\[-10\]\]
**Output:** -10
**Constraints:**
* `1 <= triangle.length <= 200`
* `triangle[0].length == 1`
* `triangle[i].length == triangle[i - 1].length + 1`
* `-104 <= triangle[i][j] <= 104`
**Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle?
| null |
Array,Dynamic Programming
|
Medium
| null |
1,496
|
Hello everyone welcome to my channel code sari with mike so today we are going to do video number 14 of our lead code easy playlist it is a very easy question lead code number is 1496 ok the name of the question is path crossing it says that there is a given string whose The name is path, it can be either A, S, E, or T, whatever you are looking for in the string, N E S D, what are all these are directions, itch representing moving one unit, North South East and West. Okay, you start at. Origin 0 on a 2d plane and walk on the path specified by the path. You are currently standing at 0. After that you have to move according to it. All you have to do is tell what is given in the path. Return true if the path crosses. It self at any point Any point in which it has previously come in the past If it comes back to that point then it is OK then you have to return true If it has never come then you have to return false If at any time you are on A location you have previously visited falls other wise ok like let's look at this example NA is like let's say you are standing at 0 ok let's say your 2d plane is what is saying after this first look is North isn't it So North has gone up, so I move it up, North has gone, it has gone up one unit, this is ok, what is East after that, East means it has gone one unit to the right, look after that, it is South, it means it has gone down one unit, it is clear till here, what does it mean? Above is North, here is East, here is West, here is South, here it was on row zero, North East, then it has gone South, pay attention, it has never happened that it has gone to its previous point again, right, all the points are there. New is fine, that's why the answer is false. Now let's take another example. Add, if we accept the example, it remains NE. Okay, so let's see what happens in such a case, initially it is at 0. Okay, I will draw the line here. Let me do it, now first of all North has gone, North means up one unit, okay, after that, East has gone one unit, after that South has gone West, one unit, after that look, West has gone one unit west, which means remember, this one means it has come here, look back. Here a point P has come back which has come back in the past. Remember 0 P has come back. In the past it came back to 0 P and if it comes back to 0 then the answer is true. We will return from here only. Okay, so it is quite easy. Question is, friend, let's start quickly and see how to make it is quite simple friend, see what you have to do simple, if you are at 0, then take x coordinate 0, take y coordinate 0, okay, after that what you have to do. You have to move according to the path given by your input. Okay, so for i = 0 i. This is given by your input. Okay, so for i = 0 i. This is given by your input. Okay, so for i = 0 i. This is less path dot length, it will go to all the characters on the path, then i + p. Okay, now go to all the characters on the path, then i + p. Okay, now go to all the characters on the path, then i + p. Okay, now put a check here that if The I character of the path is Path I, if it is equal to I, if it is East, then here I had told that if it is East, then you will see if it will go right, if it will go one unit right, then see if from here, if it will go right. If the x axis changes or the axis is constant then only one unit will be increased in What did I say, it means it will go left, okay, what does it mean to go left, that the Okay else if East West then North then look what I told you North means going up so one is constant but y is increasing one unit so just increase y plus okay else if not East If there is no West, if there is no North, then it will be South. What did South mean that it will go down? What did going down mean that x is constant but y is decreasing? What will happen in the else y will be in the minus. Okay, so and here. But later whatever will be the value of Okay, so convert it into a string and put it. Look, I have taken a set of strings. Okay, so we will convert So here I will check that if we generate here first, whether we want to search under score, you will string it, then whatever X is, it will be converted into string. If you do score string then wa will also be converted into string. Okay, let's name it and check here whether it has already appeared in That we have already come to y is not equal to add and okay that means we have already seen this I have also visited and if it does not happen, then insert it in the set, add this, insert this key, it is datchi, it was a very simple code, it was a very simple question, it is good for practice, its time complexity is on. What is n, what is the length of the path, okay and here you will say that if you are converting 2 under string, then there is only one character, so I am taking it as a constant, the length of x will be one only, right, x and y whatever. That's the length of one character and add find o will be offv. In orders find operation c+ offv. In orders find operation c+ offv. In orders find operation c+ p, o offv is amortized. Okay, so approximately time complexity will be of n. Let's code quickly and finish it. So let's quickly. Let's start its code and I will code in c + pass, and I will code in c + pass, and I will code in c + pass, you will get exact similar java code, okay, in my Gut Hub description, I have given the link of Gut Hub, you will see there, Java code will also be available, if you scroll down, it is okay. Took the unordered set of strings, first of all, where am I standing, Roma at 0, okay, so first of all, I put this that brother, I have visited 0, so to string It is easier to store in set otherwise you can store in pair also but undock you can store pair in order set ok so I converted it into string itself add insert key is ok for care and see pa of all characters We will go one by one. If the seach turns out to be East, then what does East mean that only In the comment I write, I am going in this direction. Otherwise, if my character turns out to be west, then it is okay, it means I am going to the left side, okay, then x will be minus, y will remain constant, then the direction will be something like this, isn't it left? I am going to the side, FC E, if it is North, then it will be Wa Plus, why because I will be going upwards, then X will be constant, and if C is not East, not West, not North, then it will be South, so I If it is going downwards, then First is not equal to add and if it is checked then return true. If not, then insert it. OK and if you go out of the for loop, no such point is found anywhere which we have checked nearby. So just make return false that there is no such point and then submit and see we should be able to pass all the test cases indeed yes we have solved this question and yaar vacations are coming enjoy the new year well and good Get prepared there is a lot to achieve for 2024 ok see you guys in the next video thank you
|
Path Crossing
|
lucky-numbers-in-a-matrix
|
Given a string `path`, where `path[i] = 'N'`, `'S'`, `'E'` or `'W'`, each representing moving one unit north, south, east, or west, respectively. You start at the origin `(0, 0)` on a 2D plane and walk on the path specified by `path`.
Return `true` _if the path crosses itself at any point, that is, if at any time you are on a location you have previously visited_. Return `false` otherwise.
**Example 1:**
**Input:** path = "NES "
**Output:** false
**Explanation:** Notice that the path doesn't cross any point more than once.
**Example 2:**
**Input:** path = "NESWW "
**Output:** true
**Explanation:** Notice that the path visits the origin twice.
**Constraints:**
* `1 <= path.length <= 104`
* `path[i]` is either `'N'`, `'S'`, `'E'`, or `'W'`.
|
Find out and save the minimum of each row and maximum of each column in two lists. Then scan through the whole matrix to identify the elements that satisfy the criteria.
|
Array,Matrix
|
Easy
| null |
246
|
hey guys how's everything going this is Jay sir who is not good at algorithms in this video I'm going to take a look at 2 4 6 struggle chromatic number this is mark an easy a struggle chromatic number is a number that looks like same we wrote it 100 degrees looked at upside down write a function to determine if a number is struggle chromatic number is represented as a string so 69 if you look from look up upside down it will be 6 9 mm-hmm 6 9 mm-hmm 6 9 mm-hmm I see and the ad a it's 88 9 to 9 6 2 it's not mm-hmm well so it's kind of it's not mm-hmm well so it's kind of it's not mm-hmm well so it's kind of symmetric but in a different ways of symmetric right so obviously we could take a look just to compare the head and a rare right if they are a strobe moment chromatic we books moves to the next pair all right so we use two pointers from left and from the start to the right and from the rear to the left and compare it so how many pairs are there in a strobe book romantic well I think one is Strobel dramatic right it's true so oh yeah okay so one itself is strobo one itself is trouble romantic and of course one is also right cool and 2 is a 2 5 I think that's not right this is nah I hope this is not false oh yeah two three no four no five no six and nine of course nine six is also a pair and then what 7 no 8 is eight all right take think I'm a pair this pair okay eight nine sex right so all the if I take if it is even numbers say a pair of numbers so it must be one these pairs right these are numbers so they will must be one number at the center so it would must be one on eight well okay let's do it so Wow no I let I so the input it may be empty right it's empty then it's the same that I equals zero J equals I think we should start okay I use a IJ cool Wow it will end while I swear man equal and J well let's do the compare if i is equal to j then it must be one and eight right so numb i if it is not one are using crude okay so one eight includes numb i so if it's not in s i returned false right and if it is then we move to next one so I plus 1 J miles so if it is not the pair must be 1 and 6 9 or 9 6 or 8 a mmm how could we check this well let's create another function hmm out how justice wait a minute if is not if it is a stroke Bistro but okay IJ if it is not struggle returning force so we create a separate function call Const its trouble IJ if I equals to J then we return 1 a ok and the other case will be they are not the same so how can I do it a negatively Wow let's do it something like okay this it's just a join them near the string cost this or that in good lets you set grade strobo singles one eight singles has and close airs sect one or 69 or 26 or payday right this is this struggle pairs else return stroke Affairs has we join them together okay so we're done it is returned this so this is a function but okay here okay and finally if they made I made it so I bigger than J they return true I think it should work yeah that's a myth mmm false ah 0 we forgot the zero damn ah yeah zero yeah there's this case zero would be yeah oh really oh yeah sad I couldn't even finish this easy one okay I forgot zero so I forgot the pair of zero which is very sad cool so now we're accepted and it is not that difficult acting the time well we use we traverse through each digit one time linear time so space we use a set they are constant right then it doesn't change long change according to the length of none so yeah space is constant cool so that's all for this one there will be a follow-up this one there will be a follow-up this one there will be a follow-up questions of two and three I'll make the separate videos for that and yes you next time bye
|
Strobogrammatic Number
|
strobogrammatic-number
|
Given a string `num` which represents an integer, return `true` _if_ `num` _is a **strobogrammatic number**_.
A **strobogrammatic number** is a number that looks the same when rotated `180` degrees (looked at upside down).
**Example 1:**
**Input:** num = "69 "
**Output:** true
**Example 2:**
**Input:** num = "88 "
**Output:** true
**Example 3:**
**Input:** num = "962 "
**Output:** false
**Constraints:**
* `1 <= num.length <= 50`
* `num` consists of only digits.
* `num` does not contain any leading zeros except for zero itself.
| null |
Hash Table,Two Pointers,String
|
Easy
|
247,248,1069
|
2,000
|
I have solved over 2 000 legal problems in a year here are some tips I've learned to help you save time and leave code efficiently one focus on easies first especially for beginners often you will see mediums use easys as sub problems and hards use mediums as sub problems so it's important to Master easys first two memorize and understand the patterns not the individual questions if you master a pattern you can easily solve hundreds of similar problems all at once three this may be a hot cake but if you're just beginning go straight to the solutions focus on understanding the optimal solution and building a strong sense of code quality I'd even recommend your first 50 solutions to be straight copy and paste from the discussions and four use Python just trust me I used to use C plus and there are way too many overflow mod verosity and weird idiosyncrasies that just slow down your Lee code learning process follow for more Lego tips thank you
|
Reverse Prefix of Word
|
minimum-speed-to-arrive-on-time
|
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing.
* For example, if `word = "abcdefd "` and `ch = "d "`, then you should **reverse** the segment that starts at `0` and ends at `3` (**inclusive**). The resulting string will be `"dcbaefd "`.
Return _the resulting string_.
**Example 1:**
**Input:** word = "abcdefd ", ch = "d "
**Output:** "dcbaefd "
**Explanation:** The first occurrence of "d " is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd ".
**Example 2:**
**Input:** word = "xyxzxe ", ch = "z "
**Output:** "zxyxxe "
**Explanation:** The first and only occurrence of "z " is at index 3.
Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe ".
**Example 3:**
**Input:** word = "abcd ", ch = "z "
**Output:** "abcd "
**Explanation:** "z " does not exist in word.
You should not do any reverse operation, the resulting string is "abcd ".
**Constraints:**
* `1 <= word.length <= 250`
* `word` consists of lowercase English letters.
* `ch` is a lowercase English letter.
|
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
|
Array,Binary Search
|
Medium
|
1335,2013,2294
|
1,779
|
all right guys welcome back to study plan programming skills day three we still in day three and we should be in the day four was really it's really hard to tackle all these studies plan at once so let's do the last problem in the day three then this problem is find nearest points that are the same x and y coordinates so we have two coordinate x and y and we should return the index of the valid points with the smallest manhattan distance this is the manhattan distance okay and if we don't have any valid universe candidates we'll solve minus one so the value quantitative is just if we have three equal to the first number in our arrays or egreg y equal to the second number of the array so okay let's see how we can do it let's first any other is the manhattan distance by floats and finish and let's initialize the answer by minus one now we care about the index because we want to return to index for the index and points in it enumerates any rate points we should check if the first element equal to x or the second element is equal to y in this case we can will kill the monastery so if point 0.0 point 0.0 point 0.0 equal to x or 0.1 0.1 0.1 equal to y in this case we this is our candidate so we can create the manhattan distance so the distance it should be the up so this is what's an extension will be the absolute value between x minus points 0 plus the absolute value between egreg minus 0.1 okay now if our distance is smaller than one distance so we update mountain distance it will be d and we update the answer it will be the index and finally we return we'll return the and the answer that says some competitors otherwise with all entered space is constant something wrong type like mistake again okay this check should be inside this check another type of mistake i really should work on typo mistakes to minimize them and that's it i hope this video was useful for you and see you soon hopefully ciao
|
Find Nearest Point That Has the Same X or Y Coordinate
|
hopper-company-queries-i
|
You are given two integers, `x` and `y`, which represent your current location on a Cartesian grid: `(x, y)`. You are also given an array `points` where each `points[i] = [ai, bi]` represents that a point exists at `(ai, bi)`. A point is **valid** if it shares the same x-coordinate or the same y-coordinate as your location.
Return _the index **(0-indexed)** of the **valid** point with the smallest **Manhattan distance** from your current location_. If there are multiple, return _the valid point with the **smallest** index_. If there are no valid points, return `-1`.
The **Manhattan distance** between two points `(x1, y1)` and `(x2, y2)` is `abs(x1 - x2) + abs(y1 - y2)`.
**Example 1:**
**Input:** x = 3, y = 4, points = \[\[1,2\],\[3,1\],\[2,4\],\[2,3\],\[4,4\]\]
**Output:** 2
**Explanation:** Of all the points, only \[3,1\], \[2,4\] and \[4,4\] are valid. Of the valid points, \[2,4\] and \[4,4\] have the smallest Manhattan distance from your current location, with a distance of 1. \[2,4\] has the smallest index, so return 2.
**Example 2:**
**Input:** x = 3, y = 4, points = \[\[3,4\]\]
**Output:** 0
**Explanation:** The answer is allowed to be on the same location as your current location.
**Example 3:**
**Input:** x = 3, y = 4, points = \[\[2,3\]\]
**Output:** -1
**Explanation:** There are no valid points.
**Constraints:**
* `1 <= points.length <= 104`
* `points[i].length == 2`
* `1 <= x, y, ai, bi <= 104`
| null |
Database
|
Hard
|
262,1785,1795,2376
|
735
|
welcome to october's leeco challenge today's problem is asteroid collision you are given an array asteroids of integers representing asteroids in a row for each asteroid the absolute value represents its size and the sign represents its direction positive means the asteroid's going right and negative means the asteroids going left each asteroid moves at the same speed find out the state of the asteroids after all collisions if two asteroids meet then the smaller one will explode if both of them are the same size then both will explode and two asteroids moving the same direction will never meet so if we had this example here asteroids 5 10 negative 5 we can see these two will be moving to the right negative 5 here just moving to the left so this is going to collide with ten is bigger than five so that'll explode negative five thereby leaving just ten and in the end our story to look like this five ten moving to the right here we have eight negative eight these explode each other and we'll be left with nothing here since these are moving to the left and next ones are moving to the right they're just moving the opposite direction so they'll never meet so we should immediately recognize this to be a stack problem or a stack solution and what i mean by that is say that we were given this example here what we could do is move through our list of asteroids and add them to a stack in order so we can add five and we can add ten as long as they're in the same direction we can continue to add them but once we find a condition where we have one gonna collide negative five we need to decide do we need to pop off the asteroid that's already on the stack or do we destroy the asteroid that we're going to add and just not add it to the stack so here we can see well 10 is bigger than 5 so we're just not going to have negative 5 and then we just continue our loop okay so the first thing we should recognize is that if these are negative say that we're adding like negative one uh we're never going to pop these off right because whether it's negative or positive coming off coming in um like they'll never they're not going to touch say this we have some positive ones coming in well how are they going to collide with these which are going left these are going right and if we have negative ones going like this these are all going left so they'll never collide there so that's one thing to keep note if what we add on to our stack is negative then it's just never going to apply here all right so here's what we'll do let's start by saying if not asteroids we will just return a empty list i spell that right okay that's so um what we'll first do is build our stack and i think i'll call it output it's going to be an empty list and the very first thing we're going to do is append to our stack the very first asteroid now we're going to go into loop and let's say four asteroid and 4a in asteroids let's start with the second one we are going to well we have to figure out do we need to pop off the ones that we've already added to our stack or could we move on to see what condition needs to be met to decide whether we add to our stack or um or pop off both of them if they're both going to explode so i think what i'll do is have a while loop here and decide should we pop off anything here and after that we're going to meet some conditions conditioned to either append or not or we might need to explode both okay all right so while there is an output and the last item in the output is what's the condition that needs to be met if we need to decide pop off our stack well the last one needs to be positive right so we decide as we explained before and this asteroid needs to be negative moving to the left so that's the only time where we need to decide um if we need to pop off some items on our stack so what we can do here is say okay if all this is true and the absolute value of our asteroid is greater than the since we know this one is already positive if it's greater than the last item on our output then we'll pop off our stack and we'll do this however long it takes to pop off all the asteroids that are moving right and that are smaller than the asteroid that we're that's moving left right now okay so now we need to decide should we add this candidate asteroid so the first thing is well if there's no output left yeah definitely add it because there's nothing to pop off here okay otherwise what do we need to check here okay well i guess what we can check is to see is if um we might not have met this condition but say that they're gonna collide and they're both the same size so how would that work if outputs negative one if it's greater than zero and a is less than zero and these values are equal to one another at least the absolute value of a is equal to one other then not only are we not going to add our candidate asteroid we are going to pop off the one right here because they both explode now we need to decide should we add our um this candidate asteroid should we add it or have we met this condition where uh this asteroid that we're trying to add should have actually been popped or should have been destroyed so to me technician what would take well first um well i guess the absolute value of the output negative one is this right because we know now that this value is negative okay well okay so the first thing is if this guy is negative then we definitely add it right um or if the candidate is positive then we also definitely add it or we have to meet this condition uh if the last item if it's less than our absolute a then we need to also add it i hope i got that right and finally we should be turned off so let me test this i may have missed something here uh this should be 510 okay so i think that worked okay there we go that's accepted uh so i kind of lost it there i wasn't explaining very well but basically this condition here is checking to make sure that either the last item on our stack is negative or since we've already passed this condition and we've popped off everything that would have been destroyed we got to make sure that this asteroid here is positive in order to add it or the size of the last asteroid here which was positive but it's not smaller or i'm sorry it is smaller than the asteroid that we're about to add so that means oh okay i get it so this means that it's making sure that we didn't need to destroy our candidate asteroid because otherwise we should have destroyed it and that's we're not going to append it here all right so it was is this the best solution probably not it is of n but it is kind of confusing with these conditions here but it worked for me and so i think i'm gonna just go with it alright so thanks for watching my channel and remember do not trust me i know nothing
|
Asteroid Collision
|
asteroid-collision
|
We are given an array `asteroids` of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
**Example 1:**
**Input:** asteroids = \[5,10,-5\]
**Output:** \[5,10\]
**Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
**Example 2:**
**Input:** asteroids = \[8,-8\]
**Output:** \[\]
**Explanation:** The 8 and -8 collide exploding each other.
**Example 3:**
**Input:** asteroids = \[10,2,-5\]
**Output:** \[10\]
**Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
**Constraints:**
* `2 <= asteroids.length <= 104`
* `-1000 <= asteroids[i] <= 1000`
* `asteroids[i] != 0`
|
Say a row of asteroids is stable. What happens when a new asteroid is added on the right?
|
Array,Stack
|
Medium
|
605,2245,2317
|
133
|
welcome to this video where we will learn how to clone a graph we have a graph and we are given a vertex that can reach all other vertices and we are asked to create a deep copy of the graph we have to create new vertices both by keeping the same values and the same connections to solve this problem we can think of creating a new node that has the same value as the input node and the same neighbors but this solution doesn't work because what happened when we gave neighbors of the original one to the clone is that we just gave the references so we didn't create new nodes the clone node is pointing to the same nodes which means that we didn't create a deep copy of the graph we just copied the first note not remaining once this solution didn't work what else can we try let's think about the same problem but for tree to clone a tree we can use depth first search we create a node that has the same value as the root then we traverse children of the original node for each one of them we clone it and we add the result to the children of the clone and because children of tree node are also tree nodes we use the same function we will have a recursive process this solution works well for trees we get a deep copy of the tree with new nodes and the same values and conductions let's try it with a graph the input node is 1 we'll create a copy of it the first neighbor is 2 we go to it we'll create a new node that has the same value the first neighbor is 5 we go to it we create a new node that has the same value now this one has no neighbors so return the node we created it enters in neighbors of the previous node and we backtrack next neighbor is 3 we create a node with the same value no neighbors we backtrack the return node enters in neighbors because we're inserting the node returned by the recursive call this one has no more neighbors to visit we return it to the previous node back to the initial node the next neighbor is 3 we go to it and we create a new node with the same value no neighbors we backtrack but wait what do we notice we can't notice that unlike in the original graph one and two aren't pointing to the same note even if the two nodes have the same value but they don't have the same reference so the one that is in neighbors of one is different from the one that is in neighbors of two therefore the graph we're building is different from the original one our solution doesn't work first of all why didn't we get this problem with the tree cloning a tree doesn't have this problem because in a tree nodes cannot have common neighbors like one and two so each node will be cloned only once but in a graph with our solution every time we go to the node with value 3 for example we clone it again which results in different nodes for the same value how to fix this well we want to clone a note only once not more so the solution is that once we clone the value 3 for example we store its reference in hash table and every time we find the value 3 we first check if we didn't clone it before so that instead of creating again a new node we just take the one we created before and by doing so all nodes going to the value 3 will have the same node in their neighbors and our hash table will be of type into node our key will be an integer for example 3 and the value will be the node we created when cloning the value 3. with the previous example we started from 1 we create a node that has the value 1 and put it in the hash table node nodemap of 1 now represents the node we just created then we move to 2 we don't have to in our hash table so we create a node with the value and we store it then we move to 5 same thing we went back to 2 and we went to 3. we don't have 3 in the hash table so we create a new node and sort in node map we went back to 2 we went back to 1 and we went to 3. but now 3 is in our hash table instead of creating a new node with the value 3 which would be different from the one we created before would darkly take the one in the hash table and after it gets inserted in neighbors of 1 and 2 now point to the same node by continuing like that during the whole process we got a clone of the whole graph at the end which is what we wanted to do since the beginning in code our recursive dfs function takes us parameters the initial node and the node map we start by creating clone a node that has the same value as input node next step we put it in node map of node.val we put it in the hash table node.val we put it in the hash table node.val we put it in the hash table where the key is the integer stored now for each neighbor we first check that it's in node map because if it's not it means that we didn't traverse it so we call dfs on it to traverse it create a node for it fill it and put it in the node map now that we made sure that the clone whose values neighbor.val is in node map whose values neighbor.val is in node map whose values neighbor.val is in node map we add it to neighbors of the actual clone we add nodemap of neighbor.file clone we add nodemap of neighbor.file clone we add nodemap of neighbor.file after the loop our clone is ready to be returned we return it and in our main solution function if node is null then the graph is empty we just return null else we create node map which is empty at the beginning and return the result returned by the recursive function by starting from the node given as input for the time complexity we're just performing depth first search and the time complexity of depth first search is off length of v plus length of e where length of v is the number of vertices of the graph and length of either number of edges for the space complexity we also get off length of v plus length of e because we're cloning the graph we're cloning all the length of v vertices and all the length of e edges we reached the end of this video i hope that you understood how to clone a graph suggest me problems to solving comments and see you in the next one
|
Clone Graph
|
clone-graph
|
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph.
Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph.
Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors.
class Node {
public int val;
public List neighbors;
}
**Test case format:**
For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list.
**An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.
The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph.
**Example 1:**
**Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\]
**Explanation:** There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
**Example 2:**
**Input:** adjList = \[\[\]\]
**Output:** \[\[\]\]
**Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
**Example 3:**
**Input:** adjList = \[\]
**Output:** \[\]
**Explanation:** This an empty graph, it does not have any nodes.
**Constraints:**
* The number of nodes in the graph is in the range `[0, 100]`.
* `1 <= Node.val <= 100`
* `Node.val` is unique for each node.
* There are no repeated edges and no self-loops in the graph.
* The Graph is connected and all nodes can be visited starting from the given node.
| null |
Hash Table,Depth-First Search,Breadth-First Search,Graph
|
Medium
|
138,1624,1634
|
112
|
hello there so today we will solve one of the problem on lead code problem number 112. uh it is related to path sum so you will be given a suppose a binary tree and the target sum so if the binary tree has the target sum in any of its box then you need to return true else you need to return false okay so in this case uh suppose the target sum is 5 but there is no path which can sum up to 5 so it will return false so uh you can solve this using recursive way or iterative way as well uh i'll do it the recursive way so uh first of all uh we'll do the sanity check if uh if root is null okay so if root is null then we'll return uh false okay uh sorry we'll return true okay else we'll check uh if uh so okay if root is empty then we will return false so we'll return false here if uh root dot left dot true dot left is equal to null and root dot right is equal to null we'll check if the root uh left and right child uh doesn't have uh but the root value is equal to the target value then it will return true and root dot val if it is equal to sum then return true okay now the last condition the recursive way i'll call this has bathsome okay and in this i'll pass root dot left and some minus root dot left dot val or so if either left path or right part if any of them is equal to target value then we will return true okay so in this case it will be right okay say if any of them uh returns true then in that case uh will return true so this is the sandy check uh will it return false because of this uh this if this condition will be true if the root itself is equal to target value and otherwise we'll call this as many times and until unless this will return either true or false okay so let's see if this solves the problem okay so success means the solution is correct and uh you can go through the description or you can pause the video uh to understand uh how this part things work uh if you still have question you can write in the comment section and if you think the videos are helpful do like the video and subscribe to the channel
|
Path Sum
|
path-sum
|
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22
**Output:** true
**Explanation:** The root-to-leaf path with the target sum is shown.
**Example 2:**
**Input:** root = \[1,2,3\], targetSum = 5
**Output:** false
**Explanation:** There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
**Example 3:**
**Input:** root = \[\], targetSum = 0
**Output:** false
**Explanation:** Since the tree is empty, there are no root-to-leaf paths.
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
113,124,129,437,666
|
198
|
okay let's solve leak code 198 house robber in my opinion this is such a good question to understand even though it's just an easy question you can learn so much about dynamic programming from this problem and you might already know Google really loves asking dynamic programming problems and if you want to get started on that this is such a good question to understand so we're basically given an array of integers like many problems and each integer represents a house right so this is a house they're all houses and they're adjacent to each other so it's basically a neighborhood we want to rob houses to maximize the amount of money we can rob so why not just rob all of them right nope there's a restriction we can't rob two houses that are adjacent to each other so we can rob this house but then we can't rob this house right so we have to rob this one next maybe right on the other hand if we rob this one we can't rob this one and we can't rob this one it has two neighbors this might sound really difficult right so let's just start out with the brute force approach let's imagine if we were trying to get every single combination okay so the first combination is where we pick the first house right so let's draw out what the decision tree of that would look like okay so our first decision was to rob the house with value one okay so next we want to rob more houses right but we can't rob this one so we can we have to basically get the max we can Rob from these two so does that sound kind of like a sub problem yeah but we'll get there in a minute so continuing on with just a brute-force right okay so now we just a brute-force right okay so now we just a brute-force right okay so now we want to rob these two houses right well we can't rob both of them because they're right next to each other so we can either rob house 3 or we can rob house 1 so this is the decision tree right and so along this path so if we were to rob house 1 right let's say we went along this path then we can either rob house 1 and 3 or we can rob house 1 and 1 obviously we're gonna choose this one because that gives us the total that gives us the maximum which is 4 okay but what if we didn't Rob the first house we decided to rob the second so that would be our other decision in our decision tree right Rob house - okay our decision tree right Rob house - okay our decision tree right Rob house - okay now we have not many choices right we can't Rob house three so the only house left is house one so we rob that one as well so if we went along this pathway in our decision tree we would get these two houses robbed and that's a total of three but we remember we found this which was a total of four which is greater of course so that's going to be our result now this is a very brute-force approach imagine if we had brute-force approach imagine if we had brute-force approach imagine if we had more numbers here right maybe a three and a four then we'd have to have like more paths in our decision tree this could get very complex so how can we improve it can we identify any subproblem and the answer to that is yes let's take a look at the subproblem so remember we have two choices we want to get the max that we can rob from this entire neighborhood so the first choice is we rob from the first house and then find the maximum from the remaining houses right imagine there's more houses here there could be a three or four whatever right this is the subproblem we're finding the max of a sub array of the entire array the second choice we have is we skip this house right if we skip it then basically we're saying okay find the maximum of the entire sub array not including the first value so let's actually write out the relationship if it doesn't make sense yet so if we want to find the max we can Rob from the entire array we have two choices Rob in this case indicates the max that we can Rob from the entire array so in our first decision we decided that we were gonna Rob the first value so array of index 0 plus Rob the remainder of this blue portion of the array so we're skipping index 1 we're gonna Rob the entire array from index 2 to the end so I'll say n is the end in this case so that's our first decision if we decided to rob the first house then we're gonna break up the problem into a sub problem now we got to Rob the remainder of that array skipping one of the values if we didn't rob the first house and then we simply only have the sub-problem robbed every only have the sub-problem robbed every only have the sub-problem robbed every house skipping the first house so we start at house one not house zero and go until the end of the array so this is the recurrence relationship you might not know exactly what that means but it's basically a way to break up dynamic programming problems notice the result of the entire problem depends on only these two if we can compute these two then we have our result but notice each Rob can be broken up into its own sub-problem just like we into its own sub-problem just like we into its own sub-problem just like we did over here so let's actually solve the subproblems now before we solve the entire problem now I could do this in reverse order right I could say let's find the max of this sub array and so on but it's a little more confusing to do that so I'm actually going to do it in order so let's start at the first house like we've been doing so if we rob this house that's basically our base case right so we can decide to rob this house in that case up until this point we could Rob a total of 1 ok now we get to the second house so what's the max we can Rob up until this point well we can decide to not rob this house and only rob this house if we wanted to or we can decide to not rob this house and only rob this house to is obviously greater than 1 so I'm gonna decide only to rob this house next we get to house 3 this is where it gets interesting so what's the max amount we can Rob up until this point so we have two choices again we can Rob house 3 and we can Rob house 1 or we can just Rob house to the max is obviously if we Rob house 3 and 1 and in that case we'd get a total of 4 now we get to the last value 1 so we can decide to Rob house 1 and if we did Rob house 1 then we would want the max we could Rob up until these two values meaning we'd want 1 plus 2 because 2 tells us what's the max we can Rob from these first two elements we include this one because it's adjacent to one so one of our choices is one plus two that's choice one or we can decide to not even Rob house one we can just get the max of the entire first three elements not including this one in that case we have what we would get from the first three elements right here we already computed it's four so our choices are one plus two or four obviously four is greater so I'm gonna choose four that means we put a four right here and this for this last four means that for the entire array the max value we could get is four if we wanted to rob houses so we can put a 4 here but notice how we don't have to look we don't even have to store this entire blue portion for each value like for this one for to compute this we only need to look at the previous two results that we computed and the reason for that is because we could either decide to rob this one and Rob the remainder portion of the array not including 3 and in which case we'd have the value computed right here the other cases if we wanted the max we could Rob from the entire array we could decide to not even include this and just get the max from these three and in that case the value would be stored here so now let's look at the code since we only need to maintain the last two maxes that we could rob from we'll only need two variables so I'll just name them Rob 1 Rob 2 we'll initialize them as zero because if we get an empty sub-array we because if we get an empty sub-array we because if we get an empty sub-array we want to return zero anyway so let's iterate through each of the houses we can Rob and now we want to compute the maximum that we can Rob up and tell this value n so I'm gonna compute that in a temporary variable for now and you'll probably see why so the max we can Rob up until now in my case I'm gonna say Rob 1 or Rob 2 was the last house that we robbed Rob one was the one before that so knowing that the max we could get would be n+ Rob one meaning there's get would be n+ Rob one meaning there's get would be n+ Rob one meaning there's a gap between the current house and the previous house or Rob two which includes the previous house in case it's not clear this is basically let me just make a comment to show what I mean by Rob 1 and Rob - so Rob 1 is first and Rob - so Rob 1 is first and Rob - so Rob 1 is first Rob 2 comes second and then we get some more values and n plus 1 and so on so if I want a Rob n then I have to Rob one as well I can't use Rob 2 but if I want to do Rob - I can include but if I want to do Rob - I can include but if I want to do Rob - I can include n because it's right next to it so when we iterate to the next position meaning we get here we want to update Rob one to now equal Rob - so let's do that now equal Rob - so let's do that now equal Rob - so let's do that and Rob 2 in this case wants to be updated to n so Rob 2 can now equal our temporary value that we just computed at the end we want to return Rob 2 because by the time we get to the end Rob 2 will be equal to the last value meaning that it will be the max we can rob from the entire neighborhood of houses this is a problem you can learn so much from even though it's an easy problem it might take you a while to digest exactly what's going on and to understand all the like importance of this problem so many dynamic program programming problems are built upon this one and let me know if you have any questions because I feel like I might not have explained like the recurrence relationship quite well enough but if this was helpful thank you for watching leave a like and subscribe and let me know if you have any suggestions
|
House Robber
|
house-robber
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 2:**
**Input:** nums = \[2,7,9,3,1\]
**Output:** 12
**Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 400`
| null |
Array,Dynamic Programming
|
Medium
|
152,213,256,276,337,600,656,740,2262
|
827
|
hello and welcome back to the cracking fang youtube channel today we're going to be solving leak code problem 827 making a large island before we get into this problem i just want to say if you haven't watched my videos on either max area of an island or number of islands please go watch those videos we're going to be using some of the same techniques to solve uh this question that we used to solve that one and if you don't know how to solve those you definitely won't know how to solve this one so please go back and watch those first because they lay the foundation of how to solve this problem is labeled a hard on leak code and you're going to need some of the principles that we learned in the mediums that use the same topic to actually solve this one so that being said let's get into the question prompt you're given an n by n binary matrix grid you're allowed to change at most one zero to be a one return the size of the largest island in the grid after applying this operation an island is a four directionally connected group of ones so for example if we have this island here which is or sorry we have this grid here right and we can see that there's one island currently and it's the island you know with these two tiles so what's the largest area if we could flip one zero to a one well we could see that if we flipped either of the zeros we'd get an island of size three right if we made this a one then we'd get a size three so the answer here is three and you know it seems quite simple how to do this if you're looking at the grid but how to do this programmatically is a little bit tricky so the naive solution would be to simply go throughout the grid every time you see a zero transform it to a one and then kick off a depth first search in all four directions to basically count the number of islands adjacent to it similar to how we did max area of an island and then add that up and then keep a result going as we go the problem with this solution though is that you're going to end up recomputing the areas for multiple islands for example if you were to do this here you'd compute the area of this island which is here but then when you get here you'd be recomputing that so unless you did some sort of memoization you would actually essentially uh end up repeating a lot of calculations which we don't want to do what we want to do is actually pre-compute the areas of each island pre-compute the areas of each island pre-compute the areas of each island and the thing is we don't want to count an island multiple times right because if we say okay well if we're at this zero here and we flip it to a one and we go to the left and then our dfs is going to go in all four directions we will accidentally count this island twice right we'll go here and it's going to count this entire island if we do a dfs but then when we go down as part of our original dfs we'll get here and that will dfs into the top one and we'll actually count it twice so we have to have some mechanism to actually count our islands in a unique way so what we're going to do for this problem is actually we're going to do one iteration through our entire grid just to figure out the distinct number of islands and what i mean by this is let's say we have a bigger grid here and we'll kind of just draw it out and let's say we have an island up here we have some zero we have an island here so this is an island and then maybe there's an island over here right these are all distinct islands let me just change my color so this is going to be an island and this is going to be an island what we want to do when we go through our first iteration here is actually to change all of these ones to whatever the island id is and we're going to start the island id at 2 and the reason we want to start it at 2 is that way we don't end up overwriting um characters that we've already used we can use two or we could use something like negative one and then go to like negative two that way we make sure that we don't actually end up writing a value that's already in the grid so for example let's say we started with you know negative one as our island id so we start here at the top left and we'd see that this is an island because it's a one so we're gonna set all of the tiles that this island touches to be equal to negative one and so we're gonna set this equal to negative one and now that our dfs finishes here and we found this island we can then move on to island id minus two so the next island we see we're gonna set all of the values of that island to be negative two so we keep going you know traversing over our grid to find all the islands and we get to this one now right so we're gonna set its value to negative two and again we're gonna try to kick off our dfs in all four directions but we can see that there's actually no more islands here so that means that this is the only one in the island which id negative two and what we're gonna do is we're gonna have a dictionary which maps the island id to the actual area of the island so this one was area two we have area island with id negative two and its area is one and then we'll see that you know now our id is going to be negative three and we're gonna have this island of area two so we know we set these equal to negative three so now we have negative three and two so the reason that we want to do this is i guess when we go through for a second time and we get to a zero now we don't actually have to dfs into our surrounding tiles to figure out the area of those islands we can simply say okay well you know we start at this zero we're gonna flip it into a one and we need to figure out the area of the islands uh that would be formed if this was a one so what we need to do is basically is there an island to the left of me if yes i wanna add its area to my current area which is one is there an island to the top of me if yes and i haven't seen that island because it could be the case that this is also you know negative one so that's why we have these set to negative ones we can maintain a set of all the islands that we've taken points from to make sure that we don't have duplicates because we don't want to count the area of an island multiple times so for example when we go left we want to take the area of islands with an id of minus one then we go and go to the right we can see that there's an island with negative two id so we get its area which is one and then obviously minus one was two then when we go down we can see that there's no island here and we go up obviously this is outside of the grid so that's not valid so we would wanna add the area that we get from flipping this zero to a one so that's going to be one plus the area of the island minus one which was next to our you know point that we just flipped so we add the two and then the area of the island with id minus two which was to the right of our current island so that means our new island would be this big one here that we form and it's of id4 and this is going to enable us to basically not have to do the dfs each time to calculate the area because we've pre-calculated it we've stored it here pre-calculated it we've stored it here pre-calculated it we've stored it here and we can essentially just reuse the computation but remember we have to keep track of the islands that are next to us with a set because we don't want to accidentally count uh an island multiple times uh in the case that it actually has like for example if this tile here was negative one then we would count this as the area here but this already includes it and then if we went down we accidentally double count it so that's why we want the set here to make sure that we only count islands one time so this drawing is getting pretty much into like a bowl of spaghetti here it's getting really messy and i think at this point what i want to do is actually transition into the code editor where we're going to type this out go through it line by line and hopefully it should be a whole lot more clear because it is a little bit confusing to look at the example uh especially with all of the kind of squiggles going on so let's stop this here let's go to the code editor and write this up it's really not that bad of a problem it is a quite a bit a lot of quite a bit of code but it's not really that complicated you should know how to do this from those previous problems that i told you should know how to solve before trying this one anyway that's enough rambling for real let's go to the code editor okay we're in the code editor let's code this up remember that i told you that we want to have an island id which is going to keep track of each individual island so that way we can overwrite its value in the grid and that way when we go back for a second time we can actually know which island we're working on in a really quick way so let's say that self.islandid is going to start at that self.islandid is going to start at that self.islandid is going to start at -1 because we don't want any clashes -1 because we don't want any clashes -1 because we don't want any clashes with the values that are already in the grid which are 0 and 1. so obviously we don't want to start it at 0 we don't want to start it at 1 because that's going to make problems for us and we also need a dictionary which is going to map the island id to its area so we're going to say self.island areas so we're going to say self.island areas so we're going to say self.island areas is going to equal to just an empty dictionary and this is one of those grid problems where we're kicking off a depth first search in four directions so we need to define our directions so we're gonna say self.directions and gonna say self.directions and gonna say self.directions and pretty standard we're gonna have our four directions here so let's just code these out and those are the four directions we can travel in now what we need to do remember for the first iteration through our grid what we want to do is go through and find the area of each island set its um tile values to whatever the current island id is and then at the end update our island areas with the total area of our island and remember that uh essentially this is the same process that we did in the problem finding the area of an island right so let's do it we're going to say 4m in range whoops range lan grid we're going to say 4n in range len grid of m we're going to say okay if the current value is a 1 that means it's an island value so that means that we want to kick off our dfs here so we're going to say if grid of m comma n equals a one that means that this is a new island that we're visiting we want to find all of its tiles so we're going to say island area is going to be equal to our dfs function which we'll write in a second and the dfs function is going to take our grid and it's going to take our current m and n position and now that we have the island area we want to put that into our dictionary so we're going to say self.island areas we're going to say self.island areas we're going to say self.island areas of let's see um self.island id uh is going to equal to self.island id uh is going to equal to self.island id uh is going to equal to the island area whoops island area and then we want to basically now increment our island id although because we're using negatives we're actually just going to decrement it so we're going to say self the island id we're gonna decrement it by once now we have a new unique id for the next time we go through our uh thing here so at this point in our function we're actually gonna have all of the areas for each of the islands and their values will be overwritten inside of the dfs function which we'll write in a second so now what we want to do is we want to define our answer which is going to be max area and what we need to do is go through for a second time and basically flip each 0 to a 1 and figure out the maximum area we can get by essentially doing that so let's go through the grid one more time we're going to say 4m in range uh length grid we're going to say 4n in range lan grid of m we're going to say okay if the current position is actually a 0 then we want to flip it to a 1 and figure out what the maximum area is if we were to do that so we're going to say if not grid of m n so essentially if our current value is a zero we're gonna say the area is one because that zero flips into a one so that is at least an island of area one and then we wanna keep track of all of the distinct surrounding islands uh touching that current position it could be the case that you know to our left and you know above us so up and to the left of us in the grid is actually the same island so we only want to count it once because we're going to add the area of that island and we don't want to count it twice so we're going to say surrounding is going to equal to a set and now what we want to do is look in all four directions figure out all the distinct islands uh four directionally and add their areas to us so we're gonna say 4m increment and increment in self.directions what we want to do is we self.directions what we want to do is we self.directions what we want to do is we want to say that the new m is going to equal to m plus the increment of m so m increment oops m inc and we're going to say the new n equals to the old n plus oops uh n increment and now what we want to do is we want to check first of all is our new m n combination so the new row and column is inside of the grid obviously we don't want an index error and we want to make sure that the um the new rowing column position the value there isn't actually a zero because if it's a zero we don't care it's not an island we can't take its value um so what we want to do is we want to check that so we want to say if uh the new position so we want to make sure we're in the grid so we're going to say new m less than length grid and we're going to say the new n is also less than line grid 0. so that's going to check the columns and we want to make sure that grid let me just move this over so we can have some more space here grid of new m uh new n does not equal to zero so we want to make sure that the new value at that index new m new n is actually an island if it's not then we don't care about it so we're going to say surrounding dot add grid of whatever new m and new n is remember that we don't want to be double counting things because then we're going to get the wrong answer we only want to sum the areas of the distinct islands that are touching our current position cool so now we've done that and now we need to actually add those areas because all we did was actually just add the ids of the surrounding areas remember that we overwrote the grid position at that index with the island id so now we know all the ids that are neighboring us because they're in the surrounding set and now what we can do is actually just add them to our area which remember is just one because we all we've done so far is flip that zero into a one so what we want to do now is we're going to say for island id in surrounding all we want to do is add to our current area the value from the island area's dictionary uh for whatever that island id is and that's going to be the area of the island that we can form by flipping our current position which is a zero into a one now all we need to do is simply um check that this is a maximum so we just want to say max area which is the variable storing our solution we just want to take the maximum of whatever its current value is and our new area and if our area is greater then obviously that becomes the new best answer so once we do this process for every single zero in our grid what we want to do is actually return our answer now here's where an interesting edge case comes up what happens when the entire grid is ones well if the entire grid is one we'll never actually hit this point here and we'll never actually end up updating our max area because the only time this if statement fires is when we're at a position in the grid that's zero if the entire grid is an island in this case here then we would actually just return zero because max area currently returns zero so what we need to do is check actually have we seen an island because if we haven't seen an island uh sorry if our max area is still zero at the end of this double for loop that means that the entire grid is actually an island and in that case we don't want to return zero obviously that's the wrong answer we just want to return the dimensions of our grid and remember it's an n by n matrix so we just want to return you know n squared that's going to be our solution so that's the last thing we have to check we're going to say return max area if basically max area is non-zero right basically max area is non-zero right basically max area is non-zero right otherwise uh we just want to return the length of the grid squared and remember the grid is n by n so it's just length of the grid uh squared and that's going to be our final solution there so that being said we still need to define the dfs function which is actually going to calculate the area so we're just going to do this quite quickly because you should already know how to do this from the previous max area of an island so we you know have our grid we have our m position we have our end position and essentially what we want to do is we just want to find uh sum all the areas of all the adjacent points that are part of our current island so what we want to do is we want to basically just check that we're even in the bounds of our grid so far so we're going to say if 0 less than or equal to m less than or equal to grid and so that basically checks the rows and we want to check the columns here so n less than len grid of m and basically the last thing that we want to do is we just want to make sure that we're actually at a um an island value right if our current position is actually a zero that means it's water uh and that isn't a valid position so we just want to exit out of our dfs here because we don't want to be summing anything here if it's water we don't sum it so we just want to make sure that grid of m comma n actually equals to 1 which is land in this case what we want to do is remember we want to overwrite the current value with whatever self the island id is and what we want to do is we want to say area equals 1 and then we just want to go four directionally and figure out what the area is by basically applying our dfs function to the four adjacent tiles to us so we're going to say 4m increment and increment in self.directions in self.directions in self.directions what we want to do is we want to say area plus equals to self.dfs area plus equals to self.dfs area plus equals to self.dfs uh grid m plus m increment oops m increment n plus and increment and at this point all we want to do is return the area and then for the if statement basically if we're outside of the bounds of the grid or our current position is water then all we want to do is return zero because that's not going to affect our answer obviously adding zero to anything just returns whatever you added that zero to so that is the dfs function uh this is where we called it in here in the initial pass-through of our um loop here initial pass-through of our um loop here initial pass-through of our um loop here so let me just run this make sure i haven't made any syntax errors because obviously this is quite a lot of code it looks like it's running let me just submit it hopefully i didn't waste five minutes of my life typing this and after this problem goes it's um quite a large example test cases hopefully this runs okay cool it ran perfect so last thing that we need to do is talk about the time and space complexity here so what is the time and space complexity of our algorithm well what is the worst case here so in the first example we basically go over every single tile in our grid so doing that is going to take big o of n squared time now we go through a second time which is going to also take you know big o of n squared time and the reason for this is because we could have the worst case where actually all of the degree is actually ones so we would basically kick off our dfs from the top left and we'd have to touch every single position once in the grid as part of the dfs so we're going to end up doing two times you know uh so basically big o of n squared and then the second pass through is also going to be big o of n squared where n is the you know dimensions of our grid so n squared because obviously it's an m by n matrix so there's n squared values uh in our grid so our time complexity is you know asymptotically just going to be big o of n squared space complexity wise um in the worst case there's going to be half the grid is going to be zeros and half the grid is going to be ones in this case we basically have to store um big o of n squared over two islands so in this case uh you know half of the grid would be you know distinct islands uh and then the other half would be water so we'd end up storing n squared over two grids in our um self dot island areas here so because of that our space complexity is also going to be big o of n squared so that is how you solve making a large island i think this problem is quite cool it uses a lot of the concepts that you learn in other medium level questions and i think this is definitely a fair question for the hard because it basically requires you to um think about how you might abstract away that recomputed part by using some sort of like memoization which we do here with the island areas and then simply just checking the id of the surrounding area um and that way we can just add the area very quickly because we've pre-computed it in our because we've pre-computed it in our because we've pre-computed it in our first pass-through so that's why this first pass-through so that's why this first pass-through so that's why this question is a hard one although not the most difficult heart i think it's relatively straightforward especially once you see a video like this i was having a lot of trouble solving this question at first but then i saw a video with an algorithm very similar to this and it just absolutely made everything click and hopefully um the same thing happens for you anyway i'm going to stop rambling because this video is probably 20 minutes long if you enjoyed the video please leave a like and a comment it really helps with the youtube algorithm if you want to see more content like this please subscribe to the channel i have a ton of videos helping you solve these leak code questions and i plan to make a whole ton more so please subscribe so you don't miss future videos otherwise thank you so much for watching this video and have a nice rest of your day
|
Making A Large Island
|
expressive-words
|
You are given an `n x n` binary matrix `grid`. You are allowed to change **at most one** `0` to be `1`.
Return _the size of the largest **island** in_ `grid` _after applying this operation_.
An **island** is a 4-directionally connected group of `1`s.
**Example 1:**
**Input:** grid = \[\[1,0\],\[0,1\]\]
**Output:** 3
**Explanation:** Change one 0 to 1 and connect two 1s, then we get an island with area = 3.
**Example 2:**
**Input:** grid = \[\[1,1\],\[1,0\]\]
**Output:** 4
**Explanation:** Change the 0 to 1 and make the island bigger, only one island with area = 4.
**Example 3:**
**Input:** grid = \[\[1,1\],\[1,1\]\]
**Output:** 4
**Explanation:** Can't change any 0 to 1, only one island with area = 4.
**Constraints:**
* `n == grid.length`
* `n == grid[i].length`
* `1 <= n <= 500`
* `grid[i][j]` is either `0` or `1`.
| null |
Array,Two Pointers,String
|
Medium
| null |
168
|
That In This Problem Business Convert A Number To Back Reporting Column In Excel Sheet You All Must Have Used Excel Sheet Android Columbus Rose Number One Two Three Four And When Everything Starts From Government In More BCD Withdrawal Single Digit Names Start With Eggs Paying Them All Subscribe Do a goodbye subscribe now to receive that input stuart bay easy and all the way to shyam app to read all in capital letters 1027 is this 10 b aap soe rims constant for next 19 person 52nd eggs and subscribe to find its chief V Ki Suzy 241 Tractor Use Buddhist Scripts Which Changes Everything Changes By b4m That From Here Till Gautam In Politics Of Today Its Beneficial Planet Can Take Medicine Subscribe Column Names With 2012 2072 18 Se Z Ki Jis Limits 676 Front Isse Zee TV Show The Subscribe To That NH 80 30 Reply Tomorrow Morning To Find Petrol It's Not A Division Will Give Settings Patam Her Through It's Verdict Seervi ABCD Subscribe Who Is Constant And Every Field Under Exclusive One Next Between Constant And Again To reduce and subscribe 120 6 me vyavdhaan character to 1972 a that some character respect and that day 5278 so it's Ben10 to solid countries like this series for updates please some day and number of possible combinations of 2626 cross 6This last character will change after every Value ABCD Will Be A Good subscribe and subscribe the Channel subscribe 6 subscribe and subscribe the Channel and subscribe This Supreme 2722 It's A Shift Us Jor 2108 That It Will Be C And Vansham Order Number 66 But Last subscribe The Video then subscribe to the Page if you liked The Video then Tomorrow Morning Pimental You Take That In Texture Is Its Reminder Jeevan Sweet A First Character Teaches English Cases 60 For Last Correctly Suggestion On Thursday That Vinod Now Last Character It Maps Different Dates With Don't Know Harm In Addition But Way Can spread way and shoulder the last chapter note 31 number lipstick model with 60 ko switch off banwai the soul can e write a generic statement record and so let's check the character is its value of lemon reduce reminder loot computer model way result with ugh that this dharmendra into it's off but this wishes 21 subscribe to a super bb11 reminder is to back to end 131 rates a pinch of fennel pm plus 4 subscribe 0 interest person I want to be with you in this will have to make from throat so 15 Blind That Jis Zero Christmas To Do n't Push Hard With A Flat Number Plate 52260 Subscribe To Tomorrow Morning Thank You Think In Terms Of Wool Writing Record 340 Benefit subscribe our Channel Please subscribe and subscribe the Video then subscribe to the Page Cheating 21st Plated Glass Tractors pendant weakness vid oo ki election whatsapp birnu and wept calculate the last character nau and toubro jis suggestion - one is the subscribe suggestion - one is the subscribe suggestion - one is the subscribe is 2752 and 2017 to A6 plus 0602 actions will help you will be amazed from 126 202 to 222 121 because point to Subscribe Calculated On Days 5278 wap2 100 Map To Three And Sonu So Let's See How We Can Do The Hidden More That Get One Point Something Sudhir 152 Infect Subservient To 6000 From This 6 To 251 Is Dynasty 1954 Infectious And Shioji subscribe and subscribe to subscribe our YouTube Channel subscribe ki discus want to see amazon sweater subscribe molu ki distance between them under avi show last characters - days of wave 6 plus app avi show last characters - days of wave 6 plus app avi show last characters - days of wave 6 plus app in which comes and minus one divide bike 35mm but print will withdraw all characters and comes on Subscriptions are there but very hui ko switch results jaldi do and the boys are yaar hua hai kar do hua hai ki and will result in ki and swords subscribe 220 6070 8 minutes from this so let's submit according to zameen active voice and faster Than Hundred Percent The Missions Are And Appointed In Python Also So Let's Do The Police Will Take The Sky Value Of A Guru Can Be Cleared 657 And Sudesh Will Take Place Can They Reduce And December And Mind Will Convert Into Character That And Swim I Apni To -Do pattern solution inside the interior division this updated
|
Excel Sheet Column Title
|
excel-sheet-column-title
|
Given an integer `columnNumber`, return _its corresponding column title as it appears in an Excel sheet_.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
**Example 1:**
**Input:** columnNumber = 1
**Output:** "A "
**Example 2:**
**Input:** columnNumber = 28
**Output:** "AB "
**Example 3:**
**Input:** columnNumber = 701
**Output:** "ZY "
**Constraints:**
* `1 <= columnNumber <= 231 - 1`
| null |
Math,String
|
Easy
|
171,2304
|
297
|
hello friends welcome to join our flight so today once again we are going to look at a hard level problem from lead code the problem number is 297. it's about serialized and dc realize a binary tree it's a hard problem so the description says serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or a memory buffer or transmitted across a network connection link to be reconstructed later in the same or another computer environment design an algorithm to serialize and deserialize a binary tree there is no restriction on how you how your serialization deserialization algorithm should work you just need to ensure that a binary tree can be serialized to a string and the string can be designated back to the original tree so here is an example your input will be given like one two three null four five so one being the root node two three is the child of one uh both the nulls are childs of uh two as you see they don't have any child nodes for three it is uh four and five so there are a couple of methods that we need to implement one is a serialized method which will take a node and it should give the string representation for the serialized tray and the serialized method which will take a string and give you a trig node back which should represent this tree over here so we are going to check the solution and before we look at before you look at my solution as i always recommend do give it a try yourself and see if you can come up with your own solution and then take a peek at my solution so let's move over to the board and check out the solution so i have taken the same tree that we have seen in the example which has a which is a root one then followed by two and three has two child four and five so the input will be given to us in this format so first we are going to look at the serialization process and then we will see the dc realization if you see this free we are will be getting an input like this and we need to come up with our own serialized format of the string so how we are going to do this is basically we are going to first complete the tree so this is the tree over here so a few things are not shown over here so let's put that into place first and we will see how it looks so 2 has a child's left child which is null right child which is null same goes for four and five so this is what the tree actually looks like when we are going to serialize it so how this process will go uh let's understand this what will be the serialized string so this is the string that we are talking about so first we have a one that is the root element over here then one has two child so the next two elements are the child of one so this is connected to left child and this is the right child so it will have two and three so we are filling from left to right then we have uh two elements uh for uh two child so let's mark it with a different color so two has two more childs that comes over here and what are they are nothing but null right then we have two more placeholders for three child so three will have the first child over here and the second child over here so the first child always implies the left child okay and the second one implies the right side so three has two childs that are four and five so the next two place holder would be force left child and right side what are they are basically nulls one thing keep in mind when we have nulls we will not consider their child so that's why we skipped from three to four directly and not going by those ends okay so we are done with four then we have five and the five will have 2 childs that is over here so 5's left child and 5's right side so they are also nothing but null so we are done with 5 and then we have bunch of 10 so we are not considering n so we'll go over them and this will be our output string right so we are going to talk about a serialization uh function over here and we'll see how it will be depicted in the tree form as well so what we are going to do is we are going to come up with the algorithm now so we are going to create a method called serialize and which will take a node okay so if you look carefully at the problem statement what you will see is that the value is represented by integer so we are free to use any character that we want and we are going to use n the one that we have used over here to mark the null nodes okay so the first step that we should do in the serialization function is to put that if mode is null then we are going to return the character n okay so if it is null so for all these nodes over here all these nodes we are going to return a n okay and if you look at the serialization structure what we do is we first print the node means we first append the value to the node and then we pass it on right so this is nothing but the array or a string separated by a comma so what are we going to do over here is we are going to print the node dot val so this value of the node then we are going to put a comma as we have seen um here that it's we need a separator right to identify if the number is 15 i don't know it's uh 1 5 or just a 15 right so we need this delimiter to be a very important character if we don't put this it becomes a string like this wherein i cannot make it out so i need to put this delimiter character over here that's why you are putting the delimiter over here and then we are going to call the serialize method again first is the left element right so we are putting the left first and then we are putting the right in our serialized version of the string so that's why we are going to put node.left node.left node.left so we are going to call the same function all over again with the left subtree and we are going to call it with the right subtree so let's visualize this so let me build the tree over here okay so initially the node is pointing to one right and what we are going to do over here we are going to build our output string as well along with the tree visualization so that we see what is going to happen so what we are basically doing we are first putting the node.val and then first putting the node.val and then first putting the node.val and then calling the serialization so what we are putting over here is a 1 followed by a comma and then we are going to the next level of the recursion so we are going to the left so if you see our algorithm we have the left realization first followed by the right serialization right so as i hope you can see here okay so when i call the left one what happens is we are calling with two so the function will get called here so it will be the node value is 2 now so when we get a 2 what we do it is first we check it is it null it is not null so we are going to append the value to the string and put a comma so we are going to put a two over here and then put a comma right then again from that function what we are going to do is we are going to call the same function again with the two's uh left child right and that is a null and what happens when we put a null back so basically when we put a null back we put a n right so uh one small mistake over here it should be n comma because we need the delimiter here as well so what happens over here we put a n and we put a comma right so the string becomes like this but if it is null we are returning we are no more going into recursion so what happens is we come back to the node 2 again so the recursion ends over here for this subtree and we return back from this position right and now we consider the right subtree of 2 which is again another so we get a null over here and as we have seen that when we get a null what we do is we put a n comma going by this statement in yellow over here so we are also returning from this subtree so now uh both left and right of 2 is done and we go back to the node 1 wherein we have processed only the left subtree now it's the time we should process the right subtree so we call the right so now this method is getting called for the node one right okay so what happens is we call it with the value three so as soon as we get a value of three what do we print the three and we go into the left recursion right so we are going to spawn a tree from this position and we are going to call the node with the value four so as soon as we get a value for we print the value so we put a 4 over here and we call the left subtree once again from 4 so we call the node with null so when i get a null what i do i print a n over here and there is no uh further possible ways from null so we come back and we call the right subtree from four which is also a null and we print n immediately and we return back so let me make some space over here okay so we are done with 4 so the next is 3 is right which is a 5 so the node will be called with 5 and as soon as i get a 5 what i do is first i print the value of the note that is 5 and i go to the left recursion so in the left recursion again i get a node which is null so we return back and we print the value n over here and then we go to the right subtree over here which is also a null so we return back from this as well and we put back a null over here again so you can see here that these this and this is now completely identical and we have come up with the serialized form of this tree but we have to take this string and we have to d serialize and construct it tree back from this right so let's see how we can deserialize this and come up with the solution let's put down our algorithm over here this d series uh gets a string s right unlike the serialization which received the node the dc realization will receive a string s and we are going to use the string as to come up with the free node and we are going to reconstruct this entire tree that we have seen over here node so first what we are going to do to split s by our delimiter right so what will happen in this case we'll be splitting by the character comma over here right so what will give me is a bunch of tokens over here so let's call it as t so what are those tokens are nothing but each element without the comma so we are splitting by the comma so we will get all these tokens okay so our t is nothing but array containing this tokens now what we are going to do is we are going to construct the queue and we are going to put everything that we got inside the cube we all know the queue is a data structure wherein the first element to get inside is the first element to come out so it's a basically a fifo data structure right and it's q so what happens in action is from one and we queue things and from the other end what we do is we dequeue things so if you see what we did is basically we added add all the tokens links to a queue so we have added all the tokens and since we have all these tokens so you can see that the head is at the beginning right at the beginning of the queue so what we are going to do now is we are going to call a different function uh which will be a recursive function and which will help us to build this uh entire tree from this queue so let's say the name of the function is bill trick and we are going to pass the queue that we have to this function so now let's see how this function will look like so let's say this is my military function and which is going to take this q that we have right so now what we are going to uh do in this function is we are going to do a q dot poll and we will get an element once we do a q dot poll will give me a value which is an integer so what i am going to do is i am going to create a node i am going to create a new node using this value e right now the thing is that we have a node 1 but we have not said it's left or right it's left and right is now dangling so we there is just a node sitting over here which is one which doesn't have a left and the right so our node is now ready but the only problem with this node is we don't have the left and right side to the node we still don't know what we are going to have put in the left and the right if we just call the dc the battery function again over here with the queue that i have and let's suppose that this returns back a node right so what will happen in this case is if i do something like this for the left sub tree get the value 2 so it's going to pull again and get a value 2 right and it will further go ahead and try to build its left subtree so it is going to call the same function again with the null and it will try to build its left subtree right so here it is essential for us that's why i left a space that was and in that case what should we do we should return a null now just see we are returning from the statement right so what will happen is we are not trying to set the left and right for the null right so what is going to happen in this case is we are going to return a null to it so how this null will be treated in this function so 2 is going to set its left as a null right that's what the statement say over here we are assigning node dot left for the two right and it is it sent me back a null right so this part is done now the second part is that we can do the similar thing over here as well then we can just call the bilitry function with the nodes remaining so just to visualize over here 2 is done and this knowledge popped out three element has been popped out so far right and this is the link that has been established so this is all present on the call stack right so the same thing will happen as well for this guy so what will happen is it will call the function with the queue and what it will get is a null and we are assigning this null to the right subtree of two that's what has happened so this two function has been completed for two so what will happen is now two's left and right is done now two will now one this element one has invoked the call on its left software right so what will happen is it is going to return this node at the end right so at the end what we should be doing is we'll be returning this node that we have created one for normal case for null cases we have already handled it over here for the other cases we are returning the node so for one what will happen is it will return the node to right and which it will assign to its left right so you can see that our tree is slowly getting constructed so null has been this null has also been popped out right so for the so two is done so flow for one left is done now it will go for the right one so it will call the same function again and this time it will pop out a three right so we'll get a 3 over here and 3 will try to set its left child again so it will call the same function so 3 is popped out so it will be called with a 4 over here right because the next element that is on the queue is a four okay so four will try to set its left child what it will get is a null it will set an r then four will try so four is done this null is done so again four will try to set its right child so it will call again and it will set a null it will pop out a null so 4 is also done so now 3 will try to create its right side and it will pass the queue so what it will pop out is a 5 so the 5 will come over here and then 5 will try to set its left child it will pop out the next element and set it there that's null then five will try to set out its right child it will also get a null and it will pop it out so now what will happen is now five will return uh so three strike will get a five as a note to its right so the entire tree will look like this and if we remove the null from this tree what will happen is the tree will look something like this which is nothing but the actual tree that we have received as a input one two three four and five so this is how the entire algorithm works and this is how we are going to serialize and deserialize the tree and we are going to see in the code how the solution looks so we'll head over to lead code and we'll quickly look at the code so initially what we have is a serialized method and the serialized method is very simple we talked about if our root is going to be null in that case what we are going to do is we are going to return our n followed by a comma right and if so this is this part of the algorithm that we are talking about so if it is now we are going to return otherwise we are going to take the value and go and do the recursion so we are going to return the value name was root dot val plus we are going to append a comma and we are going to call the serialize function again and we are going to call first with the left and then with the right so this is what the entire serialization looks like and we are going to do the serialization part also very quickly so this is just a simple three lines of code nothing else and these three lines of code will produce this string that you see over here right so now we are going to look at the deserialization part as well so what we are going to do basically is first we are going to so we have passed with the data and we need to split this data based on the delimiter that we have used so it has to be the same delimiter that we have used over here right so what this delimiter is going to do is it's going to give me a bunch of two pins so let's call it token so we have a list of um array of tokens over here and the next thing that we are going to do is we are going to build a queue which will contain string and let's call this queue only and it will be a link list implementation this queue is i'm going to add all the elements into this all the elements that we have got as a token into this so what we need is a list over here so as list i'll do and pass on the tokens so what will happen after this statement is our queue will be populated like this somewhat like this so we'll have all the elements in the queue you added so the next thing that we are going to do is we are going to return the build ring function from here and this military is going to take our cue and it's going to return me a tree node right because we are returning a tree now let's say we have a private method which returns me the free node and the name is beltry and which is going to take a queue of and let's call it q so what we are going to do is like we are going to get the element out of the queue so we are going to do a q dot poll so once we do a q dot poll the first thing that we should check is because we know that it's going to be capital l in all the time and if it is so we are going to return a null from here because if not then what we are going to do is we are going to construct a tree node lets call it node and um lets see they have a constructor with the value so lets leverage that so we are going to pass element but uh to remember element is a string and we need to pass it as a integer so we are going to do our integer dot parsing and we are going to take this element so our node is ready and we need to set the left of this node before we return this node back so we are going to call directory again with the same cube and we are going to call the right subtree as well with so we are going to pass both this and once we are done we are going to pass this node back right so this will uh return the entire tree and this will return back the tree to the calling function so let's run this code and see i'm sure that i have made some here and there okay it will be element not e so let's run it again well you can see that it has been accepted okay so our solution has been accepted and this is the whole algorithm that i wanted to pass on that how a simple approach that can help us build this solution so do let me know what you think about this video if you think this video was helpful do give it a like and do share as well and if you haven't subscribed please feel free to subscribe to the channel and help the channel as well so one more thing that i wanted to mention over here is like if you want me to solve any particular problem then do or drop a comment with the lead code or any platform or any particular problem that you have in mind which does not belong to any platform either and i can definitely try to solve it and create a detailed video on the same like the one that you are seeing now so i hope this video was helpful do let me know in the comments do give it a like if you think this solution what solution was worth giving a like and yeah that's all from this video and thank you once again have a great day
|
Serialize and Deserialize Binary Tree
|
serialize-and-deserialize-binary-tree
|
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
**Clarification:** The input/output format is the same as [how LeetCode serializes a binary tree](https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-). You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
**Example 1:**
**Input:** root = \[1,2,3,null,null,4,5\]
**Output:** \[1,2,3,null,null,4,5\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `-1000 <= Node.val <= 1000`
| null |
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
|
Hard
|
271,449,652,765
|
65
|
okay so lead code practice time so in this video there are two goals the first one is to see how to solve this problem and the second one is to see how to solve this problem properly in the interview so okay and interview so remember the first thing in the interview is to always try to understand the problem if there is anything unclear please bring the questions to the interviewer to ask the interior to clarify and also at the same time think about some match cases and let's read this problem so valid number can be split into these components in other a decimal number or an integer so optional and e or e followed by integer so decimal number can be split into these components a sign character one of the following formats at least one digit followed by a dot uh at least one digit followed by a dots followed by at least one digit a dot followed by at least one digit okay an integer can be split up into these components a sign character at least one digit uh okay so a while number can be either a decimal number or an integer and the definition uh of this small integer are listed as something like this okay so some examples let's see those are all wide numbers those are not valid numbers because this contains like some invalid characters for numbers this one doesn't have the number itself actually this one okay so e should be followed by integer all right so on and so forth um so i think we are pretty much understand we i pretty much get the question what the question is so if so given string return true if s is a valid number okay something like this all right so let's read the constraints so for sure that the string is not going to be empty between 1 to 20 and consists only english letters both uppercase and lowercase digits and the plus or minus all right so yeah i think i pretty much understand what the problem is so i think there are a lot of ash cases at this moment to think about um yeah because there are a lot of conditions to constraints to define what the number what the wallet number is but i would say if this question is asked um it's pretty much just testing your coding ability instead of because there are not much room to find the solution like finding the algorithm like that but briefly i would say um it seems like there are several different things so first one is a dot and the second one is the e and also if e exists uh we should make sure that after e there is an integer there all right so and we need to make sure that if dot exists it should come before e and uh um and yeah it should come before e um okay except that i think we should be good so like i said um i would like to define different things so for let's see the number so let's say if i have 1.22 and then the e if i have 1.22 and then the e if i have 1.22 and then the e let's say this is plus e minus three so something like this i would decompose the number into several different parts so the dot the e and the number that comes before e and the number that comes after e so that's the four parts we need to think about so i'll say let's say first we define the dots um if we have income we have a dot within the number and the other one i would define the e if we have e in this number and the and these and then we would i would define the first part of the number which is the 1 sorry plus 1.22 1 sorry plus 1.22 1 sorry plus 1.22 so this one i would say is the first part and the next one i would define the second part so the characters so the character won't contain uh space okay that's good um all right so if would say if um i stole car i'll first define the idx is equal to zero starting from it if s dot car at zero is equal to a plus or i stop r at zero is equal to a one sorry i is equal to a minus what i was thinking so i would adjust a plus idx and then uh well um idx is smaller than sls uh first i would get a car c is equal to style car at uh idx all right so what if so if c is equal to a plus or c is equal to a uh minus then i would expect that it comes after ae at this moment so i would say if um s dot car at uh idx minus 1 is not equal to e uh it is not let's say it's not equal to e so let's say s car is not equal to and s dot car at uh idx minus 1 is not equal to the character e so if those are not this is not e the previous character is not even we just need to return fast here okay else if it is a dot if c is a dot then if we have already have dot or we have already have e then we need to return boss otherwise i think we should be good and then we have we need to make sure that he has a dot has true and then else if c is equal to e or c is equal to capital e then if he already exists then we need to return a false for it uh if he already exists or if we don't have the first part of the character sorry the first part of the number like we don't have this something like this part with before the e then we need to return false otherwise we have the e as true okay uh yeah so that's uh that's pretty much it and else if um else if it's uh it's a digit so if character dot is digit c if it's a digit then i would just say um if e then we have second part as true otherwise we have the first part as true okay and else if it's something other than those character set for sure it's going to be a uh email thing you're going to return fast here and up and we need to plus index here and the authors outside of this while loop what we do is we can we need to just return um so first of all we need to make sure that the first part exists so it should be like the first part exist and either second part so either if it is not e and not uh second part that's perfectify or if it is e and it is a second part then that's the thing then that's iso okay yeah so i think that's pretty much it uh let's randomly pick up some number two to check so okay so after the coding it's time for you to do some testing so i think in if this one is asked you will need to go through a couple different test cases manually to explain how this piece is going to work and what it is going to return so for example um if it is let's take the example minus 0.1 let's take the example minus 0.1 let's take the example minus 0.1 so first of all it is minus v plus idx and the x is equal to one now and the next character is zero so it falls into this branch it's not e so it says second part as true and then we encounter the dots we see that dot haven't been set then we are going to set down as true now you can count another digits then um not too much to be done um we just then set first part that's true as well and finally first part is true and e and second part no set so this one is you're going to return true let's see abc for sure it's going to fall this part so it's going to return false for sure let's see for one e so first of all it is a one first the second we said the first part that's true and then the next character it is e he said true s e yes true and you see that first part is true but it's like e exists but the second part doesn't exist uh so if e x the second part doesn't exist then this part is going to be uh this part is going to be false so yeah so over i think it's good um let's give it a shot all right so it's accepted so that's it for this uh coding question um yeah i think not too much to think about solution but mostly about coding and just ash case checkings um so a lot of ash kids to think about yeah so that's it for this coding question if you have any questions about this puzzle or about the solution please leave some comments if you feel this video helpful please help subscribe to this channel and i'll see you next time thanks for watching
|
Valid Number
|
valid-number
|
A **valid number** can be split up into these components (in order):
1. A **decimal number** or an **integer**.
2. (Optional) An `'e'` or `'E'`, followed by an **integer**.
A **decimal number** can be split up into these components (in order):
1. (Optional) A sign character (either `'+'` or `'-'`).
2. One of the following formats:
1. One or more digits, followed by a dot `'.'`.
2. One or more digits, followed by a dot `'.'`, followed by one or more digits.
3. A dot `'.'`, followed by one or more digits.
An **integer** can be split up into these components (in order):
1. (Optional) A sign character (either `'+'` or `'-'`).
2. One or more digits.
For example, all the following are valid numbers: `[ "2 ", "0089 ", "-0.1 ", "+3.14 ", "4. ", "-.9 ", "2e10 ", "-90E3 ", "3e+7 ", "+6e-1 ", "53.5e93 ", "-123.456e789 "]`, while the following are not valid numbers: `[ "abc ", "1a ", "1e ", "e3 ", "99e2.5 ", "--6 ", "-+3 ", "95a54e53 "]`.
Given a string `s`, return `true` _if_ `s` _is a **valid number**_.
**Example 1:**
**Input:** s = "0 "
**Output:** true
**Example 2:**
**Input:** s = "e "
**Output:** false
**Example 3:**
**Input:** s = ". "
**Output:** false
**Constraints:**
* `1 <= s.length <= 20`
* `s` consists of only English letters (both uppercase and lowercase), digits (`0-9`), plus `'+'`, minus `'-'`, or dot `'.'`.
| null |
String
|
Hard
|
8
|
502
|
hello everyone let's solve problem 502 that is IPO suppose lead code will start its IPO soon in order to sell a good price of its shares to venture capital it could would like to work on some projects to increase its capital before the IPO since it has limited resources it can only finish at most care distinct projects before the IPO help lead code design the best way to maximize its total Capital after finishing at most K projects okay you are given an given n projects where ith projects has a pure profit of profits of I that means we are given a profits array okay and a minimum capital of I is needed to start it what does that mean we'll see initially you have W Capital when you finish the project you will obtain its pure profit and the profit will be added to your Capital pick a list of at most gay distinct projects from given projects to maximize your final capital and return the final maximize capital okay so this is what we have been given now what does it say Pro ith project has a pure profit of profits of I so for a project say 0 the profit is one or one it's two for two it's three okay and a minimum capital of I is needed to start it so in order to do this project you need to have this amount of capital at least now what do we have in our Capital we have initially zero so with this Capital we will be able to start this project but not this project because for this project to start we need at least one Capital similarly for this we need at least one capital okay now what we have been said is that when we complete a project okay let's say we complete this project okay the profit of that project will be added to our capital if we complete this project this profit will be added to our capital so this is what it is happening all right that means if we do a project and its capital is added to our uh and the profit is added to our Capital increases and more number of projects become available to us right now our task is to maximize this Capital by doing the projects now how is this going to be how are we going to maximize it we are going to maximize it by adding the profits right profits to it and how can we maximize it the only way we can maximize It Is by doing as many projects as possible Right but here is the thing we can do at least at most two projects okay we can do only two projects at most two projects okay so for that what can we do say if we are supposed to do only one project let's say and we are we have these profits one two and three which project are we going to choose let's say we don't have any constraint we are going to choose this project right because this has the maximum profit isn't it so what do we understand from that we need the projects which have the maximum profit at first we need them first okay then serially we will take up the maximum okay say we have two projects if we do these two we have a profit of what three if we do these two projects we have a profit of five let's just say okay so the thing is we need the projects with the maximum profit okay but we have this constraint as well right in order to do a project we need at least that amount of capital fine so the thing is now if say our capital is initially say X what project will we be able to do only those projects whose what whose capital is less than or equal to X right let's say our profit uh sorry Capital initially is uh say 4 okay and the capital uh of say four projects is let's say 0 1 2 and 3 okay and their profits let's say are three two four one now among these and let's say we can choose only two projects which projects are we going to choose we are going to choose this project and this project because they yield the maximum profit isn't it so from this we get the idea that if this is our Capital Which is less than our initial capital we would need the projects which have more profit first that is we need them in a sorted fashion that is decreasing order it would be two then it would be zero it would be one and it would be 3 because we can choose all of them because they are less than equals to X right so because they are yielding the maximum profit we will choose these two so since we are going to need the projects with more profits at first right for that we will we are going to use a maxi fine what will the maxim do it will provide us the access to the maximum profits at first okay but before that these projects would be available to us if their capital is less than our Capital less than or equal to right so for that what we are going to do say we have these three capitals okay and initially our capital is say one now in order to have a capital lower than our current capital our Capital we are going to call these capitals one by one in which way that hey whoever is the minimum come to me at first so what is the minimum zero come to me at first okay I will do some work on you okay he is done then which is the next minimum it is 1. that is less than equals to 1 isn't it we will I will do some work on you and eventually some profit would be added to this one right so it will increase and more profits would be available to ourselves as we move on okay so in this case our task is to get the minimum capitals to us at first okay for that we are going to use a mini heap so let's summarize for the capitals we are going to use a mini heap now this mean he will bring us the least capitals to us at first that's our capital is w and say we have three capitals available to us which is less than W now these three capitals would have some profit Associated to them right for the project let's say one four three and one okay now because these three capitals are less than W our Capital then only we will be able to work on these profits then only we'll be able to get these profits right and which one would we choose we will choose the maximum so for that we will put these profits into our Max Heap fine now when our uh Capital would increase we will go to the next projects if we can do more projects okay now that you have the idea let's try to code it we are going to have a Min Heap for what initially the capital right let's call it mean c in capital new priority Cube what are we doing in this say these are the profits available to us and these are the capital okay now they are in pairs right they are related to each other we can't just uh we can't just use the priority queue to sort them and leave them as it is right they will be shuffled isn't it so we will sort them together by keeping them together okay now let's create our maxi let's call it Max Speed Max profit right ldq okay now in the mean heap of our capitals let's put the data uh profits dot length I plus Min Capital dot offer new and what capitals of I and profits of I we are sorting it based on the capitals that is a of 0 minus B of 0 okay now while K minus is greater than 0 we'll do K we will work on K projects okay while our main capital is not empty minimum capital is not empty and Min capital the peak element of mean Capital it contains the capital of ith project and capital of profit of ith project if that capital is less than or equals to our initial Capital while it is less okay we will add those profits Associated to our Max profit Maxi okay Min Capital dot all one index one right profit says in index one is index one okay what did we do we did so this was our say this is our mean Heap okay initially our capital is 0 what are the capital that are less than or equals to our current capital it's this one only so we will add this profit to our Max Heap now this is our maxi okay what we will do one by one we will add this maximum profits to our current capital okay now we did only one project now let's move on our Capital now increased from W 0 to 1 isn't it so these two are available to us now and we are yet to do one more project okay so what we'll do while Min capital is not empty and Min capital of peak of zero is less than equals to this one this and these are less than or equals to 1 right so we will add these two profits to our mean Max profit that is 3 and 2. and which one will we choose we will choose the maximum amount of them that is three that is what our Max shape is for okay W plus equals to maxib dot Pole now there is one more condition if our Max profit Heap is empty we will break out why let's say at some point we have the capital of say three and the next projects that are available to us has the starting Capital value greater than 3 let's say the next project that we have the capital four five so there is no way we can start these projects right so in that case we are done we will simply break out okay and whatever profit that we have collected whatever the capital that we have maximized we will return it so this is our code okay let's try to run it accept it now what is the time complexity is first we are iterating over the profits and we are adding data into our mean Heap right that will be login okay then we are doing operation K times that is O of K what we are doing we are adding as well as polling or popping from our mean Heap right that is another log of n so this is our time complexity and our space complexity is we go of n right so this is the solution I try to make it clear I hope it's clear for everybody and in case you still have a doubt you can ask in the comment section I'll try to reply to them all right so yeah if you like this video hit the like button share this video And subscribe to my channel if you haven't and I will see you in the next video bye
|
IPO
|
ipo
|
Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only finish at most `k` distinct projects before the **IPO**. Help LeetCode design the best way to maximize its total capital after finishing at most `k` distinct projects.
You are given `n` projects where the `ith` project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it.
Initially, you have `w` capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.
Pick a list of **at most** `k` distinct projects from given projects to **maximize your final capital**, and return _the final maximized capital_.
The answer is guaranteed to fit in a 32-bit signed integer.
**Example 1:**
**Input:** k = 2, w = 0, profits = \[1,2,3\], capital = \[0,1,1\]
**Output:** 4
**Explanation:** Since your initial capital is 0, you can only start the project indexed 0.
After finishing it you will obtain profit 1 and your capital becomes 1.
With capital 1, you can either start the project indexed 1 or the project indexed 2.
Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.
Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
**Example 2:**
**Input:** k = 3, w = 0, profits = \[1,2,3\], capital = \[0,1,2\]
**Output:** 6
**Constraints:**
* `1 <= k <= 105`
* `0 <= w <= 109`
* `n == profits.length`
* `n == capital.length`
* `1 <= n <= 105`
* `0 <= profits[i] <= 104`
* `0 <= capital[i] <= 109`
| null |
Array,Greedy,Sorting,Heap (Priority Queue)
|
Hard
| null |
389
|
hello everyone this is our first video on this channel and today we'll be solving an easy lit code question that is find a difference the number is 389 so question says that you are given two strings s and t string s is generated by randomly shuffling string s and then add one more letter at any random position so we need to return that one letter which was added to the string t let's look at the example now string s is a b c d and d is a b c d e so e was included in the string t from s so we simply return e in example 2 string s is empty and string t is y so y was added to string t so we simply return y now there are basically four approaches to this question first is have hash map we will be using an unordered or simply map hash map to include all the letters of string s that is we include all the letters from s and after that we traverse through t and include all the letters in our map after that we simply loop on our hash map and wherever the frequency is 2 is greater than 1 greater than 2 we will simply return the index or the letter from that from the map and we get the solution if we don't get any solution which would not be the case then it will return minus or simply any letter we can write any character over here so based on the time complexity of this approach will be open because we are looping through our hash map and the space complexity will be open as well because we are using hashmap for storing our all the letters second approach is uh shorting elements so we simply sort our all elements we simply sort string s and string t after sorting it would seem something like abcd and abcde as the string was already sorted in our first test case the sorting would not be a barrier over here after that we traverse through the string s and wherever the index of s and t doesn't match we simply return the index of t because it the extra letter was added into t so we simply return t and if it is if it's not the case if condition doesn't work then we simply increment our i and at last we return the size of our t so this was the second approach the time complecity would be of n log n for shorting the both the strings and n for uh traversing through the string and space complexity would be off and after that approach 3 is some difference so basically we take this differ some sum of both the strings and after that we take the difference of the string so the e was extra and so it would be output of our equation so basically what we do is take a for loop and we simply add on uh the elements into our sum one and uh add on elements of t n to some two and we they simply take the difference b absolute value of difference between sum2 minus someone that is sum of l all elements of string t minus sum of all elements of string one so we get our output by uh sum difference and the last approach would be uh difference so our x application so what source uh so applies is that if zeros uh a and b are zero then answer would be zero uh if a and b are 1 then also answer would be 1 and if either of the 2 is 1 then the answer would be 1 so what we do here is we take 0 of all the elements and the odd one out that is the odd one which we which does not have any pair from snt would simply be uh one at last and we get the our output so the time complexity of this approach so our approach would be often because we have to look through our whole area i mean whole string and the time space would be off would be constant so yeah this was the four approaches of this question some define the difference and i hope you understood the approach and see you in the next preview thank you
|
Find the Difference
|
find-the-difference
|
You are given two strings `s` and `t`.
String `t` is generated by random shuffling string `s` and then add one more letter at a random position.
Return the letter that was added to `t`.
**Example 1:**
**Input:** s = "abcd ", t = "abcde "
**Output:** "e "
**Explanation:** 'e' is the letter that was added.
**Example 2:**
**Input:** s = " ", t = "y "
**Output:** "y "
**Constraints:**
* `0 <= s.length <= 1000`
* `t.length == s.length + 1`
* `s` and `t` consist of lowercase English letters.
| null |
Hash Table,String,Bit Manipulation,Sorting
|
Easy
|
136
|
885
|
This problem is the third problem of the spy real matrix with l code number 885. Now, it is a medium difficulty problem. Now, what about a two-dimensional array? what about a two-dimensional array? what about a two-dimensional array? Gauss is given there again, and Laos is given the opportunity to write the number of columns. And we don't know where to start with 3. The word given is zero and in reality there is n't much where to start. They say they are looking at yeast. Now, yeast suddenly appeared. This is a bit confusing. I thought I would have done more if I said it was good, but I don't want to put a virgin on it. What is the standard for this now? I thought I was going to pray. Let's look at the map of Korea like this. So, where is it? It's here. Where is the West Sea? I understand. I have someone else's education. Where is the footgam? Let's open it. Let's see it like this. So East Donut is the comment, and where is the reservation? South Korea has to do um and there is no North Korean date. If you look at it like this, it doesn't seem like we will be there. Let's find out what happens? We're walking. Where is the snail? Ugh, you can go into the Spiral 3. The Spiral Chevy is talking about the snail. And in which direction, clockwise. He will be allowed to return. I searched for PG terror, but they say he is visiting from Grid Grade's mod for intellectual property. Uh, and what we are all saying is nc, this is now uh, when the union-run flower shop, Thames, comes out, they say they love all the items. uh, when the union-run flower shop, Thames, comes out, they say they love all the items. uh, when the union-run flower shop, Thames, comes out, they say they love all the items. That's the situation. It tells us to return from ah, what is the list, the cut-in's coordination side, what is the list, the cut-in's coordination side, There are 2 3 4 Gap, how many columns, 6 stations, 1 2 Ssam 4 5. Where is the starting point? Yang Nao is the work. The column should be bought. The area marked with that work should be attached. The base said something, and it was str. And this. It will progress in a way that goes out more and more. So is it the first time? 1 Yes, it is cloudy so I did ej. What happens next? I have to change it at night, so I changed it after that. Huracan The sun sets, Kaora, and Then I changed the direction again. This time, should I do 1st item? I'm going to North Korea. Now I changed the direction again. This is to wipe one space. 2 The curry is like that. It's full. Tooka. From now on, let's go to the town wall. 2 Selfie Aura. Every second stem increases by 1. Let's do the law that goes from and we will be like this. Then I will be able to know how to turn it like this in about 5l ratio. Let's look at it in a general way because it is 2-dimensional, so let's break it down with a loop. general way because it is 2-dimensional, so let's break it down with a loop. general way because it is 2-dimensional, so let's break it down with a loop. I think I can make it n square, but I think I can figure out SK Oral-B. In this case, the app is used by skiers. Let's find out how to figure out SK Oral-B. In this case, the app is used by skiers. Let's find out how to figure out SK Oral-B. In this case, the app is used by skiers. Let's find out how to turn it on. It's also very difficult. So, when you run the loop iteration once, it will visit. It's quite possible if we clean up the argument value so that the value comes out. Let's give you a brainstorm on how to do it. What was there in the first watch? At first, it doesn't really feel right, and then every two more. The next university is number 2. Oh, 1, it can be bigger every time. Now, and o2 bunt, what else is different? That, and Plain Tony, what can you say? 100 Should I tell you to smile? The end is 5, please. 2 It will be genuine. Now, let's give it a try. Let's implement it with this. I'll look at you first, starting with the number of pieces needed. I can't tell you what you need per day. Well, it's in that shape. Wow, I have a special way to say the color. It's quite an initial value, and the sound response is r0. I'll prepare it. Well, let's see. I know it all, and what else do I need? I'm weak in meat. I didn't even wear clothes called Route, but now he has a role to play here, so there's a lot of abandonment. Let's see who does this. Let's take a few attacks like this and go to North Korea. So, let's leave the Reims HPL for this and the current Corent D is 0 . It goes like this. . It goes like this. . It goes like this. When you reach this point, you can change the direction. Let's try it that way. So the font is 1 to 0, and it comes out. Um, let's start quite differently. What is the king? Ah, it would be nice to have a bare face. Um, 5. How long will it last? Yes, until he takes the blame, the story is ah yes. When you look at Langs, ah, it's a real fight. It can go as far as riding Kano. Let's end it at this time. Let's end it. Let's stick with it until we inform Lotte stimulus. When it is in the position, wow, when the column is in the position, its function can be processed only when there is cancer. I understand the car. I need to use it in modern times, so where is the blau in all the bottles? That's not going to work. Otherwise, there's no big deal. If you have to corrode and destroy it, you can make a column with me. That's right, it's like a mailbox. Now, it's like this. I'll ask you carefully. Next, I'll take the request. 5 I'm the only one who thinks about this every time the direction changes from before. This is because if you lose than the route bar, if you fall down, you have to go in that direction. It will be a scary 1-dong indicating the direction we are sticking in. And this value is the same from 0 to the top. will be a scary 1-dong indicating the direction we are sticking in. And this value is the same from 0 to the top. will be a scary 1-dong indicating the direction we are sticking in. And this value is the same from 0 to the top. Hero Flight is smaller than 1. If it is the world speed, it is high school as expected. I guess if it is 0, should I increase the score? Now, I have to increase the mon in the column, right. I have to give it a split rainbow. What on earth are you talking about ? 9 down. Who is it? If it's down, the aura direction, Yinging, is like this. It's going to be split. If not, it's the last one. Here, I raise the need for a leader analogy a little less. Please take a look at Miya. Bye, yes, that will work. I do n't know if it's like this, but I'll do it. The root and race font has now gone to the end. What should happen after going all the way to Elos? After hitting the water that came back at the end, I'll do it. Lapin, and there's another thing that needs to be done. The direction is left and you receive it. If that happens, let's see where it actually changes. When I do the y truck, does it change? M When I changed it became the same thing. That's right. What happens when you download it from Bright? Atta Umi, it's done until the end. It's the same, but one is included. So when it changes, you can download it. And Raftral and Baekdam have changed. Let's see. Uh, does the pattern change then? Oh, ah, only for the next task, we can raise the lengths one by one. We will do that. Then, what is Tao? Sunday and Uh, why, when the number is 3, I 'll give you the cork method. If that's the 'll give you the cork method. If that's the 'll give you the cork method. If that's the case, it'll work. Ing didin night life, more everyday life. Even if you express it like this, there's no problem with saying, "It's okay to be honest." express it like this, there's no problem with saying, "It's okay to be honest." express it like this, there's no problem with saying, "It's okay to be honest." But if you want to be more technical than this, what happens with 131? That's right, for 5% of the percentage, I understand that when I look at the state and the for 5% of the percentage, I understand that when I look at the state and the for 5% of the percentage, I understand that when I look at the state and the work or 30s, I now know the pool operation. How is it defined? At least for the presidential election mask, the end of this long sleeve should be 1, and that number is 300 because of this. If it's the same, it's one and if it's 3, there's one more thing here, so I'm using the same character like this, so I'm wondering if yes is one and what's going to happen. Now, I don't know in that case, I'll increase it and change the direction after it flows. What will happen to the direction? Oh what? He's sitting at home. How can he put his life into it and it will follow? Hey, let's do that and now and then and now the torrent is back and the vest and the invention were thrown away so 0 I don't think I was able to come up with the initial medicine um ah where 5 when it comes to math, if it goes like this then everything will go well. I think so, if everything turns around, it won't work out. Oh, I'll continue with the promise. It's going to be bad. o Ho ho, I did it right. It was the next time, and let's try it. ok, it came out well on the island. Now, Time Purple What will happen to the time couple I think I can say it's 5 won except after seeing it because it's absolutely necessary. Thank you for your hard work.
|
Spiral Matrix III
|
exam-room
|
You start at the cell `(rStart, cStart)` of an `rows x cols` grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.
You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid's boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all `rows * cols` spaces of the grid.
Return _an array of coordinates representing the positions of the grid in the order you visited them_.
**Example 1:**
**Input:** rows = 1, cols = 4, rStart = 0, cStart = 0
**Output:** \[\[0,0\],\[0,1\],\[0,2\],\[0,3\]\]
**Example 2:**
**Input:** rows = 5, cols = 6, rStart = 1, cStart = 4
**Output:** \[\[1,4\],\[1,5\],\[2,5\],\[2,4\],\[2,3\],\[1,3\],\[0,3\],\[0,4\],\[0,5\],\[3,5\],\[3,4\],\[3,3\],\[3,2\],\[2,2\],\[1,2\],\[0,2\],\[4,5\],\[4,4\],\[4,3\],\[4,2\],\[4,1\],\[3,1\],\[2,1\],\[1,1\],\[0,1\],\[4,0\],\[3,0\],\[2,0\],\[1,0\],\[0,0\]\]
**Constraints:**
* `1 <= rows, cols <= 100`
* `0 <= rStart < rows`
* `0 <= cStart < cols`
| null |
Design,Ordered Set
|
Medium
|
879
|
304
|
hi my name is and today i'm trying to solve this problem which is a zoom led code problem the question is ransom quality to the immutable the a matrix has been given to me and we'll have to handle the multiple query and the query is given as a formula top left corner top left uh coordinate and the bottom right corner coordinate so in between that so we'll have to find the sub matrices ransom so let's do that do i approach suppose i have an matrix of three by three so one two three 5 6 7 8 9 so if i have been contribute uh check that how much coordinate contributing of every element so i have been trying to do that through prediction concept so let's do that first of all prefix sum is one three and six then one plus four that is five and 5 plus 7 that is 12 so now that's one tricky thing here that is 3 plus 5 that is 8 minus 1 plus 5 that is 7 plus 5 that is equal to 12 now 6 plus 2 is 18 minus 3 that is 15 plus 6 21 now 12 plus 12 24 minus 5 that is 19 plus 8 that is 27 plus 21 that is 48 minus 12 there is 36 plus 6 plus 9 that is equal to 45 right 6 9 7 8 is 45 just keep considering that now i am founding the whole prediction so now i have been coming to this question which is asked suppose if the top left corner value top left coordinate has been given that one and the bottom right that one so how do they from there my logic is that first could have to take in whole uh prefix sum uh value then i have been deducting that sub matrices for sum and that sub matrix system so after that will be the remaining apart and that value will be the answer so how do i do that let's find it last one the other one three six 155 12 21 5 12 21 and the last one is the 12 27 43 12 27 45 so now the prefix will present so i have been doing that value has to be deducted and after that sub matrix the sum will be the answer so i'll do that so fast that was given and now i have been trying that protein 0 1 0 2 1 0 1 2 0 2 1 2 so i have been that is there and that is that one has been given and two has been given so fast we have been taking that to two that is the whole sub matrices now i've been deducting that value so prefix sum that is 0 of 2 that minus 1 is that 2 of 1 that is 2 of 1 but there isn't that coordinate and that somebody said that something but this the portion that we have been repeating so we'll have to deduct in there so if i have been deducting that with the plot as a positive over because we fix sum to 2 that is the whole if i've been taking the minus common then prefix sum of zero up to plus prefix sum of two of one and now i've been deducting the prefix sum of zero and zero so what i am right now finding that basically the generalized formula what is the analysis formula basically that is the top left value now that one is that prefix sum of zero that is one so that is top left row minus 1 and 2 is basically the bottom right column right now that one there is prefix sum of two of one that one so that is 2 is basically the bottom right row and top left column -1 column -1 column -1 and that one is basically minus prefix sum of top left row minus 1 and top left column minus 1 so that is the whole general formula of to find the given sub matrices so i am right now implementing that let's do that first we'll have to making the prediction so matrix it says so for so fast we'll have to realize that initialize that we could sum the release cells of n plus one all are initialized to g two right now so now i've been trying to implementing their prediction so what is that so and one more thing i am right now i want to share that logic so to overcome the integer overflow so if that is therefore energy has been coming 2 so i have been taking that for n plus one that is zero so zero that one so that is basically zero that is i minus one that one and that minus one has to be done so that basically so what is that so that is zero 1 that is 1 0 and that is 1 but here basically if i've been taking that from i have been taking the 1 4 or taking this loop from the 1 that means that from row is 1 and the column is 1 that means that if i have been taking this for i minus 1 j plus i j minus 1 plus matrix of i minus 1 j minus 1 so what is that is 1 0 that is 1 so that's to uh to overcome the integer robot basis problem so if i've been taking both set extra zero part minus 1 there is a column value left side and the upper value of the top column and now i have been deducting the three sum of time minus one and the z minus one and now i have been adding that matrix value so we have been calling the p sum of matrix that's passing it and now we'll have to call that down so so what i'll do that so if i have been saved that previous one concept basically what is it yeah here i have been taking one extra row and extra column so in that case all number so that will be the added by plus one because that's the zero row and the zero column has been present there right now so now implemented so return these sum of row 2 and the call 2 and minus epic sum of taking sum of torque left row that means low minus row one so in that case when i mean approaching there so that one the minus one but here i've been adding the plus one so what it understood yeah bottom right column so that is called two minus p sum of bottom right row that is row 2 so that was present there only row 2 so i have been adding plus 1 there and also column 2. at and top left minus 1 that is left column there is only call 1 and now that we'll have to add that the diagonal value so p sum off that is the row one minus one done so i've been adding plus one as well as call one minus one and plus one i think that will be the answer let's check that okay is some okay i've been here there's some net is somewhat so function in the matrix is being same so that's what maybe okay so there is an error problem matrixes and for the one plus one i minus j one and now that there is a depiction i have been implementing there so now i have been trying to do that submit first we'll have to check there yeah that is the answer has been given is submit yeah that's been submitted and accepted also and here i have been taking order of n cross m matrices so that's why the space complexity is order of n cross m and the fast will try their the prefix sum so that is
|
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
|
6
|
in this video we'll go over leak code question number six zigzag conversion given a string and a certain number of rows we have to perform a zigzag conversion and return the result so what exactly is this zigzag conversion well let's say the string is hello world and the number of rows is three we can arrange the letters in a certain zigzag pattern so the first letter H would go into the first row the second letter would go into the second row and so on then once we've hit the bottom we'd go back up so the next letter goes in the second row then the first row and we'd continue doing this until all the letters are used up so you can see that this is the zigzag pattern then we'd have to return the string that would be formed if we read it row by row so first we'd read the first row which is Hol then the second row which is elwrd then the last row Lo So reading in that order the string that we would have to return is h-o-l-e-l-w-r-d-l-o here's another example with four rows so this time we'd assign the letters down to the fourth row then go back up and continue the same zigzag pattern this time reading the string row by row gives us h o e w r LOL LD now to solve this let's look at the connection between the zigzag pattern and the original string if we Traverse the string one character at a time and see which row it's in we can see that H belongs to Row 1 E belongs to Row 2 L is in Row 3 and the second L is in row four O then goes back up to row three W is in row two and O is in row one then we go back down again to rows two three and finally four so what you can see is that the order in which we assign the rows to characters is one two three four three two one two three four in other words we are oscillating or going back and forth between the top and bottom rows this also works for the case with three rows the order of the row numbers is one two three two one two three 2 1 2 we see the same oscillating pattern so here's how we'll solve this we'll Traverse the string and keep track of which row each character is in then we'll concatenate all the characters in Row 1 concatenate that with all the characters in Row 2 and finally concatenate that with all the characters in Row 3 and return the result now let's look at the code and see how we can do this in Python let's say the string s is hello world and numerals equals three first we can check for some base conditions if there's only one row then the string stays the same so we can just return s and if the number of rows is greater than or equal to the number of characters then the string would just become one vertical line and when you read it row by row it would still be the same string so we can also just return s now the first thing we'll do is initialize a 2d array called rows and we'll initialize an empty list for each row if you're not familiar with this notation this is called list comprehension in Python and what it's basically saying is four row in range num rows so range 3 create an empty list and we'll Nest all of that inside of an outer list I've also indicated the index of each inner list here notice that here the first row starts at index 0 not 1. then we'll create a variable called index which will indicate which row we're currently on and we'll initialize that to zero since we know that the first character will always be assigned to the first row we then create another variable called step and this variable is going to tell us whether we need to go up a row or down a row as we're assigning characters to rows for now we'll make it 1 which means that we'll start by moving down a row you'll see what I mean in a second then we'll enter a loop and use a variable called Char which will take on the value of each character in the string so it starts off as the character H then we'll start assigning each character to a row index equals zero so this line will append the character H to the first row then we need to add the step variable to the index variable in order to update the index but first let's check for two things if the index is zero then that means we're at the top row so we need to increment the index so we'll make the step size 1. if the index is at numerals minus 1 or in this case 2 then that means we've reached the bottom row so now we need to decrement the index so step will be negative one so right now the index is zero so we'll make the step equal to one and add it to the index so now index equals one and points to the second row then we'll move on to the next character let's append e to the second row and check for both conditions index is neither zero nor two so we can safely just add step to index and now the index is 2. next up is L and we'll append that to the last row now index does equal 2 so we have to reverse the direction and make the step equal to negative one now when we add step to index becomes one and moves up a row next is L again and we'll append that to the second row neither condition is true so let's move the index back up to the first row then we'll append o and since we've reached the top row let's change step back to one and move down a row and we basically just keep repeating this pattern we append the character move to the next row and if we see that we've hit either the top or bottom row then we switch directions and keep on going so I'm just going to speed up the rest since it's the same thing but you can see that the index variable oscillates between the top and bottom rows and appends each character to the appropriate list okay now that we're done with a loop the last thing to do is join the characters together into one string we can use the built-in join method that converts an built-in join method that converts an built-in join method that converts an array into a string but we'll have to do this in two steps so first we'll convert each inner list into a string by joining all of its elements on the empty string so in other words we're just smooshing it all together into one string so the first list which contains h o and L gets converted into the string Hol then we'll do that to the second list then the third list now that we finally have a single list that contains the strings from each row all that's left to do is to call the join method again this time on the outer list which is the rows variable so by joining all three strings together we finally get our final result which is h-o-l-e-l-w-r-d-l-o now you may be wondering why did we have to use a 2d array for the rows couldn't we have just initialized each row to the empty string and use the string concatenation to append each character well the problem with that is that since strings are immutable each string concatenation would run an O of n time that is you can't just append a character at the end of a string concatenation actually allocates new memory and copies over each character to create an entirely new string so that means that this line would end up running in O of end time and since the loop is also of n the algorithm would end up running in O of n Square time but if you use lists instead since lists are mutable we can just append each character in constant time or more precisely speaking the amortized complexity of appending to a list is constant so that means that everything inside the loop runs in constant time so the algorithm now runs in O of end time
|
Zigzag Conversion
|
zigzag-conversion
|
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: `"PAHNAPLSIIGYIR "`
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
**Example 1:**
**Input:** s = "PAYPALISHIRING ", numRows = 3
**Output:** "PAHNAPLSIIGYIR "
**Example 2:**
**Input:** s = "PAYPALISHIRING ", numRows = 4
**Output:** "PINALSIGYAHRPI "
**Explanation:**
P I N
A L S I G
Y A H R
P I
**Example 3:**
**Input:** s = "A ", numRows = 1
**Output:** "A "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of English letters (lower-case and upper-case), `','` and `'.'`.
* `1 <= numRows <= 1000`
| null |
String
|
Medium
| null |
1,710
|
Scientist Hello How are you I am positive in good swords question is maximum unique and attract and devotion is so let's reader question you are assigned to put some amount of boxes on 21 pun Aryan today are ok sombir and number of units is ok and here Fine return on maximum total number of units that can be spotted on the truck ok subah adventure tours and abstract size only so that shubh but show what is box type boxer vijay are in which they have been in the number of small initiative which subscribe to that If from time special unit which can be put in response to this that other have to drops and jobs have to unit this mystery box and hidden former and unit switch off the in that in which of the best one can put one unit how to Use of the sea boxes in this 873 death means that Bigg Boss is closed that N A and S A Unification Sports 30 2012 Misbehave to drops two and comments subscribe that Arvind is box decide Chhotu soil from here how much water and how much total number of lord You can see a number of BJP candidate from this industry in this manner in this is the soon box ki encroachment 1-pure honey antagonist three ki encroachment 1-pure honey antagonist three ki encroachment 1-pure honey antagonist three c adventure game one wait you can see the one ko pure number of this Is the unit per box sun means how much you need you can get how much water number fluid which can perform other breasts government because by vikas because i have three love you have three box and in the same manner 84 phone number of box i 210 Bittu Boss Dish Drops A Special Teaching Box SMS On Which Slots Which Skin Box And Third Box 220 Is Only And Each Of Them Have One Unit Of Lord Surya Total Number Of Baroda Number Plot By Selling Form 2013 That And Advanced 141 For Means The Missiles Defense In this is the one drops this is the to the self to solve verses ka news bihar tak size truck size isko subah hai one drops for boys in this 3 and how much lower birth in the water till nine feminine few days day will go a guy will see she is absolutely low two drops but e have total per excise meaning of but if they know how much you must size thin but being to do subscribe 4 hai to seven dandruff bandh dream defect vighnchi box button take And Only One Drops OK Subha Will Only One Lots And Lots Of Wave Units Subscribe Solve Vighn-Vighn Units Urs Problem Will Vighn-Vighn Units Urs Problem Will Vighn-Vighn Units Urs Problem Will First The Number Of Units Which Can Be Seen That Will Go For Smaller Will Not Again Play List Of The Day In 500 Index It Will See Morning That Train Tracks Size Pure Maximum Units Which I Can Get Depend Dishes Page And Get Strength And Have Attend Till Size Are Only Two Drops A 100 - 52 Only Two Drops A 100 - 52 Only Two Drops A 100 - 52 That Is Painful And Home Assam Back Water Till Now Its Faith In 210 Spa That Not Be Left With Only Five Tracks Is No Way Have Only Fetishes 15 Days Will See What Is The Meaning Of But Can Get 2009 This Is The In Unit Tomorrow Morning To End Sizes 3 And The Number Box Ironing OK Suresh Kaushal Vikas Vihar And five truck size and behave with clothes they can put this box in the 500 15 - 30 remaining box in the 500 15 - 30 remaining box in the 500 15 - 30 remaining bittu which alarm assembly of water no is part plus noida 307 56001 water nor will again cod not be left with only to 279 will seervi chicken's Others contain time hot and planets 700 but they have only but were left with only two trucks sexual too so will feel choked time boxes for the boxes 16 to - 2012 Assam including 40 Baghwa Toli to 16 to - 2012 Assam including 40 Baghwa Toli to 16 to - 2012 Assam including 40 Baghwa Toli to services three member team 16 total number of rather Hai but is this 19th that Shaadi Se Chalaoge Nau Let's Implemented on in the clear will shot in on the civil services student on the will singh on the basis of this follow okay so infection is also that soft function Bigg Boss W 's seeds turtle 's seeds turtle 's seeds turtle am that surgical strike Lambda 21000 Discover This Dam India Hindu Saint Only Anindya Morning-Evening Teams Special Only Anindya Morning-Evening Teams Special Only Anindya Morning-Evening Teams Special 5490 Candidates Should Aware And In This Manner On's Sweater They Will Arrange Man A New City Power Rangers Is And Descending Order 09305 Middling Some Shabbir Withdraw From Back Side is a reward which has arranged in descending order on that know what will do you can simply rana loot lo hai very tight I think they should have to right now box type of that and work with will say is our that access oil live But you can say number and unit do who is inferior number phone number boxes greater than only power truck size aaj tak size is greater than the number foxes so they can put on possibility say turtle honor plus phone number *unit a who phone number *unit a who phone number *unit a who is what do You do it means sleep size nadu 41 wale number five morning can get the number subscribe in this manner hear here vyaghro but they can take only two boxes and two subscribe them respected subscribe plus i class is combined size * unit and share will combined size * unit and share will combined size * unit and share will decrease one room Size - 11 no. Mixture of it a that member of 19th I hope in the Quiet India Movement and let's Meerut's facility also submitted come this I have total time manage space quality is the space quantity is soaked of in the time to cities end of birth starting and resources required And when time to time and space for this city is I hope home ministry of very shot BP shot services and loop specific day Tuesday re subscribe thanks for watching this Channel subscribe comment And subscribe The Amazing you do
|
Maximum Units on a Truck
|
find-servers-that-handled-most-number-of-requests
|
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`:
* `numberOfBoxesi` is the number of boxes of type `i`.
* `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`.
You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`.
Return _the **maximum** total number of **units** that can be put on the truck._
**Example 1:**
**Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4
**Output:** 8
**Explanation:** There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8.
**Example 2:**
**Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10
**Output:** 91
**Constraints:**
* `1 <= boxTypes.length <= 1000`
* `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000`
* `1 <= truckSize <= 106`
|
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
|
Array,Greedy,Heap (Priority Queue),Ordered Set
|
Hard
| null |
1,929
|
welcome to my youtube channel so today we will try to do lead code 1929 problem where we'll try to solve how to concatenate errors so this one is accepted by 91 percent let's see okay so basically we have to do concatenation of arrays so if you have an input one two one what we want is we want to get one two one to one so basically concatenate it and just print the same error twice and how would you do it so we'll try to solve it in javascript so this one's pretty easy solution right so what we want is so we have a input so what i always try to do is just write it here in comments like just make a comment and you know so we know what we are trying to achieve so we got input we output so i decided so what do i want so i want input i literally want input and then i want input again right both in array so let's say i want what do i so input plus input so i just want to know how i want to know how can i add to errors right so what like what would i do i would just try to do like nums plus nums and just return it but that's not gonna work directly like this so obviously maybe we have a method in javascript so in javascript what can i do is so i can store this i can like i can create a variable first array and sorry i can create a variable called first array and we can store the value nums in it and then we can this is just for the simplicity we have a better solution than this but you know for you guys to understand so we'll create a variable called second array and we'll again store nums in it's okay so now what i want to do is i just want to add it but if we directly try to add it like first error plus second array obviously we're gonna get error so what do we can concat so there is a method in javascript like array dot concat so you can connect first to second so what we'll do return first array dot co c first edit dot concat secondary so we're continuing first array into secondary which basically means literally adding the secondary after the first array so if we do this um for the simplicity we can do this variable result equals to you can do this and just return the result right return result and if we try to run the code so see we got a good runtime 97 ms and we got the correct input so you even if you try to submit the solution so it will test all the use cases see you just go atms like faster than 92 percent so easy solution it's nothing it's just a method in javascript called concat you can use it and literally do this and you know there's another solution as well if you want to do this so you can comment this code easy solution one line solution so one line solution would be using the three this thing so you can copy nums and you can use the littles and again copy numbers and then if you type so what it does is it creates a copy of the num array so this nums is array and we write it separated by a comma and then you again do the same thing like dot this dot creates a copy and then you write the array so it's again gonna put this error and then add this error after this so if you run the code it should work as well see 86 ms and if we can submit this it's gonna work see we got a little bit slower solution but yeah it worked so that's it if you want more solutions like this come to my channel
|
Concatenation of Array
|
maximum-value-at-a-given-index-in-a-bounded-array
|
Given an integer array `nums` of length `n`, you want to create an array `ans` of length `2n` where `ans[i] == nums[i]` and `ans[i + n] == nums[i]` for `0 <= i < n` (**0-indexed**).
Specifically, `ans` is the **concatenation** of two `nums` arrays.
Return _the array_ `ans`.
**Example 1:**
**Input:** nums = \[1,2,1\]
**Output:** \[1,2,1,1,2,1\]
**Explanation:** The array ans is formed as follows:
- ans = \[nums\[0\],nums\[1\],nums\[2\],nums\[0\],nums\[1\],nums\[2\]\]
- ans = \[1,2,1,1,2,1\]
**Example 2:**
**Input:** nums = \[1,3,2,1\]
**Output:** \[1,3,2,1,1,3,2,1\]
**Explanation:** The array ans is formed as follows:
- ans = \[nums\[0\],nums\[1\],nums\[2\],nums\[3\],nums\[0\],nums\[1\],nums\[2\],nums\[3\]\]
- ans = \[1,3,2,1,1,3,2,1\]
**Constraints:**
* `n == nums.length`
* `1 <= n <= 1000`
* `1 <= nums[i] <= 1000`
|
What if the problem was instead determining if you could generate a valid array with nums[index] == target? To generate the array, set nums[index] to target, nums[index-i] to target-i, and nums[index+i] to target-i. Then, this will give the minimum possible sum, so check if the sum is less than or equal to maxSum. n is too large to actually generate the array, so you can use the formula 1 + 2 + ... + n = n * (n+1) / 2 to quickly find the sum of nums[0...index] and nums[index...n-1]. Binary search for the target. If it is possible, then move the lower bound up. Otherwise, move the upper bound down.
|
Binary Search,Greedy
|
Medium
| null |
394
|
well you had it all figured out didn't you were told oh the number one fantasy for all those babes i see at the beach is a guy in his underwear at four in the morning illuminated by a 15-inch monitor doing c illuminated by a 15-inch monitor doing c illuminated by a 15-inch monitor doing c plus right that's exactly what they dream of so if that's what you believe you better get through decode string which says given an encoded string return its decoded string the coding rule is k encoded string where the encoded string inside the square brackets is being repeated exactly k times notice that k is guaranteed to be a positive integer well that's good you may assume that the input string is always valid no extra white spaces square brackets are well formed etc furthermore you may assume that the original data does not contain any digits and that digits are only for those repeat numbers k for example there won't be input like three a or two four okay so what does this mean so if we have three times a you repeat the a three times and then if you have two bc you repeat bc and bc again so twice now you have three times but within this three something you repeat c twice so we should get c six times so it's a and then two c's so a2cs and a2cs which in canada stands for the air canada center or uh some bogus place where the leafs are always losing okay so this problem is actually a recursion problem we could do it with a stack but i find it more succinct and easier to do it or to think about it as recursion now it is hard to think about this and i admit i didn't immediately find the answer myself so this is a model i took off the discussion pages and in fact i think this is the approved solution the thing is there's a lot of things to think about now in an interview setting you won't necessarily be able to decipher this the first time you see it but if you study this you'll realize well you know it's not that hard as long as i think about a couple of concepts for example what are we really looking at as we iterate through the string we're looking at what happens if we have a number what happens if we have an opening bracket what happens if we have a letter and what happens if we have a closing bracket those are four cases so let's see how we could go about that we're going to need a helper function um and as such all we need to do is return helper and uh we're throwing it s and we're throwing at zero as our position so let's design the helper function which will return as you could tell a string because if we're returning helper it means that helper itself will return a string so some sort of alarm ringing in the background or some sort of fire truck um we're taking ed a string s and uh we're taking ed the position over here which we'll take as constant over here and um well actually no the reason why maybe we should declare int position equals zero over here and pass along position since it might be easier as we're going to be modifying position and we can't necessarily pass it as a constant then to uh to deal with it this way okay now that we got this let's see how we go about this well we're gonna have to create some sort of word and which starts off as nothing that's the point of this whole thing we're creating a word and within the word there's going to be some repetitions and those repetitions are going to be a function of the number that we see here which we're calling number so let's iterate so for while we already created our um we already created our position over here we know that position has to get to uh has to iterate up until s size so it has to be smaller and we increment position okay so far so good um let's see now so remember a 4k says if it's a number if it's an open bracket if it's a letter or if it's a closing bracket pretty clear so let's start if s position so our string at position equals and here's our opening bracket then um how do we play this then we're going to have a string and we'll call it my string equals helper um helper s and then we're going to increment position over here okay so what does this mean it means that before passing pos over here we're going to increment it so in fact we could have written it like this i think this is clear i happen to like these a little bit better once we do that once we have the word that we need we know that we're going to have to repeat it for the number of numbers and you'll see that we know that once we reach this we would have gotten the number first so in fact this will never be the first thing that we hit in the string uh we'll always get a number first so we're going to tackle that at about two seconds so four into i equals zero i smaller than num i plus and what do we do with that well word plus equal um my string that's it so that's it's my string that's being repeated x number of times or rather what is it num number of times um and then once we're done that we set num equals zero again okay now we have another situation elsif s posts um what did we say so we had an open bracket and now we want a closing bracket if it's a closing bracket we could just return the word that's it that's all we need to do um let's see now so this could either be kind of an inner type of call to helper at which case it would be coming back here and we'd be that we'd be coming up with what is it the number of um the number of repetitions so this is always some sort of inner type of recursion whenever you might encounter that else if s pose what do we say equals um what is it equals okay so actually we have a little function here is digit um s pose so if this is true then num equals num times 10. s position minus the character 0. okay this is kind of a standard conversion to a digit now we could have used let's see now uh a toy i believe a toy would have given that or is a toy the contrary i don't even remember now else now if we actually encounter a character then we could just do word plus equal s pose and at the end of all this why is this for loop okay here at the end of all this all we want to do is return the word so does this work and it's taking an inordinate amount of time when it does that i just select everything i hit refresh so leak code always or very often has these kind of strange moments let's run the code over here um it gave aaa over here could this be vis-a-vis my not incrementing over here so that was good okay so word equals my string num equals zero so okay this seems okay if s digit s pose num uh equals num times 10 plus okay um oh okay here we go okay we have a winner and the reason it was doing that is we have to modify the position yeah it can't be passed by value over here and if you look at it you might see why in fact i might need to see cy too okay this leads me to think i need to study this a little bit more thanks a lot everyone and so should you if you don't immediately see this but i think we have the bare bones systems let's study each of the cases what happens when you hit a bracket what happens when you hit the closing bracket what happens when it's is digit s position okay now another way of writing this is uh else if um else if s pose bigger or equal to um zero and s pose smaller equal to nine so that makes it a digit over here and let's see what happens so same thing if you don't remember the is digit you could always use this thing over here thanks a lot everyone have a good day
|
Decode String
|
decode-string
|
Given an encoded string, return its decoded string.
The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets is being repeated exactly `k` times. Note that `k` is guaranteed to be a positive integer.
You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, `k`. For example, there will not be input like `3a` or `2[4]`.
The test cases are generated so that the length of the output will never exceed `105`.
**Example 1:**
**Input:** s = "3\[a\]2\[bc\] "
**Output:** "aaabcbc "
**Example 2:**
**Input:** s = "3\[a2\[c\]\] "
**Output:** "accaccacc "
**Example 3:**
**Input:** s = "2\[abc\]3\[cd\]ef "
**Output:** "abcabccdcdcdef "
**Constraints:**
* `1 <= s.length <= 30`
* `s` consists of lowercase English letters, digits, and square brackets `'[]'`.
* `s` is guaranteed to be **a valid** input.
* All the integers in `s` are in the range `[1, 300]`.
| null |
String,Stack,Recursion
|
Medium
|
471,726,1076
|
1,647
|
hello everyone welcome to coding decoded my name is sanchez i am working as technical architect sd4 at adobe and here i present day 28th of june lead code challenge the problem that we have in today's minimum deletions to make character frequency unique it's a medium level question on lead code and i also feel the same without further ado let's quickly try and understand the question here we are given a string and it is said to be a good string if there are no two different characters in s that have the same frequency what do we need to identify the minimum number of characters that you need to delete to make the string good in nature for example here uh the input string that is given to us is double a b the frequency of a is two the frequency of b is one since both the frequencies are different that means they are unique and no deletion is needed it's already a good string let's proceed ahead next we have three a's three b's and two c's therefore there's a conflict between the frequency of a and b we have to make some deletions in order to make them unique in nature and what those deletions could be either you can delete both the b's one ways to delete both the b's up and the other way is to delete one b and one c so at minimum at least two deletions are needed without further ado let's quickly walk through the presentation section where i'll be talking about the algorithm to go about it so let's get started let me just start the slide slideshow and take a pen lead code 1647 minimum deletions to make characters frequency unique it's a medium level question on lead code and in case if you have any doubt understanding this question or if you want to ask anything from me in general please feel free to drop a message on the telegram group or the discord server of coding decoded both the links are stated below it can be with respect to anything referrals placements job opportunities and i'll be more than happy to assist all of you there now let's get back to the example here we have three a's three b's and two c's so we'll be divising the algorithm while iterating over this test case and the first the foremost thing that you should be doing is to create the frequency map this is what i have exactly done here so we have two c's three a's and three b's now what i'm gonna do i'm gonna create a set that will store all the unique frequencies that exist in my input string so let's get started and what i'll be doing i'll be iterating over this frequency array so the first element that i will witness would be a and the value that i have happens to be 3 i check whether 3 frequency exists in my set or not it doesn't exist in my set as a result of it's a happy case i'll be adding 3 to my set and let's proceed ahead that means this is safe to be added as part of our unique frequencies the next element that i have happens to be b and at b the frequency is 3 i again check whether 3 exist in my unique frequency set or not it does exist that means it's a conflicting case and whenever you see a conflicting case that means all these three b's can't be considered as part of your unique frequency set you have to make some reduction so let's create the deletion count variable so it will store the number of deletions to be done in our final output string and the initial it is initialized to zero since deletions are to be done what do we simply delete one b character from our input string so one b is gone it could be any of the three b's anyone out of the three b's so since we are deleting one b character so let's update the deletion count to one and the frequency of b gets updated to 2 and again we are going to check whether 2 exists as part of our set or not 2 doesn't exist that means it's a happy case so we go ahead and add 2 to our set now our set has two free kind of types of frequencies three and two let's proceed ahead the next frequency that we have in our frequency map is two so let's check whether two is part of our unique frequency set or not to already is part of our unique entries unique frequency set therefore we have to make some deletion and we will be reducing the frequency of c and we will be deleting one c out of our input string the updated frequency gets set to one and again we will check whether one is part of our unique frequency set or not it is not part of the unique frequency set therefore it can be easily inserted into it the total deletions that we did turns out to be b and c and the count gets updated to 2 that gives us the desired result that simply means that we have to delete one character of type b another character of type c in order to make this input string have unique frequencies overall let's take one more example so that you guys get a good hold of the concept so we have the input string as c e a b a c b so the first and the foremost thing that i have done is to create the frequency map and let's create the set as per the previous example the first element that we see happens to be a and a has a frequency 3 does 3 exists in my set it doesn't exist so we are it's a happy case we go ahead and add 3 to it let's proceed ahead the next element that we have is b so b has a frequency two it's two part of my unique frequency set it is not part of my initial frequency if we go ahead and add two to it let's proceed ahead next we see is c has a frequency too two is already present as part of my unique frequency set therefore we have to make some deletion so we will be deleting one c character so once the character is gone the frequency gets updated to one we check whether one is part of this unique frequency set it is not part so therefore we are going to add 1 to it so far so good let's proceed ahead the next frequency that is left is of e and e has a value 1 we check whether one is part of our unique frequency set it is part of our unique frequency set therefore we have to make some deletion as a result of which e character gets deleted is to be deleted and the frequency gets updated to zero since it has been updated to zero that means we have completely lost the identity of v it doesn't make sense to add it into our set in total how many relations did we do we did two deletions and the final said that we have had three to one as a unique frequency values now in order to complete it up let's quickly walk through the coding section and i'll exactly follow the same steps as i've just talked here i've created a deletion variable that will actually store my result moving ahead i've created the frequency map and i've also created a set that will store all the unique frequencies i iterate over my frequency map and check whether the value is greater than 0 till the time it's greater than 0 and my frequency map contains the count value if it does contain the count value that means we have to do some deletion and we have to correspondingly reduce the frequency count this is what i have done here till the time this loop continues the deletion variable gets incremented and count variable gets decremented once i'm out of this while loop i simply add unique frequencies as count to unique frequency set once i'm done with this for loop i simply return the deletion variable so let's try this up accepted 50 faster which is pretty good i am also connected to vpn that may be the reason for the latency and with this we have successfully completed day 28th of june lead code challenge and guys please don't forget to check out coding decoded sd revision sheet if you have an important interview planned very soon and you don't need to know how to revise in the most crucial concepts that are asked in interviews for example dynamic programming graph trace binary search back tracking bit manipulation monotonic stacks lighting window matrices sets then this playlist is for you what do you need to check out uh these google sheets and here you will find uh that the problems are listed in increasing order of difficulty starting from easy medium and hard and uh i have provided video solutions for each one of them and the interesting part is a template that you will find in some of the playlist for example monotonic stack tries backtracking so the first one that you will see is the uh template which is highlighted over here and once you will go through this video you will see that in the rest of the question the same template gets applied so do give this these sheets a shot and i promise after you will go through them these concepts will be on your tips the hard work is all yours i can only be the catalyst and i wish you all the very best in this journey of yours 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 all the links are stated below so do check them out
|
Minimum Deletions to Make Character Frequencies Unique
|
can-convert-string-in-k-moves
|
A string `s` is called **good** if there are no two different characters in `s` that have the same **frequency**.
Given a string `s`, return _the **minimum** number of characters you need to delete to make_ `s` _**good**._
The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string `"aab "`, the **frequency** of `'a'` is `2`, while the **frequency** of `'b'` is `1`.
**Example 1:**
**Input:** s = "aab "
**Output:** 0
**Explanation:** `s` is already good.
**Example 2:**
**Input:** s = "aaabbbcc "
**Output:** 2
**Explanation:** You can delete two 'b's resulting in the good string "aaabcc ".
Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc ".
**Example 3:**
**Input:** s = "ceabaacb "
**Output:** 2
**Explanation:** You can delete both 'c's resulting in the good string "eabaab ".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
**Constraints:**
* `1 <= s.length <= 105`
* `s` contains only lowercase English letters.
|
Observe that shifting a letter x times has the same effect of shifting the letter x + 26 times. You need to check whether k is large enough to cover all shifts with the same remainder after modulo 26.
|
Hash Table,String
|
Medium
| null |
880
|
hi guys welcome to algorithms made easy today we will be solving the question decoded string at index so let's go through the question first an encoded string s is given to find and write a decoded string to the tape the encoded string is read one character at a time and the following steps are taken if the character read is a letter then that letter is written on to the tape if the character read is a digit say d the entire current tape is repeatedly written d minus 1 more times in total so now for some encoded string s and an index k find and return the k letter one index that is the index starting from one in the decoded string so if we see the example lead to code three k equal to ten we get o at tenth index because the string becomes two times lead is repeated and then code with code this string is repeated thrice let's look at the example in detail the first digit that we encounter is at five so all the letters till four will be repeated twice then we get a digit at index 10 so everything before that we have that is lead code is repeated 3 times and if we see the length can be found out by this 4 multiplied by 2 plus 4 again and which is multiplied whole by 3 which gives us the length is 36 and this is indeed our string now do we actually need to store the string because k can range from 1 to 10 raise to 9 and the string can go up to 2 raised to 36 characters which will be a huge space and so we would not want to do that so how would we do it without using any space let's see so we will start working backwards reducing our string and k as we move ahead firstly we start with three here this is the tenth character and the character present at this position is three this means that the string was repeated three times and thus we can get a smaller string by just dividing it by its length by three and taking only that much part so now the reduced string would become lead code with this if we see e goes out of bounds so we would also need to reduce k so k would now become k mod the length of this new string which is 15 mod 12 and which gives us 3 this becomes our reduced problem so we need to find this e with this we move at 9th character which is e now this 9 and this 3 are not equal so this is not the character that we were finding so we'll move one step backwards and with that we will reduce the length of the string also which will eliminate our e now the character is d and n is eight and we need third character so we move ahead and reduce the length we keep doing so again here we got 2 and our k is still smaller so we would again break down this string and the string would become lead the reduced k would remain the same as it is less than four again when we will reach the third letter the string that would be left with us is l e and k is three which matches the index that we wanted and so what we do is we return e this way we'll not need to store the string but we can just work with the indices and the input that is given to us now that we know what we need to do let's write some code for this approach okay take a variable long size and initialize it to 0 and end n which is equal to string dot length after this we will find the size so for each character in s we check if it is a digit or not if it is a digit we will do size equal to size multiplied by the digit otherwise we do size plus so this will give us the size so now we will start from backwards and write a for loop so now we'll be working on the character at this particular index let's take it handy now if k becomes equal to 0 or k is equal to size and this character is a letter we simply return this character return the character what if it's not the end case so if character is a digit we need to divide the length or size so size equals to size divided by the digit else size minus that is we are just decreasing the size so one more condition is that k becomes k mod size at every step and at the end return null just to be sure that the program runs and just mark this okay let's submit this code and there it got submitted the time complexity for this algorithm is off and the space complexity is of fun thanks for watching the video see you in the next one
|
Decoded String at Index
|
rectangle-area-ii
|
You are given an encoded string `s`. To decode the string to a tape, the encoded string is read one character at a time and the following steps are taken:
* If the character read is a letter, that letter is written onto the tape.
* If the character read is a digit `d`, the entire current tape is repeatedly written `d - 1` more times in total.
Given an integer `k`, return _the_ `kth` _letter (**1-indexed)** in the decoded string_.
**Example 1:**
**Input:** s = "leet2code3 ", k = 10
**Output:** "o "
**Explanation:** The decoded string is "leetleetcodeleetleetcodeleetleetcode ".
The 10th letter in the string is "o ".
**Example 2:**
**Input:** s = "ha22 ", k = 5
**Output:** "h "
**Explanation:** The decoded string is "hahahaha ".
The 5th letter is "h ".
**Example 3:**
**Input:** s = "a2345678999999999999999 ", k = 1
**Output:** "a "
**Explanation:** The decoded string is "a " repeated 8301530446056247680 times.
The 1st letter is "a ".
**Constraints:**
* `2 <= s.length <= 100`
* `s` consists of lowercase English letters and digits `2` through `9`.
* `s` starts with a letter.
* `1 <= k <= 109`
* It is guaranteed that `k` is less than or equal to the length of the decoded string.
* The decoded string is guaranteed to have less than `263` letters.
| null |
Array,Segment Tree,Line Sweep,Ordered Set
|
Hard
| null |
451
|
hi everyone welcome back to the channel and today we solve lead code daily challenge problem number 451 sort characters by frequency so it's a really easy problem to solve and we'll first check out the problem statement then we'll look into the approach which you're going to use and towards the end we'll see the code as well so starting with the problem statement it is given that given a string is sorted in decreasing order based on frequency of the characters the frequency of a character basically they have given the definition of frequency return the sorted string if there are multiple answer return any of them so basically what you'll have to do is you have to figure out the frequency of each of the character in the string and sort the whole string based on that okay uh and if uh two characters have same frequency it doesn't matter where you put that so yeah this is the whole uh problem statement so the approach which I'm going to use is very simple so what I'm going to do I'm going to use uh hashmap and sorting method to solve this problem so what we will do we will first count the or we'll first prepare the frequency uh dictionary for the string for example in this case we have tree right so what I did I uh took the characters as the key and I uh counted or I took the frequency of every character as a value of the dictionary okay so this will be the first step after that like as soon as you have this stationary with the frequency mapping uh you just have to basically sort the dictionary on the basis of the value of the dictionary or in this case we can say frequency of the characters and when you'll do that uh you'll get something like this for example e had to uh the frequency of e was two so it will be at the top then T1 R1 okay and this can be interchanged it uh doesn't matter okay this can be interchanged and at the end you'll just have to iterate this sorted uh mapping and we'll keep a variable we'll name it result it will be an empty string and just we'll just keep on uh adding or appending the characters uh multiplied with a frequency for example if you'll multiply e with two it will give you e right then T1 will give you T R1 will give you R so if you'll add everything up you will get e which was our uh expected result for the example so yeah these are the three simple steps which you'll be using let's check out the code for the same okay so in this code what we have done as explain in the explanation side uh we have an empty string uh and we have given the variable name result to that and we are calculating the frequency using the counter method okay so it will basically give you uh frequency corresponding to each of the characters in The String okay to sort the uh dictionary on the basis of the key we I have used uh the sorted method okay and what we are doing over here so the first parameter over here is the uh items so basically frequency do items it any dictionary items gives you key and value both okay and for the key what we are doing we are taking the values and uh that can that is determined here so uh items gives you key value pair right so the first index will always represents the value and we wanted it in the decreasing order so do that uh we have this parameter called reverse which uh accepts a Boolean value and uh I have given Pro for that okay after that uh I'll just simply iterate the sorted frequency uh it will be an array of tles okay SED frequency be an array of tles uh and the structure will be like this so to give you an idea it will be something like uh e comma 2 okay sorry um yeah e 2 then we'll have t comma 1 and so on so forth so what we are doing we are just simply iterating this sorted frequency and uh we are appending the result of multiplication of frequency and the character itself in the variable and at the end we are just simply returning the variable so let's check out the test cases as you can see the test cases got C let's submit for further evaluation now okay it is taking some time H so as you can see the solution got accepted and I don't know why uh didn't perform well this time but last time I submitted it was around 90% so yeah this submitted it was around 90% so yeah this submitted it was around 90% so yeah this was a solution guys thanks ATT time for watching out the video stay tuned for the uping ones don't forget to like the video and uh subscribe to the channel thank you than you
|
Sort Characters By Frequency
|
sort-characters-by-frequency
|
Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string.
Return _the sorted string_. If there are multiple answers, return _any of them_.
**Example 1:**
**Input:** s = "tree "
**Output:** "eert "
**Explanation:** 'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr " is also a valid answer.
**Example 2:**
**Input:** s = "cccaaa "
**Output:** "aaaccc "
**Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa " and "aaaccc " are valid answers.
Note that "cacaca " is incorrect, as the same characters must be together.
**Example 3:**
**Input:** s = "Aabb "
**Output:** "bbAa "
**Explanation:** "bbaA " is also a valid answer, but "Aabb " is incorrect.
Note that 'A' and 'a' are treated as two different characters.
**Constraints:**
* `1 <= s.length <= 5 * 105`
* `s` consists of uppercase and lowercase English letters and digits.
| null |
Hash Table,String,Sorting,Heap (Priority Queue),Bucket Sort,Counting
|
Medium
|
347,387,1741
|
1,913
|
Hello everyone welcome to my channel Codesari with Mike so today we are going to do video number 11 of the playlist of Lead Code Easy. Okay the lead code number is 1913 and it is a very simple question. The product difference between two pairs A & B & C & D is Defined as pairs A & B & C & D is Defined as pairs A & B & C & D is Defined as such, OK, the formula has been told that how do you find the product difference. For example, the product difference between 56 27 is 5 * 6 - 2 * 7 that is 16 given an integer is 5 * 6 - 2 * 7 that is 16 given an integer is 5 * 6 - 2 * 7 that is 16 given an integer if the numbers are given an integer then choose four. Distinct Inces W x Y Jd True That's the Product Difference Between Pairs Nums W Nums You have to pick two numbers, okay, let's assume you picked A and B, multiplied both of them and picked two more numbers C and D, multiplied the difference between them, then what is the maximum value that can come, that is what you have to find. Okay, so look, it's an obvious thing, like here, a is in b minus c, let's go with this value. Okay, now see, you want this to be the biggest, you want the maximum, what does the value maximum mean, the bigger it can be, the better. And since we are finding this difference, neither the smaller it is, the better it is nor the bigger it is, the better it will be for me, and the smaller it will be, the better it will be for me, because if you look at this, the less the text component, the better it will be for me. A bigger answer will come on my right and the bigger it is, the better it is. It's okay for me, so yes, how will it be bigger? Multiply the two biggest numbers. Which are the two biggest numbers? I am seeing Sen and Saks. So. Make it 7 * 6 minus this, I want it to be smaller, it is the So. Make it 7 * 6 minus this, I want it to be smaller, it is the So. Make it 7 * 6 minus this, I want it to be smaller, it is the smallest because this is a substack component, this is everything that is happening, so the smaller it is, the bigger the value will be for this overall, then how will we get the smallest one, these are the two smallest ones. Multiply the numbers, which are the two smallest numbers? One is visible as two and one is visible as four. So 2 * 4 is the smallest number we visible as four. So 2 * 4 is the smallest number we visible as four. So 2 * 4 is the smallest number we can get. I am okay then 42 - 8. How much will it can get. I am okay then 42 - 8. How much will it can get. I am okay then 42 - 8. How much will it become? 34 is our answer. Okay, so if you notice, the simplest approach coming to your mind is that you need two largest numbers and two smallest numbers. Right, just apply simple sorting and you will sort this thing. If you sort it then Look how it will look like A 2 4 5 67 5 6 7 So all you have to do is pick the last two numbers seven and six because these two will be the largest and second largest numbers this is the largest this is the second largest okay so those two You have to multiply it by minus the starting two elements of the beginning because this will be the smollet and this second smollet. You have to multiply both of them by 2 * 4. This is your answer. Okay, so 2 * 4. This is your answer. Okay, so 2 * 4. This is your answer. Okay, so sorting has become very easy, easily the last. Picked up two elements from the starting point. Okay, time completion will be a pity because you have not taken any space. Okay, and if you do n't want to do sorting, then no problem. You can put a for loop and find the largest and second largest. Find the smollett and second smollett number. Okay, let's see that also. What is there in approach two that I don't want to do sorting. If I want to do sorting without sorting, then there is no problem. Even by writing a simple for loop, we can find the largest and second largest. Okay, what was our input, 56274, right? 5 [ 56274, right? 5 [ 56274, right? 5 6274 Okay, so I'll take two variables, largest and what's the second variable, second largest, and I'll take two more variables, Smollett for Smollett, and what's this second smallest okay? Right now I don't know which is the largest and which cell, so here minus infinity is okay, either you can put int man, what will you put in smollet, infinity i.e. either you can put int max, it infinity i.e. either you can put int max, it infinity i.e. either you can put int max, it is okay, now one -Come one by one, is okay, now one -Come one by one, is okay, now one -Come one by one, five on every number, is it bigger than the largest? Yes, if it is bigger than the largest, then the value already in the largest will become the second largest. Okay, then whatever value was in the largest, it is assigned to the second largest. Did minus infinity and changed the largest to five. Okay, now Smollet dies. Is the five that is Smollet small? From this variable, yes because its value is infinity, then the value that will already be in Smollet will become the second Smollet. Okay and update Smollet. Will do that Smollet has just shown five, I am okay, now let's update it on six first, is it bigger than the largest? Yes, then the value already in the largest will become the second largest, that is, the second largest will become five. And the largest will be updated to six, okay now let's come to Smollet, this is smaller than six smollet, no, is this six smaller than the second smollet, yes, then the second smallest will be updated to six, okay now I have come to the next number, two, but what? Is it bigger than the largest No Is it bigger than the second largest No Okay so these two will not be updated Let's see in smollet Is it smaller than smollet Yes then the already value of smollet will become second smollet So here I made it five and now I got two, the smallest one, so I updated it. Okay, now let's come here, is it bigger than the largest? Yes, the value that was in the largest was given to the second largest and if the largest seven was found, then it was updated. Done Is it smaller than the smallest No Is it smaller than the second small No Does it come at four Is it bigger than the largest No Is it bigger than the second largest No Is it smaller than the small Is it not four Look is it smaller than the second small That's updated the second small, okay now see I got the largest and second largest, got the small and second small, so 7 * small and second small, so 7 * small and second small, so 7 * 6 - 2 * 4 is our answer and what will be its time 6 - 2 * 4 is our answer and what will be its time 6 - 2 * 4 is our answer and what will be its time complex t o of n because what we have Did we just iterate this array, let's complicate the space one more time and finish it, so let's quote it with both our approaches. The first approach is nothing, just simple, take out the data size of these 10 numbers and Let's sort the beginning of numbers and end of numbers. Okay, so we have sorted it in ascending order so that I can easily find out the largest and second largest. Okay, so which will be the largest? Numbers of n goes into numbers of n and this second. Largest done minus smallest which will be the numbers of zero in numbers offv this second largest second small okay so let's submit and see hopefully fully we should be able to pass the example test cases indeed yes we have passed the test cases now Let's come to our second approach. Okay, so what was there in the second approach? I had said that we will take four variables. Largest second, largest small, second small is to keep track. So, for int and num. These numbers will go through all the numbers one by one. First go to the largest. Let's track the largest and second largest, okay, so if my current number turns out to be bigger than the largest, then it is obvious that whatever is the second largest will become the largest and we will update the largest, okay and if it is not so, that is. If the current number is not greater than the largest then let us check whether it is greater than the second largest, otherwise the second largest will be equal to the maximum of the second largest common number. It is ok. Similarly, what will we do? We have tracked the largest number, similarly. Smollet and second smollet are ok, so here we will do Nam like this. If less than Smollet turns out to be ok, then the second Smollet will become Smollet and we will update Smollet to Nam, and if it is not so then Nam is Smollet. If it is not smaller than , is not so then Nam is Smollet. If it is not smaller than , is not so then Nam is Smollet. If it is not smaller than , then we will check that it is smaller than second smolt. No, second smolt is the minimum of second smolt, common. Okay, then in the last, do not do anything. As soon as the for loop ends, we just have to check this and find the product of both. Difference not sorry largest into second largest is ok Will try to help you out see you sing in the next video thank you
|
Maximum Product Difference Between Two Pairs
|
make-the-xor-of-all-segments-equal-to-zero
|
The **product difference** between two pairs `(a, b)` and `(c, d)` is defined as `(a * b) - (c * d)`.
* For example, the product difference between `(5, 6)` and `(2, 7)` is `(5 * 6) - (2 * 7) = 16`.
Given an integer array `nums`, choose four **distinct** indices `w`, `x`, `y`, and `z` such that the **product difference** between pairs `(nums[w], nums[x])` and `(nums[y], nums[z])` is **maximized**.
Return _the **maximum** such product difference_.
**Example 1:**
**Input:** nums = \[5,6,2,7,4\]
**Output:** 34
**Explanation:** We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 \* 7) - (2 \* 4) = 34.
**Example 2:**
**Input:** nums = \[4,2,5,9,7,4,8\]
**Output:** 64
**Explanation:** We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 \* 8) - (2 \* 4) = 64.
**Constraints:**
* `4 <= nums.length <= 104`
* `1 <= nums[i] <= 104`
|
Let's note that for the XOR of all segments with size K to be equal to zeros, nums[i] has to be equal to nums[i+k] Basically, we need to make the first K elements have XOR = 0 and then modify them.
|
Array,Dynamic Programming,Bit Manipulation
|
Hard
| null |
1,014
|
so smart it's like not really fair this is 1014 best sightseeing pair don't you dare okay let's go ahead and get right into it so you're giving an integer array values where values I represents the value of the ith sightseeing spot okay so you have all these spots in the array at a certain index like an index I you have the value of the spot at index I two sightseeing spots I and J have a distance J minus I between them okay so if you have this JF spot and then you have this eyed spot right so the spot the ith index and the spot of the Json decks you just subtract those from one another to determine the distance between them okay you do the score of a pair I less than J okay so that's interesting constraint of sightseeing spots is value I plus value J plus I minus J which kind of makes sense for sightseeings right like the value of I right that's the value of this sites you're seeing and this is the value of the other site you're seeing but the distance between them is going to contribute to the score of that site right those sites together those sites as a pair and you'll notice since I is less than J right as you increase the distance between them it's going to minimize your score so that's what you can notice from looking at this function right the farther apart these sites are from each other that would mean that J is larger than I and J continues to get larger than I and you're subtracting J from I so this becomes negative so the farther apart things are the lower your score is okay the sum of the value of the sightseeing spots minus the distance between them right so the value of each of the spots minus the distance that occurs between them and that distance is just based on the index of each of the elements right so you could just imagine that there's all these things in a row right and each of these things has a value and you try to pick a pair of them but the distance between them is going to minimize it's going to lower your score so you want to pick things what so you want to return the maximum score of a pair of sightseeing spots so you want to maximize the values that you get but also consider that you want to minimize the distance between them because the farther apart they are from each other the lower your value is right and the closer they are to each other the higher value is going to be okay so in this example right if we didn't consider distance right we would say well the best two values we can get would be zero and one two three four right for example but if you had uh eight one five two six if you didn't think about this idea of the distance between them you'd say well the best two I could get simply put is just eight and six and that's 14 but the best value is 11. why well you might get eight plus six if you choose both of these values but you need to consider the index of the element as well right so this is the values of I and this is I itself so this is I equals 0 1 2 3 4. right so if you were to choose eight plus six you would get eight plus six minus or plus zero minus four right because you have to take the ith element eight so you get the value of that is the zero element and zero one two three four and then you take the jth element and the value of the jth element is 6 and index four so if you just plug that directly into this formula you get eight plus six minus four which is eight plus two which is ten right so you'd get 10 if you chose this element in this element versus if you choose I equals 0 and J equals two right so I equals zero so you choose this value J equals two so you choose this value right so although they have lower values since they're closer to each other you spend less you lose less because they're closer to each other so you just subtract 2 from this and that's eight plus three which equals 11. so you notice how this works right so it's not necessarily the fact where just picking the two greatest values will give you the best score because you have to factor in this distance okay um in this example well you know it's kind of like a base case not saying that we're going to use recursion but you know you have one and two well the best two you can choose are just these two and with your constraints you know there's always at least two items okay so the N squared solution right the easiest solution which probably won't pass because this is five times ten to the four so if you had an N squared solution it would be 25 times 10 to the 8 which is 2.5 times 25 times 10 to the 8 which is 2.5 times 25 times 10 to the 8 which is 2.5 times 10 to the a so 2.5 times 10 to 10 times 10 to the a so 2.5 times 10 to 10 times 10 to the a so 2.5 times 10 to 9. far too slow right that's too slow it's not going to pass we're going to get a tlea issue so that's not going to work right because the N squared solution's simple right you just look at each pair of elements right and choose two elements you look at each element in its index you then you just plug it into this formula and you return the maximum so that's a very intuitive solution and if that's all you can get at least you have something so like I always argue what I always uh um suggest is in any interview context try to just State The Brute Force solution just State something just so you know there's in you have intuition you might not know specific tricks that you've learned from just doing hundreds of problems and studying data structures and algorithms but you know how to code right you know how to take a problem and approach it to find a solution even if you can't find an efficient one that's kind of a side note but just State The Brute Force solution right so there's an N squared Brute Force solution you literally just look at each item you can do a for Loop right you go through I and you go through J you go through each eye you go through each J calculate the formula return the maximum one but that's not going to meet the constraints of this problem right because uh there's far too many you know n is far too large n is the length of values okay so I guess the first observation you need right there's really two observations you need for this problem the first one you need is that for any J value right so for any J value I has to be less than J so we want to choose an eye that maximizes what maximizes this formula so we for any J so for any J what do we want to maximize something we want to maximize the values that come before J right we want to choose the maximum I such that it maximizes this formula which is um stated above heard something weird it was weird um values I'll do it a different color just because we like to get fancy around here you know I spend so much on this tablet I might as well uh use it okay so whatever I'll just do blue so I we want to do oh values of uh I just I swear we're gonna do values of I plus values of J plus I minus J right and there's only one such value that meets this condition right so we kind of want to keep track of what the maximum thing is before any value right so we want to keep track of when I'm looking at a certain element I have I want to keep track of what's the maximum thing that could provide the most for this element right usually if you were doing this problem without this constraint right let's do this problem where we're just trying to maximize values I in values J if that was the case right you were just trying to maximize value I and value J and you didn't consider the distance between them you would always just keep track of the maximum value right if we were doing this problem and let's just say that we remove this constraint let's just say for the sake of trying to build our intuition we remove this constraint here and we just consider the maximum of values I plus values J is there a way to efficiently do that well to do that what you would do is you'd say well I'll just keep track of the maximum ice index right if I did this problem that way right I'll just keep track of the max ith index so the ith value that I'll use I'll just call it ice right so what I'm saying is for any J value there'd be a maximum I value that comes before it that'll provide it with the maximum sum so if I look at any J value and as I go through the system I just keep track of the maximum value before me I'll always have the value that I'll use to get the maximum i j pair using this J so what I'm basically saying is like let's call this J now okay and this is the value of I values the J value of any index the maximum value up to here right that would provide me with the largest I value is 8. right and the maximum value up to here that would so for so here we'll put uh values of I plus values of J so we'll put that system here so here there's nothing right because there's only one pair but we'll just put an eight it's fine or I'll think about what we'll do there for there now we'll just put a little just grid aligned it specify that we don't know exactly what's going to go there but what I'm going to do is every time I look at it look at a value I'll keep track of the largest ice value that I can use right because the largest I value will be what I connect to any J value that I encounter to maximize the score right so now when I'm looking at one I know okay I already know what my maximum ice value I should connect myself to I should use eight and I'll get a sum of nine and then I'll look at one and say does one increase my maximum value no 8 is still the best thing I can do right because I can just save what my I value is and then go through each J value and already know what I should pair this J value with to maximize the score right now when I look at 2 and I have 5 I say okay well my J values five and the maximum if I can provide is eight and that would give me eight plus five what is that uh 13. and then I look at five and say does five increase my ice value No 5 does not increase my ith value because my iPhone the maximum I value I can provide is eight okay and then same thing here I have two and I have eight I get 10 I'd ask does this increase my I value no this is 10 and then eight and six does this increase no so my iPhone my ice value is still eight plus six nine plus six fifteen fourteen so then I have the score here of 14 right so what I'm essentially saying right is when I go through this system if every time I look at a value I just keep track of the largest ice value then I'll know that's what I should match with my jth value right I'm going through the JS values and every time I see a larger value I say oh this would be a good ice value so I use that as the I value for any future iteration right because the I value always has to be less than the J value so every time I look at a value I can make it the ice value for the subsequent run right the only issue here is though is that you know eight is good here but as you increase the system there's an IJ Factor so just because it's eight doesn't mean it's going to provide eight right because what happens in this system as you increase right like it provides eight as a value over here but there's this huge distance between them so since there's a distance between them you're no longer going to get that total eight right because we can't forget about this I minus J part but what this will basically tell you is like in order to find the maximum pair and end time without this constraint right I would just keep track of the ice value that maximizes my score and for each J value connect that J value to that I value using this process here okay so that's the first observation the second observation is well if we look at this again maybe I can think of it in terms of the mathematics I plus the values of J plus I minus J right so that's the formula we're trying to maximize now what I said before for this right we catch the values at I right so we don't actually need to keep track of the values of I we just need to keep track of the max value that comes before J so we'll just call that the ith element we'll call that ice Max so every time we run this Loop we'll keep track of the maximum thing right so we can actually just write that code just so it's Crystal Clear what we're talking about here right so we'll call that ice Max and we'll call uh our Max pair and we'll set it equal to zero so what we basically do right is we look at each whoa what the heck somehow my isn't that weird what did I something got okay we have the our ice Max and our Max pair so what we'll do is we'll look at each value we'll look J's value we'll call this uh the max I value for each J value and values well we'll say well the max pair is if we use the max ith value plus the jth value or any previous Max pair that we found and then we'll update the max size value say okay is this new value that we're getting larger than the previous value that we found and we're going to do that compared to jth value and at the end we just return the max pair now this isn't right because this will this is not going to consider that I minus J this is just me coding up the solution to what I previously said an end time algorithm math I'd value I just love math so much I spell it out even when it's not related and object is not Max pair equals the max I don't know what I'm doing guys don't do this in interview don't continue to do things wrong okay so now it's saying 14 why well because it's doing this process here right where the maximum was 14 with 8 plus 6. so when the basic thing is we don't need to have what the value I is and I minus and I here right because for each J value we'll just have the maximum value that comes before us right so if we call that in our code Max ith value so let's use the same terminology so that things are clear all right Max ith value plus values of J Plus the ith index right because that's the index of I we'll just call it I whatever minus I minus J okay so now we don't need to actually know we need to know what i is but we have this variable here um so how can we think about this well let's just reorder this a little bit I actually don't know where I'm going with this so hopefully I get something that makes a little bit of sense plus values of J okay um so I guess the idea here right is that the maximum value is actually the maximum value the ith Value Plus the difference between where you're at now and where that I value is right so we could keep track of ice and update I accordingly but I guess something to notice here right is like every time J increases by one what happens to the max ith value in total right if the difference between these things is one right so if the difference between the ith and the jth element is negative 1 meaning that they're one apart from each other right so if they're one apart from each other then the total value that I'm going to be able to get from the maximum ice value is Max I value Plus minus one plus values of J right because they're one away versus if they're you know two away right if J is 2 away then the max ith value minus 2 plus values of J which makes sense right because every time they move I move one away from the max I value it's going to decrease by one right because whatever value I'm looking at if I want to make that the max again it's going to be one farther away so I'm going to base what I'm trying to basically say here using this way of writing it down if it doesn't make sense is eight is the max here right and it's going to provide eight minus one to this system here right that's how you get what so let's write down the whole thing again because I don't want to miss any point here because I'm going to end up making things too confusing right so let's still call this J it's fine okay so our formula is the values of I plus the values of J plus I minus J so when we're in this system here right and let's put that here this would just put a blank line when we're in this system here how much are we actually going to get provided when we reorder this system right because we're going to keep track of the ice value plus I minus J and that's one thing plus values of J well the ice value will provide us with a right this will become eight but since the ith values index is zero and this index is one effectively it's only providing me with seven does that make sense so the second observation really is like every time I move one away right every time I move the maximum value is going to get decreased by one in total right if I just looked at the ith value as this whole thing right it was eight but now since I've moved one away it becomes seven right because when it's using this value that what it's actually going to contribute is seven you can think of the I values being eight but since it's one away it only is going to contribute a total of seven to me right and same when I get to this 5 here right now the I value can only contribute six to them right because it can contribute eight but since it's two away right it contributes eight but since it's two away it's going to end up subtracting 2 from the ice value so it can only actually provide me with six right and then here it can only provide me with five and here it can only provide me with four right because every time you move one away you have to decrease what your maximum value was before by one because now it can only effectively give you one less than what it could give you before right if I think about it in terms of people right if this is the largest person or how would I do that maybe that's not a good idea but we should get two guys here that look pretty happy and sad but the idea is if I'm farther away even though you're eight every time you have to move one unit to get to me you're gonna have to decrease by one right so I might as well decrease You by one every time I increase the value of J because that is effectively what you're going to be able to contribute okay so that's how you can get this solution here right six plus five eleven five plus two seven four plus six ten seven plus one eight plus nothing here because I have nothing to compare to so maybe this shouldn't be this would be no as well okay so I'm hoping that makes a little bit of sense right the idea is for the second observation just to write it out write our second observation is although value of I is maximum at the I value in total value of I contributes value of I plus I minus J total points to value of J right so every time you increase the ith value the ith max value you have to every time you increase the jth index you have to decrease the ice value by one because every time you move over by one you get smaller right the idea is let's imagine that you had uh I don't know it's weird to think of it like that because it doesn't make sense on those terms but it's okay right so hopefully that makes sense so I ideally what you would do is you would just say well my new max value right at any Index right my Max I value is well you whatever my max value was before since I'm gonna move over one it's going to decrease by one so whatever my Max I value was before but now it's going to decrease by one or my new device value could be this JS value but it too is going to decrease by one right because when you increase J right when you increase J there'll be one away from whatever this value was and when you increase J it'll be one away from whatever this value was right the ice value used to be able to provide eight but since you moved over one now it can effectively only provide seven and since you moved over one it can now effectively only provide six and at some point if this was like 7 here right it would be better to actually use this value going forward right you would choose this value over this value to make this 6. because this 7 would become a six you wouldn't use the six anymore because it would only be able to effectively provide you with five right so it's kind of a greedy approach it's like whoever's close to me whoever can provide me with the most I don't care what your value with so I'll keep track of how far away the maximum thing is by every time I go to a subsequent index I'll decrease it by one because every time I go to a subsequent index I'm one more away from that maximum value pink up so instead the max ice value is now what well whatever the max I value was minus one right because now I have to decrease it by one because I'm going to be moving one to the right so now I'm one farther away from whatever that value was so whatever can totally contribute to me decreases by one or whatever this J value is minus one because maybe this J value can provide me with something larger right maybe it's even if the max I value used to be a hundred and this is only nine or this used to be ten and this is only seven but this is more than four away it'll get decremented to something smaller than seven so it'd be better to use this jade value right but it's still the same because the max I value now is just the effective value that I get from using that value because it encapsulates also the distance to the system since we're subtracting one every time we increase all right let's submit that and I'm just going to call this I and look at that Jace pair ice Jace right because now that we don't have I and J we don't need to we can just call it the ith value whatever and if we really want to be and whatever and if we really want to be fancy and we really want to impress ourselves you can put this all on three lines okay so what is the run time and space complexity of this problem let's say n is the length of values okay for time well we create these two variables so it's constant we just look at each value right so we look at all n values and then we just do two constant operations right this is a constant operation finding the max of two things this is a constant operation find the max of two things we say that the two variables constant operation so for n values we do constant things right so we do a constant thing for all n values therefore we do a total of N Things right proportional to O of n uh what about space well we just create these two variables and then we update them within the loop there's no recursion there's no additional stack space there's no you know it doesn't scale with n if the length of values was a million or the length of values was seven we only need to keep track of these two variables right whatever we think our Max pairs that we can find and the largest I value right maybe not the larger size value but the value that can contribute the most to the jth value because we decrement the ith value at every iteration okay all right guys that's all I got for today I hope you guys have a wonderful rest of your day rest of your weekend I Jace don't hate appreciate my coding skills are good go rate
|
Best Sightseeing Pair
|
k-closest-points-to-origin
|
You are given an integer array `values` where values\[i\] represents the value of the `ith` sightseeing spot. Two sightseeing spots `i` and `j` have a **distance** `j - i` between them.
The score of a pair (`i < j`) of sightseeing spots is `values[i] + values[j] + i - j`: the sum of the values of the sightseeing spots, minus the distance between them.
Return _the maximum score of a pair of sightseeing spots_.
**Example 1:**
**Input:** values = \[8,1,5,2,6\]
**Output:** 11
**Explanation:** i = 0, j = 2, values\[i\] + values\[j\] + i - j = 8 + 5 + 0 - 2 = 11
**Example 2:**
**Input:** values = \[1,2\]
**Output:** 2
**Constraints:**
* `2 <= values.length <= 5 * 104`
* `1 <= values[i] <= 1000`
| null |
Array,Math,Divide and Conquer,Geometry,Sorting,Heap (Priority Queue),Quickselect
|
Medium
|
215,347,692,1888
|
38
|
this is the most confusing coding question I've ever seen the problem is called count and say and the count and say sequence is a sequence of Digit strings defined by this recursive formula count and say of one that is equal to the string of one but more generally count and say at n is the way you would say the digit string from count and say at n minus one so count and say of one is just the string of one but now we need to count and say this well it's 1 one count and say of two is 1 one then we need to count and say this well it's not one it's actually two ones and so two ones oh well that is actually two and then one finally how do we say 2 1 we have one two and we have 1 one and therefore it's 1 2 1 yep I'm equally as frustrated I'm not going to walk you through it but save this video if you'd like to solve it yourself
|
Count and Say
|
count-and-say
|
The **count-and-say** sequence is a sequence of digit strings defined by the recursive formula:
* `countAndSay(1) = "1 "`
* `countAndSay(n)` is the way you would "say " the digit string from `countAndSay(n-1)`, which is then converted into a different digit string.
To determine how you "say " a digit string, split it into the **minimal** number of substrings such that each substring contains exactly **one** unique digit. Then for each substring, say the number of digits, then say the digit. Finally, concatenate every said digit.
For example, the saying and conversion for digit string `"3322251 "`:
Given a positive integer `n`, return _the_ `nth` _term of the **count-and-say** sequence_.
**Example 1:**
**Input:** n = 1
**Output:** "1 "
**Explanation:** This is the base case.
**Example 2:**
**Input:** n = 4
**Output:** "1211 "
**Explanation:**
countAndSay(1) = "1 "
countAndSay(2) = say "1 " = one 1 = "11 "
countAndSay(3) = say "11 " = two 1's = "21 "
countAndSay(4) = say "21 " = one 2 + one 1 = "12 " + "11 " = "1211 "
**Constraints:**
* `1 <= n <= 30`
|
The following are the terms from n=1 to n=10 of the count-and-say sequence:
1. 1
2. 11
3. 21
4. 1211
5. 111221
6. 312211
7. 13112221
8. 1113213211
9. 31131211131221
10. 13211311123113112211 To generate the nth term, just count and say the n-1th term.
|
String
|
Medium
|
271,443
|
1,926
|
guys I'll be solving nearest exit from entrance and Maze and this is a typical um BFS question breath first um where we'll be searching our nearest neighbor with our length with size one and if it's not found and we don't encounter a row or column that meets the boundary of this Matrix then we increase our search range by one and we go with the Neighbors of length 2. so with um BFS what we need is a queue and a Boolean array a Boolean Matrix to mark all except our entrance as false because our entrance will be placed inside our Boolean Matrix and inside our queue just to get the ball rolling and get it to get that as the starting point and we'll be uh once we'll get this uh starting position by Q dot pole and then we search our four nearest positions first and we check that if to filter out all the invalid options if it goes beyond the boundary like if it goes less than zero or greater than two for our row if it goes less than zero for column or greater than three or if we meet a plus and that Matrix and the node then we continue we don't add that to our queue or explore that option further and we know that once those conditions are clear then we're left with the valid options and if the valid if that position it's such that we are indeed on the boundary of this Matrix like if it's at zero or if it's that row or if it says zero or if it's that column then we know we have reached the answer so we're gonna return on the result and the um steps I'll call it steps so breadth would be defaulted to one before we even start the iteration and once we find a valid node on the boundary then we return steps so we return one here and if not we if we have all four if we have almost four positions that are unfortunately not on the boundary then we mark this as visited like as true and we add that to our queue to explore that option and this will be pulled in the next iteration and these four positions will be checked okay so that was a lot of explaining but once you see the code it'll be much simpler so and rows equals or staying late into a nice darling okay and we use a queue of integer array VFS equals new array deck and we create a Boolean Matrix let's say this to put new volume of size rows and calls I remember that we have to add the entrance to our queue and visited as our starting point so we have to add that entrance and we don't really have to do a conversion because it's an integer array and our queue contains an integer like this so we can leave it like this but for visited we have to convert it into rows and calls so entrance the first element and the second element we Mark that as true so this will be true okay and our breadth would be one we'll be starting from one Okay so I'll Define let's say size is um DFS dot size and so our Q our um BFS search ends on two conditions one is that if we find a position a path that indeed exists on the boundary of this Matrix then we just break out of the loop and we return steps but if we continue with all the possible um outcomes and our queue contains no nodes anymore then we know that we have exhausted all the options so that's when we return -1 the options so that's when we return -1 the options so that's when we return -1 so -1 -1 -1 so those two conditions so we want to check that while it is not empty um okay we want it right here and zero I less than size I plus and I have a I have had a really difficult time as to figuring out an error basically I did like I combined this two together so normally like we do four into icons zero I less than BFS dot size and I plus right and I was wondering why this was causing an error so if you see my submissions uh yeah I was like why is it causing an error and that's because our BFFs our cue size changes when the loop runs and we've added like um notes that have been visited and our size of the queue so our size by default is one right like for here we've added one entrance so our size is one but what if we have like four valid options that let's say we have four value options here and we've added that to our queue then our size has been defaulted to one here so our beer festival only pull one out of four options so that's not what we want so we have to do this I'll run this code first and then I'll run this code later to see what there is okay ah less than size and where was I um yep um and row up we want to pull the um position the starting position so and our end row would be this and call would be this Okay so we've gotten our rolling column I want to we want to check the four positions that we can go so let's say oh adjacent cell I recent okay adjacent cell both new and oh man and here we have to create the full uh paths that we can take so row plus one call row minus one or plus one row whole minus one okay and we see that let's say all right let's say a Json plus possible solutions and we say adjacent cell in our Json boss and we say a Json row as adjacent cell so basically making our lives easier because we have to use this variable when checking the validity of the parts so if you want to filter so if it goes beyond the boundary or if we meet this block which is marked by positive sign so if it goes beyond the boundary or if it goes Beyond Rose and if the Json call same thing greater than oh false and if it is not by a positive sign then we continue we don't explore this option further and now we're left with the valid options let's say this and this right for this starting position so if that node has not been visited before so we know that it's going to be false so that node has not been visited and if that row and column is indeed on the boundary of this Matrix then we know that's the answer so Json row adjacent row s minus one remember zero index uh adjacent Paul calls minus one then we know that we've reached the answer so return steps how can I make it nice okay return steps um if not if like for example here we're not along the boundary so we Mark that as visited and we offer that to our queue to be explored further oh wait no queue BFS offer and remember our BFS contains an integer array so we create a new image pretty soon raw adjacent call okay and okay so if all the four positions have been um checked and if we don't find that answer then what we have to do is uh to increase the breadth so we increase the search range from one to two so until here and if not and our queue is empty and we've exhausted all the um possible notes that we can travel or we can visit and we have no choice but to return minus one oh sorry oh man no sign then uh mm-hmm mm-hmm mm-hmm okay yep and it varies runtime but for me the personally learning point is that we have to remember that our cue size Alters so it's not fixed at size one at the beginning so for example if let's say we have like a block here then our queue will offer will have two values this and this considering if this is a block okay then what if we have what if we say like this then for the two um values that we have added to our Q only one will be explored here so if I say submit like this then wait instantly oh okay if I say like this it's kind of hard to look at this thing but we are missing a additional sorry for your uh expecting five we only get four so we know that a possible um value in our Q has not been explored fully so we have to know that this is wrong and that our efsq size Dynamic it will alter depending on the um this folder will change and be different from the initial size of that the size of one when we added entrance to two one Dolly of entrance okay and yeah that's basically it so hmm yeah we say we've set it to true and we add that to our queue and so for here if this runs all perfectly fine then we've export all the four paths and once we've exhausted our queue that's when we increase the steps because we know that just the four parts in just exploring the four parts of the values stored in our queue is not enough so we have to increase the search range yep all right so that was a long pretty long I think a pretty long solution but I hope you guys understood a bit and I'll see you guys next time bye
|
Nearest Exit from Entrance in Maze
|
products-price-for-each-store
|
You are given an `m x n` matrix `maze` (**0-indexed**) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where `entrance = [entrancerow, entrancecol]` denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell **up**, **down**, **left**, or **right**. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the **nearest exit** from the `entrance`. An **exit** is defined as an **empty cell** that is at the **border** of the `maze`. The `entrance` **does not count** as an exit.
Return _the **number of steps** in the shortest path from the_ `entrance` _to the nearest exit, or_ `-1` _if no such path exists_.
**Example 1:**
**Input:** maze = \[\[ "+ ", "+ ", ". ", "+ "\],\[ ". ", ". ", ". ", "+ "\],\[ "+ ", "+ ", "+ ", ". "\]\], entrance = \[1,2\]
**Output:** 1
**Explanation:** There are 3 exits in this maze at \[1,0\], \[0,2\], and \[2,3\].
Initially, you are at the entrance cell \[1,2\].
- You can reach \[1,0\] by moving 2 steps left.
- You can reach \[0,2\] by moving 1 step up.
It is impossible to reach \[2,3\] from the entrance.
Thus, the nearest exit is \[0,2\], which is 1 step away.
**Example 2:**
**Input:** maze = \[\[ "+ ", "+ ", "+ "\],\[ ". ", ". ", ". "\],\[ "+ ", "+ ", "+ "\]\], entrance = \[1,0\]
**Output:** 2
**Explanation:** There is 1 exit in this maze at \[1,2\].
\[1,0\] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell \[1,0\].
- You can reach \[1,2\] by moving 2 steps right.
Thus, the nearest exit is \[1,2\], which is 2 steps away.
**Example 3:**
**Input:** maze = \[\[ ". ", "+ "\]\], entrance = \[0,0\]
**Output:** -1
**Explanation:** There are no exits in this maze.
**Constraints:**
* `maze.length == m`
* `maze[i].length == n`
* `1 <= m, n <= 100`
* `maze[i][j]` is either `'.'` or `'+'`.
* `entrance.length == 2`
* `0 <= entrancerow < m`
* `0 <= entrancecol < n`
* `entrance` will always be an empty cell.
| null |
Database
|
Easy
|
1948
|
1,431
|
Hello friends, welcome to the channel, this is lead code 1431, which is the number three question of lead code 75. We are preparing for 19 days in which I am making you do DA, so looking at the question, it is a very easy question, Kids with Greatest Number. Of candies, you just have to read the story, the question was very easy, actually see what is this question, you have been given these few candies, 2 3 513 and extra candies, explain the example, you will understand in a minute, 2 53 and extra, so the children have candies. 2 3 5 1 3 You have three more extra candies. You can give extra candies to any one child and you have to tell whether after giving those candies that child will have the maximum or not. Okay, so see what is the maximum now. The maximum is if I give three to the first one then it will be 2 P 3 5 then grain equal to 5 then yes maximum will be achieved if I give it to the second one then it will be more than 3 P 3 6 5 then give it to the third person. Let 5 + 3 8 be more than 5, give it to the third person. Let 5 + 3 8 be more than 5, ok if the fourth one is less than 1 p 3 4 f then false 3 p 3 6 if it is more than 5 then true false true this is the answer, check once. Do it whether it is true or not otherwise true to true false true basically we will take the question tell me what is it take see what is the question for you take the max of the whole array this is your array take the max of the array max if so that's it Now you have to give True False in the list. Now you do not have to do anything. Which number is your I have done it and it is easy, so let me code this in front of you. I have made airless ballin, if you return then you will take out max first, so what did I do for max, I put candies of zero, now this kind of code can be wrong. If the array of candies comes up empty, then we are told that there will be at least two elements inside the array of candies, then I can set max to zero and run the loop with i = 1. can set max to zero and run the loop with i = 1. can set max to zero and run the loop with i = 1. Finding the dot length maximum. So max is equal to method max of effect, we use it only if there is no internal code inside caddy's math max, if it is a little more than this then it can run very minimally but still if gr is equal to max then Now replace the max, come, you have got the maximum, now what to do, again we put the loop, I put the loop with 0, candies, now what will I check everywhere, what is this value plus extra candies what? It is greater than equal to max. If yes, then I will insert true. Otherwise, I will insert false in fact. Look at the answer dot true. Instead of doing false in else, you know what you can do. Look, I would insert true in if and else. If it does false then basically this expression is either true or false then just add this expression na expression is a Boolean expression value plus extra candies greater than equal to max is a Boolean expression so if value plus extra candies greater If the value is max then it will return 2. If it is false then it will return false. Whatever happens, our add will be done. So it is better to add true false by doing if then add the expression directly. It was a very easy question. User Question on Beats 94 It was very easy, so I hope you have understood, so let's move to the next question. Okay, before leaving, I will just tell you that, I will give you two links in the description to a school of technology, if you have any younger brother or sister. So you can apply through my link. Okay, secondly, I will give you the link of the journal. So friend, do comment on your progress. You have to support me for these 90 days. Comment on my journal. Tell me, what are you doing? How is the preparation going on, what are you trying, where are you losing, where are you winning, okay, let us get evolved, more evolved, let us prepare together, okay, let me tell you about SST, why is it amazing, do you know what it is like? Did you study in college or did I study in college at the age of 50 but I studied non-CS, so inside SST, the studied non-CS, so inside SST, the studied non-CS, so inside SST, the curriculum is 100% CS, the entire curriculum is 100% CS, the entire curriculum is 100% CS, the entire curriculum is only CS, okay, so there is only CS in the curriculum, then the culture of our college. Because there were all kinds of children inside, the culture also changed. The culture here is the same whether the children are there from day one, first year children, after four semesters and four months have gone to play ACM ICPC, so the culture is the same. The one with Code Chef, the one with hack thas, that culture, then who are our instructors? Who were your instructors? Who are the PhD teachers? Do you know who is their instructor? Who is their instructor? Aman Rajput, who was my first student who went to Microsoft? Not the first one, my first student from MET [ went to Microsoft? Not the first one, my first student from MET [ Sangeet] Scar of Technology will be the first to reach so if this appeals to you then admissions are on at the moment I will put the link in the description so you can go and apply if you need some coupon code to apply for something like this then I can help you whatsapp-web thank you so much let's meet the whatsapp-web thank you so much let's meet the whatsapp-web thank you so much let's meet the next question bye
|
Kids With the Greatest Number of Candies
|
all-ancestors-of-a-node-in-a-directed-acyclic-graph
|
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have.
Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _if, after giving the_ `ith` _kid all the_ `extraCandies`_, they will have the **greatest** number of candies among all the kids__, or_ `false` _otherwise_.
Note that **multiple** kids can have the **greatest** number of candies.
**Example 1:**
**Input:** candies = \[2,3,5,1,3\], extraCandies = 3
**Output:** \[true,true,true,false,true\]
**Explanation:** If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
**Example 2:**
**Input:** candies = \[4,2,1,1,2\], extraCandies = 1
**Output:** \[true,false,false,false,false\]
**Explanation:** There is only 1 extra candy.
Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.
**Example 3:**
**Input:** candies = \[12,1,12\], extraCandies = 10
**Output:** \[true,false,true\]
**Constraints:**
* `n == candies.length`
* `2 <= n <= 100`
* `1 <= candies[i] <= 100`
* `1 <= extraCandies <= 50`
|
Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
1912
|
240
|
all right so let's talk about the social 2d metric too so you have to write an efficient algorithm and then there is a target in the metric and then you have to search for it right so here's it so this is a target so you can actually use a brutal force to traverse every single one of the columns i mean one of the cells right and then to see if there are a cell in is equal to the target if this is true then your return true if not your return false so again but you have to write efficient uh solution uh the brutal force is not the efficient one so for my solution i start from the top left and then i have i equal to zero uh i equal to zero and j equal to uh m minus one and n represent what and represent the row and this is an all right this is an and then my end represent a column right and this is it so i will traverse from this cells all the way to one i can either go down or i can either go left right so um this is uh pretty much the idea so what's the constraint so if the i is less than n this is okay right and also j is squarely equal to zero this is all inside the green right so what happens if they are not inside of three so if there are if there's a value not in the table and then you have to uh you have to get uh get out of the free to search for it and then you return false so this is it right and let me just uh just demo if probably you could apply so if probably equal to 5 i start from here right so i'm going to say the num is actually equal to what the metric a i j right so 15 is a num the target is 5 so is 5 to 15 no they are not right so you don't return true but 5 is what 5 is less than 15 right so if 5 is less than 15 then you probably need to write you probably need to going down right so uh going left right so again uh 11 doing that seven right going left all right now you have four right so five is five less than four no right then you're going down so again you'll find the efficient solution you just go either left or bottom so this situation now you're not able to search for it so you already get rid of the half of the degree so this is much more efficient so let's start coding so in i'm going to just define my earning the metric length and equal to matrix and view collect i to the k equal to n minus 1 and then while i is what i is less than n and also j will be equal to 0 right so a noun equal to what matrix i j if the target is actually equal to a norm i find it right i will return true if not if target is what if probably a squarely known right i plus else now you're either going down this is going left right uh everything else you cannot find it your return flows so here is it and submit so let's talk about the time and space this is space constant right even though i look at the space inside the value i mean this is pretty much like constant and then for the time it does look like all of n times n but the problem is you cut the matrix into the hat right when you're going left or when you're going down so this is actually all of um plus and i mean for the one is what the role of the measure and then m is the column of elementary right so prime so here's my quick note time is n plus n basis constant and then represent the length of a matrix and represent the endoclamatory zero alright so this is a solution and i'll see you next time
|
Search a 2D Matrix II
|
search-a-2d-matrix-ii
|
Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties:
* Integers in each row are sorted in ascending from left to right.
* Integers in each column are sorted in ascending from top to bottom.
**Example 1:**
**Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 5
**Output:** true
**Example 2:**
**Input:** matrix = \[\[1,4,7,11,15\],\[2,5,8,12,19\],\[3,6,9,16,22\],\[10,13,14,17,24\],\[18,21,23,26,30\]\], target = 20
**Output:** false
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= n, m <= 300`
* `-109 <= matrix[i][j] <= 109`
* All the integers in each row are **sorted** in ascending order.
* All the integers in each column are **sorted** in ascending order.
* `-109 <= target <= 109`
| null |
Array,Binary Search,Divide and Conquer,Matrix
|
Medium
|
74
|
724
|
hey there fellow coders welcome back to codemaster Quest I hope you are having a fantastic day because we are going to dive into another exciting problem today we are tackling the problem of finding the pivot index in an array so grab a cup of coffee sit back and let's get our code on here's the question description uh given an array of integers Norms we should calculate the pivot index of this error and what is the period index you know as you can see here is the index where uh where the sum of all numbers um strictly to the left of the index is equal to the sum of all the numbers directly to the index is right and if the index is on the left edge of the array then the left sum is zero because there are no elements to the left this also applies to the right edge of the array and at the end we should return the leftmost pivot index and if there is nothing like this we should return -1 nothing like this we should return -1 nothing like this we should return -1 and if you consider this example one if you have an array like this we should return number three and why this is happening because if you consider index number three which is this number six um you know the elements on the left the sum of all the elements on the left is equal to 11 and the sum of all elements on the right side of this index is equal to 11 as well so now let's switch back to them Visual Studio code and try to solve this question let's solve this question and first of all we need to Define our function signature find pivot index then we should Define the input for this function which is going to be an area of integer let's call it nouns array of integer and at the end we should return the pivot index which is going to be integer again right and to solve this question the first step is to calculate the total sum of this array let's calculate the total sum in this way total sum equal to Norms that reduce 0 and plus and if you want to do it in a you know in a simpler form you can make a simple for Loop iteration for item in nums and then in each iteration you can say total sum plus equal to item but I prefer to do it in the shorter version and to solve this question I'm going to make an iteration over the elements of this array and in each iteration uh I want to check whether the left sum is equal to the right sum right and to do this we should calculate the left sum and write some in each iteration for this purpose I want to Define a variable called Left sum and set it equal to zero at the beginning then let's make our iteration let's say for I in 0 up until two nums that counts I want to you know add the value of the current index to that left sum let's say plus equal uh nums I but I prefer to do it in this way I can say value equal to nums.i say value equal to nums.i say value equal to nums.i and say left some plus equal to value right but before uh before adding you know uh the existing index to the left side I want to check whether the left sum is equal to the right sum right so for this purpose I need to calculate the right sum let's say right sum is equal to Total sum minus left sum from the previous index uh minus the value of current index and this will give us the right sum right so here we can check whether the left sum is equal to right and if this is the case then we should return this specific index and if we went through this um you know folder and we didn't find anything we should return the non-existing pivot index flag which is non-existing pivot index flag which is non-existing pivot index flag which is -1 -1 -1 right so this should be the solution for this question but to make sure everything is working correctly let me switch to the browser uh find the examples for this question like this come back to the visual studio code that's it okay let's sort this array somewhere let equal let num equal to this one and then let's call this function pivot index for norms and let's store the result somewhere that result equal to this one and then print the result okay now let's call um you know let's run this to a file Swift problem one that's three right let's check whether the expected value is 3 or not yeah the output is three right so this should be the solution to this question but to make sure everything is working correctly let's come back to the visual studio code close the terminal copy the solution come back to the browser and submit this solution to a lead code hit the submit button and yeah that's it where's the solution to this question thank you everyone
|
Find Pivot Index
|
find-pivot-index
|
Given an array of integers `nums`, calculate the **pivot index** of this array.
The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right.
If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array.
Return _the **leftmost pivot index**_. If no such index exists, return `-1`.
**Example 1:**
**Input:** nums = \[1,7,3,6,5,6\]
**Output:** 3
**Explanation:**
The pivot index is 3.
Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11
Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** -1
**Explanation:**
There is no index that satisfies the conditions in the problem statement.
**Example 3:**
**Input:** nums = \[2,1,-1\]
**Output:** 0
**Explanation:**
The pivot index is 0.
Left sum = 0 (no elements to the left of index 0)
Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0
**Constraints:**
* `1 <= nums.length <= 104`
* `-1000 <= nums[i] <= 1000`
**Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/)
|
We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1].
Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].
|
Array,Prefix Sum
|
Easy
|
560,2102,2369
|
1,770
|
lead code challenge the problem that we have in today is maximum score from performing multiplication operation here in this question we are given two arrays nums array and multiplier array what do we need to identify the maximum score that can be generated after performing n operations and there are a few rules that are specified in the question I'll be walking you through these rules as well as the algorithm to solve the question by the presentation so let's quickly hop on to it get back to the problem given the number array you are given the multiplier array and what you need to do you need to identify the maximum score that can be generated after performing M operations and M signifies the length of your multiplier array and with each operation you have two options you can you need to select an element from the multiplier array and you can multiply it with either the leftmost index in nums or the rightmost index in nums either the leftmost index or the rightmost index and after performing M operations one for each element in the multiplier array you need to tell what is the maximum score that could be generated the most obvious approach after reading this question that comes to everybody's mind that we can go in the greedy manner however greedy will not lead to the maximum result why I'm saying this let's try with the same example so right now we are at three and you have two options either to choose one or three so as per the greedy algorithm you will select three so 3 into 3 gives you 9 let's proceed ahead three got consumed and let's we move to the next element and this three is also gone the next element that we have is two for two which one are we going to Select 1 or 18 we'll select 18 so 2 into 18 gives you 36 and 18 is gone so is two we move to the next pointer we have five for five the answer remains as 1 so 5 into 1 is 5 the total sum turns out to be 9 + 5 is the total sum turns out to be 9 + 5 is the total sum turns out to be 9 + 5 is 14 + 36 gives you 5050 is this the 14 + 36 gives you 5050 is this the 14 + 36 gives you 5050 is this the right answer no it's not the right answer how by I'm saying this let's go with the another approach let's restart the iteration at three I have two options either to go for the leftmost element which is one or I can go for the rightmost element which is three so let's assume I select three this time so my total score gets updated to 3 into 3 gives me 9 so this element is gone so does this one now let's move on to the next multiplier element which is two add two I have two options either to go for the leftmost element which is one or the rightmost element which is 18 this time instead of selecting 18 what I'm going to do I'll select one and I'll keep 18 for the later portion because some bigger element may exist in future and multiplying that element with 18 can lead to more or higher result so I'll consume one instead of 18 so let's do that we get 1 into 2 gives you 2 and one is gone so does two let's move on to the next element that we have is five only one element is left in nums which is 18 5 into 18 gives you 90 so let's write that up and the total sum turns out to be 1 01 which is way much higher than the greedy approach that we followed also that signifies that we need to consider all the possibilities that we may exist as part of computing the answer and therefore uh since overlap apping cases would be there we have to consider dynamic programming approach how we will be doing that let's move on to the next slide let's consider a hypothetical scenario where we are given a long array and uh we will try to derive the equations for our dynamic programming algorithm how to go about it let's start the iteration let's assume we are given the long array and L represents the leftmost index of this array right represent or R represents the rightmost index of this array we have the multiplier array given to us we will use I to keep track of the index under consideration in the multiplier array and the values for I can range from zero and goes up till M where m is the length of the multiplier array and if I select if I ask you guys we are at the I index in the multiplier area and what two options do we have either we can pick up the element from the leftmost index or we can pick up the element from the rightmost index if we go for selecting the leftmost index what would be the equation so we multiply the m multiplier element which is M at the ith index with nums at the leftmost index pretty simple and straightforward very obvious what remains after consuming the leftmost index in my nums are it is left + one up till right so are it is left + one up till right so are it is left + one up till right so since we have consumed this element we will increment this to the next pointer which will be l+ 1 and uh the rightmost which will be l+ 1 and uh the rightmost which will be l+ 1 and uh the rightmost index Remains the Same because this portion of the array is to be considered there that's the reason we have passed in left + one to the same recursive in left + one to the same recursive in left + one to the same recursive method and right index Remains the Same along with this we should increment our I pointer because we have identified and consumed one possibility that corresponds to n muls of I and we will be incrementing and looking for the future values which would come from I + future values which would come from I + future values which would come from I + 1 let's do the same thing assuming instead of picking up the leftmost element we picked up the rightmost element and since we picked up the rightmost element what would be the equation like mul at the ith index gets multiplied by nums at the rightmost index along with this we should write the equation for the remaining portion of the elements that we have so leftmost index Remains the Same we reduce the rightmost pointer by one and I again gets incremented by one for the next iterations to happen once we have identified uh pick left value and pick right value what do we identify the maximum value out of these two and we set it at DP of left comma right pretty simple and straightforward guys it's exactly the same steps I have written that was specified in the question itself so the question gave you a lot of hint with respect to solving this problem up now let's move on to the coding section there's a small catch over here which I'll talk in the coding section rest of the things I'll exactly follow the same I have created two private methods one for keeping track of number of elements that I have in my Namar other one is for msar and this is a map that I have used in order to submit the code using memorization technique of dynamic programming so let's start the iteration so the value of M and N sets up uh we initialize the memorization array with new integer and uh the parameter that I have passed over here is n cross n and in the question it is also specified that n would always be greater than M so we are pretty safe with respect to it let's walk through the core algorithm that I have written in the method of DP so what parameters ases it accepts the leftmost index it accepts the rightmost index which is this one it accepts my numar it accepts my M AR and the last one is keeping track of the index under consideration in my Ms AR if my I index has GED my terminal state that means I happens to be equal to m i abort the process and return zero from that because that's my termination condition what do I do next I check whether have I preet Ed the value for the result starting from the leftmost index comma rightmost index ever in the past if I have that answer with me I reutilize it so this is a typical way of memorization in recursion or dynamic programming let's proceed ahead let's look at the next two lines which is picking up left and picking up right so these are exactly the same that I showcased in the presentation and once you have computed them up what do you select the maximum one out of these two and set it to your result value at left comma right so let's try and submit this up this solution is perfect and it should ideally work however it will give you memory limit exceeded exception so let's see that exception memory limit exceeded so the concern here is the size that we have created for our memorization which is basically reducing the time complexity however this memory limit is getting exceeded hard memory limit not a concern for us the solution would have worked so how do we optimize on this memory limit can we do something better the answer is yes let's reduce the memory size from value of n into n to M into n how to go about it let's walk through the coding section so let me just commment this up and let me just uncomment this up and let's try and submit this first so as to check whether it works or not accepted which is pretty good in terms of time complexity and memory and if you carefully observe over here then we have updated the size of our memorization array from n into M to M into M and in the question it is specified that n will always be greater than M let's walk through the DP helper method that I have created which is responsible for the core logic instead of keeping r as my index over here I have filled in I which is basically keeping track of the element under consideration in my Mal so again this REM condition Remains the Same if I happens to be equal to M I return zero if we have pre-computed the return zero if we have pre-computed the return zero if we have pre-computed the value in the past for L comma I then we reutilize it otherwise what do we compute the left pick value there's a small deviation in the equation that we previously discussed so here what do we multiply nums of left into Ms of I so this portion Remains the Same however let's talk about the Des of the equation we pass in DP and we pass increment the value of left pointer I also gets incremented by one muls and nums Remains the Same what about the rightmost index so we will keep track of the rightmost index using the combination of n i and L what I'm trying to say let's walk through the next equation so we let's understand pick right so pick right uh the interesting part Lies over here so mof I gets multiplied with n- i - l - 1 mof I gets multiplied with n- i - l - 1 mof I gets multiplied with n- i - l - 1 so if you carefully take few examples and write it on paper and Pen then you will realize that this will signify the rightmost element and since this signifies the rightmost element we multiply it with I and identify the total product that comes as the result and we pass in 2 DP of L comma I + 1 and we pass in 2 DP of L comma I + 1 and we pass in 2 DP of L comma I + 1 nums and Mal so this is the final equation we select the maximum out of these two and we set it at left uh memorization of left comma I so this is it let's try and submit this up as I previously told as well and still if you're interested in looking out for the bottom of approach then Anu has already raised the we are on coding decoded GitHub Rebo where he has beautifully explained the bottom of approach so this approach is slightly higher than what we just discussed you are open to understand this up and it's pretty simple and straightforward almost exactly on the same lines as I just talked over to you guys I hope you thoroughly enjoyed these sessions I'm attaching the link to the solution in the coding repo so do check them out with this let's wrap up today's session I'll see you tomorrow with another fresh question but till then goodbye
|
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
|
1,302
|
hey what's up guys new ID here i detecting coding stuff on twitch in youtube today we're gonna be doing a tree problem called deepest leave some this medium problem it's actually a newer one got out recently and it's actually not it's pretty easy for a medium problem compared to there's an easy one like path some tree or something that's much harder and it's easy um given a binary tree is just a tree where each node has 0 1 or 2 nodes so this has you know 0 either you know this one has 0 you could see we could have 2 you could have one child just 0 1 or 2 because binary is base to number system right return the sum of the values of the deepest leaves by the way I have a green screen yo so I'm not blocking the code anymore just had to you know say that I just got it okay given a binary tree return the sum of values of its deepest leaves so deep his leaves in this case what I thought it was at first was okay this is a deepest leave and this is devious leaf it's just counting it's just talking about the leaves at the very last level so even if it's like a leaf node down here that doesn't count it's just the very final level of leaves so to do this like it's actually not too difficult what we're just gonna do is a basic BFS or level order traversal where we just go this level and we just have a sum of all the nodes at each level so 1 5 whatever this is 9 plus 6 15 and then at this level we'll just we don't care about the sums of these so we'll reset it every time as we loop and then just in this level will just calculate we'll have the sum and then just return the last sum that we get because it's the sum over the final level so we just run the final level of nodes the sum of the level at the final it's pretty straightforward just a BFS so we could use a queue to do this that's how BFS is Andy you know normally done he just set up a queue so we'll do a queue of tree nodes all BFS is already just do a new linked list and then he just oops what are we doing wrong QQ seems good to me was it indenting weird that was weird what am i doing okay queue of tree nodes sorry about that kind of ruin the flow of the tutorial but it's fine okay so the zig BFS is this is how basic BFS is you have a queue and you just put the root on right so the first thing on the queue is this and then we evaluate them in levels right so we're gonna evaluate the nodes as levels so we're just going to evaluate this then we're gonna put you know the children onto the queue so 2 & 3 will be on the queue then we 2 & 3 will be on the queue then we 2 & 3 will be on the queue then we evaluate all those then we put all of these on the queue as we evaluate and we just add these to a sum and now you just keep doing it's just level by level it's you know basic as it gets so we're just gonna make a level some variable so we could actually just do that down here you know level some we'll keep track of the sum of all the nodes at each level we'll just set it to zero while queue is not empty so as we go through we'll be adding things for the queue so it won't be empty until we get to the very end and evaluate the last notes because there'll be no more nodes to put onto the queue we will have a loop in here and we're gonna go from 0 up to sighs I plus and size is going to be Q dot size the size of the queue and basically this just works so that we evaluate all the nudes nodes level by level you need this loop cuz you know we put two nodes on the queue you know we can't just evaluate one note at a time because we won't be able to keep track of the level so you have to do it level by going up to the size because the size of the queue will increase each time so the size will be one then it'll be 2 then it'll be 3 then will be you know - it'll be 3 then will be you know - it'll be 3 then will be you know - it'll be different every time so we want to go up to the size of that level basically the queue size will be the size of the level how many nodes are on at the current level right ok so when we go up to the size all we're doing is you know you do tree node current node fools queued up poll sorry do that poll see pop a note off the queue so you pop one off the queue one is on the queue we pop it off right away okay now we evaluate it we add it to the level some so we say level some plus equals current note Val now we have to add the other the children onto the queue to go over the next level okay so to go over the next level we just we don't want to add nulls on to the queue like we don't want to add you know seventh children are null five children are no so you want to do current node left we're gonna do a check that the node dot the children are you know not know before we add it to the queue then we do a cute offer and we do current node got left because left doesn't know and then you can just we'll just copy and paste so we could speed this up since I messed up earlier this is for the right node make sure the right node isn't null and then you could add the right node right child onto the queue Wow okay now pretty straightforward right okay so we pop nodes off and we evaluate the whole level we get the level some right and basically all we're gonna do is just every time we go to a new level we just reset the level some back to zero so level some goes back to zero and yeah and then when you get out you'll have evaluated so it'll be like okay yeah we'll just walk through to the second you returned the last level something basically cuz level some gets set to zero right at the beginning of the loop right so level some zero okay root is on the queue so ones on the queue okay we evaluate that level 1 the SOT we add one to the level some we add two and three on to the queue right they're not no so we had two and three out of the queue okay next level some is 0 again so new level some now we evaluate 2 & 3 because level some now we evaluate 2 & 3 because level some now we evaluate 2 & 3 because we go up to the size of the queue because it's two so we go two and three we pop those off okay 2 plus 3 is 5 so we get level some is 5 we add all of their children nodes onto the cube 4 5 & their children nodes onto the cube 4 5 & their children nodes onto the cube 4 5 & 6 right we were sad level some back to 0 we add 4 5 & 6 we get 15 then we go back we add 4 5 & 6 we get 15 then we go back we add 4 5 & 6 we get 15 then we go back to 0 then we have 7 & 8 are the final to 0 then we have 7 & 8 are the final to 0 then we have 7 & 8 are the final ones on the queue we evaluate both of those 15 and we break out of the loop because the queue is empty at this point because they don't have to notes add so the level some doesn't get set back to zero and then you return it that's basically it I did this live on livestream I got the green screen so you know please like and subscribe to help me grow the channel I'm taking it a lot seriously cuz I you know I bought a you know my setup is very I bought a new PC for the streaming that gun didn't mic I got the you know the green screen I got everything so please like and subscribe help me support the channel I really appreciate everyone the you know swatches for its channel P so I got another message today saying someone gotten to Google again because of my videos which is really awesome so thank you guys for watching please you know everything thank you and yeah I'll see you in the next video more questions coming all right peace
|
Deepest Leaves Sum
|
delete-characters-to-make-fancy-string
|
Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 100`
|
What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest.
|
String
|
Easy
| null |
1,933
|
hello so this question is check if string is decomposable into valid equal sub so what is valid equal string they have the same character same Char all right what does uh decompos mean like there must be a l of two um substr in the string if and others remaining l of three and you will only return true if you can decompose s all right so just one quick example for I mean sorry one quick explanation for this one so example one return false because you don't have L of two example two you can return two because you can split the one the L of one digit into three and two separately so this will return two so I mean this is actually pure logic so uh I'm going to start holding and then you will just follow along so if s the lens M by three does not equal to two I will return false why because it must be one exactly one sub then of two right and everything else should be three so this will be the base condition and I'm going to check my result for the L of two is what uh is valid right so I'm going to using this counter so I will have a two pointer so it's going to be I and then s. length I ++ and then Jal to I so what I need to ++ and then Jal to I so what I need to ++ and then Jal to I so what I need to do is try versing the C Char the same character and sart at a i equal to sart at AJ and then j++ so based on this I will get all of j++ so based on this I will get all of j++ so based on this I will get all of the same character into one combination so for example I and J starting from here and J will just keep going right until it break out a full loop so how when does it break out a full loop it will definitely break out a full loop right here at a one position right so I'm going to check so J minus i j minus I represent what the length so j 0 1 2 3 minus 0 is three right so cancel okay so if J minus i m 3 if this is equal to two I increment my counter so this is one allowable right and then if my result equal to two like there are two um substring uh which contain L of two you want to return for right here so what does this mean so if J minus I Mo by 3 equal to one so what do M by 3 equal to one mean like there is a outside condition which doesn't satisfy this one and also this one you will return false right away so once you have list you want to reinitialize your value should be what your I mean your pointer value so for example J was here right and I was here right here and here so what do you need to do you want to reset your I right but your I will be increment one by one every single iteration so keep in mind you cannot say J equal to i j equal to I doesn't work I mean we want to start at this position but J equal to I if we say you know I equal to J sorry I equal to J right here on the next iteration you increment so you are starting from here so you want to say i = j minus one J minus one is right here = j minus one J minus one is right here = j minus one J minus one is right here right and then the full iteration will increment the I automatically and to here so this is a little trick so IAL to Jus one so this will be it so simple enough so all right so what is the time in space is constant so for time all of N and also this one you basically traversing based on the uh the same character right I mean both for worst case is going to be what uh this will be all of I mean this will be all of n but once we Traverse list we will reset I and the I isn't keep going for the rest of the value so I would say the worst case going be this one all of them because this one is considered all of them if they are all the same character but you actually reset your I which will help you to reduce the time complexity for the I duration for the full loop so time will be all of them for sure so if that's a if that's the case all right so if you have question leave a comment and I'll see you next time bye
|
Check if String Is Decomposable Into Value-Equal Substrings
|
number-of-different-integers-in-a-string
|
A **value-equal** string is a string where **all** characters are the same.
* For example, `"1111 "` and `"33 "` are value-equal strings.
* In contrast, `"123 "` is not a value-equal string.
Given a digit string `s`, decompose the string into some number of **consecutive value-equal** substrings where **exactly one** substring has a **length of** `2` and the remaining substrings have a **length of** `3`.
Return `true` _if you can decompose_ `s` _according to the above rules. Otherwise, return_ `false`.
A **substring** is a contiguous sequence of characters in a string.
**Example 1:**
**Input:** s = "000111000 "
**Output:** false
**Explanation:** s cannot be decomposed according to the rules because \[ "000 ", "111 ", "000 "\] does not have a substring of length 2.
**Example 2:**
**Input:** s = "00011111222 "
**Output:** true
**Explanation:** s can be decomposed into \[ "000 ", "111 ", "11 ", "222 "\].
**Example 3:**
**Input:** s = "011100022233 "
**Output:** false
**Explanation:** s cannot be decomposed according to the rules because of the first '0'.
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consists of only digits `'0'` through `'9'`.
|
Try to split the string so that each integer is in a different string. Try to remove each integer's leading zeroes and compare the strings to find how many of them are unique.
|
Hash Table,String
|
Easy
| null |
74
|
in this video we will solve a problem where we are given a 2d matrix or a 2d array and the numbers are sorted and we have to search in this so numbers in the rows are all sorted and so this increases in this order so 1 is the smallest then 7 it's increasing in this direction and in the next row it's more than the last element here so it's further increasing so it's if you pick this row first row then second row then third row then still it will be sorted so we have to search in this so how can we search it for example if you see here we are searching for three and it's present so let's see how we will do it will be very similar to the way we do a search in a 1d array which is sorted which is doing binary search of course you can search element wise but that is not efficient so here we have row and column instead of just rows so uh first we need to figure out which row the number belongs so by looking at this so let's say you are asked to find 3 so what you will do you will see that here 23 is the smallest element in this row 23 is the smallest and this is more than the target value 3 so all the numbers will be more so there is no point in searching in this row so just by looking at one element we are clear next we come here we look at the first element it's 10 so this is more than three so all the numbers will be more than three no point in looking here we see that one is less than three then we know that it might contain the number three so we check at the last element it's more than this so first element is less last element is more so we are sure that if 3 exists at all it should lie here similarly if we had to search for 4 we would have narrowed down to this row because 4 is more than 1 and less than 7 so if 4 exists at all it would win this row only so once we are we found the row we can do binary search simple bind research in this row but here manually we were checking one by one we took this row and so on so we can apply binary search here also so we have this first one last one take the middle compare with that and so on so we will find out a row where first element is less and last element is more so if this is the number of rows is r and number of columns is c then finding the row will take log r time then searching within that row each row will have c elements will take another log c so overall it will be log r plus log c and space it will be o of 1 since we will be using some variables to keep track of the indexes so this will be our approach so let's see how we can do that so we have a few examples it can be true or false 3 was present but here 13 is not present it's empty so nothing will be present so number of rows is matrix not size if it's empty that is r equal to 0 then no point in searching return false then number of columns so now let's find the rows so we will have r1 that is the first row 0 r2 last row that is r minus 1 the index so this is size index will be from 0 one less and then we will use a variable mid so let us better define it here outside so what is the mid row r1 plus r2 minus r1 divided by 2 if matrix mid so we are looking at the mid row and its last element which is c minus 1 so if last element is less than target then everything will be less than target so if this last element let's say we are searching for 25 then we look this is the mid row and we see that 20 is less than 25 so all the elements will be less than 25 in fact all the elements in all the rows above it will be less than 5 so there is no point in searching there so initially our first row pointer r1 was here r2 was here and mid was this one and we were searching for 25 so this 20 is less than 25 so everything above it will be less than 25 and everything to the left of it so we can directly move r1 here one pass to this so r1 equal to mid plus 1. so that is what we will write here what is the other condition else if first element itself is first element if first element itself is more than target then everything to the right of it and below it will be more than target by the same logic that we just saw so no point in searching there onwards so move r2 above that else if none of these condition satisfies then we found the row and we will keep it in r1 so mid is the actual row because none of these conditions satisfy that means uh last element was more than or equal to target and first element was less than or equal to target which is what exactly we are searching for the row that row for that row first element should be less than equal to target last element should be more than equal to target then if target exists at all that will win that row so this is the third condition where we found the target so we can exit from this loop so if even if you don't write it should work but for some cases where if let's say r1 and r2 have a difference of 1 then this mid will always be r1 and this will keep on repeating so that's why this break is important here now at the end of this loop we have the exact row which is in r1 where we have to do the binary search so another binary search so c1 equal to 0 c2 equal to c minus 1. while c1 less than equal to c2 and y equal to because c1 can become equal to c2 and that value might be the target so we have to do one more comparison so c1 c2 becomes equal that does not mean that we did not find we will compare one more time whether that's exactly equal to target or not we can use the same mid variable we don't no longer use it we will only be using r1 because that is the row so r1 is the row we are searching for mid is less than target then c1 equal to mid plus 1 simple binary search else if matrix r 1 mid is more than target then c2 equal to mid minus 1 else if none of these satisfy that means this is exactly equal to target so else return true and if it exits out of this loop that is c1 has become more than c2 that is we did not find it so return false and let's see and the solution is accepted and if we look at the time it's 4 millisecond so 99.61 so that's it's 4 millisecond so 99.61 so that's it's 4 millisecond so 99.61 so that's good we are on the top side so you saw some vertical bars so the most of the time was more than our solution because they may be they may not have optimized for log n plus m or log r plus c log r plus log c now let's do the same in java and we will hardly need to change anything apart from this and the java solution is also accepted and here also we are right on top finally we will do it in python 3 for the sake of completeness so and the python solution is also accepted
|
Search a 2D Matrix
|
search-a-2d-matrix
|
You are given an `m x n` integer matrix `matrix` with the following two properties:
* Each row is sorted in non-decreasing order.
* The first integer of each row is greater than the last integer of the previous row.
Given an integer `target`, return `true` _if_ `target` _is in_ `matrix` _or_ `false` _otherwise_.
You must write a solution in `O(log(m * n))` time complexity.
**Example 1:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 3
**Output:** true
**Example 2:**
**Input:** matrix = \[\[1,3,5,7\],\[10,11,16,20\],\[23,30,34,60\]\], target = 13
**Output:** false
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 100`
* `-104 <= matrix[i][j], target <= 104`
| null |
Array,Binary Search,Matrix
|
Medium
|
240
|
377
|
hey everybody this is Larry this is day nine of the legal day challenge hopefully today's prime is slightly better than yesterday's uh weekly problem uh today's Farm is combo some four let's see which one it is I don't know there's so many of them but uh yeah okay so given the way of this thing integers nums and talking in the Target return to normal possible combinations and we are trying to okay so they're different in uh the older matters yeah the order matters and the answers are in the 32 bits but yeah so we talk about negative numbers afterwards I suppose I don't know if I've done in the past I feel like done this one a few times probably uh yeah I mean this is good I mean the first thing you should do about this is look at the constraints the reason being that uh the reason being that this is uh exponential right this is NP um so you know I mean there are a couple of ways to kind of look at the constraints and think about how to approach it and how to take advantage of the constraints right but given that this is NPO and be complete I always yeah for me I mean I know that I know the nuances behind it but I always forget which farmers and which uh class and for me knowing that as an NP is good enough uh like weather is an MP complete or not you know for it for definitely for competitive it doesn't really matter right um because you have to probably do something else unless for whatever reason it's easy uh okay but yeah there are a couple of ideas here but look at the constraints n is 200 uh the sum of oh not the sum but each number is up to a thousand numbers that bring your interesting and Target is less than a thousand allow us to kind of already figure it out right because uh because then now it allows you to do something we call pseudopinomial which is on the order of the size of the uh the storage size or whatever right meaning that given that this is a thousand you could do something and this is just let's say this is T we can do something like T times n or something like this right um yeah and I think that's all we need to do um right um kind of think in my head whether which way is a little bit cleaner I mean I think it doesn't really matter so yeah so there are a couple of ways you can do it actually to be honest uh but the way that I think the one thing you have to do and that's what I was kind of doing my head which I didn't articulate very well is kind of it the hardest part about these combinations someone is that yeah okay it's for Loops it's maybe recursion we want to do because of me but it actually matters um there's some nuances with respect to um you know whether the order matters or you know and stuff like this right in this particular case the order doesn't matter um so you have to kind of enumerate the problem in that way right because like the first number could be won but it could also be two and then go back to one uh where if the or if this is to go to this and is you go to this as one combination or whatever they call um then that would be a little bit different because then now you're seeking to normalize um or canalgualize the possible input so that you don't double count in this particular problem you can double it's not double count but basically it's as Brute Force as it gets it seems like so we can kind of think about that way so yeah let's start with uh yeah just count with the number of Target left right and then if Target is less than zero uh we just returns zero I don't think we should be able to otherwise we have uh total is equal to zero then total and then it is just as Brute Force as it seems right it's for x and nums uh total we added to count of Target minus X and given that this is unique and I presumably non-zero this unique and I presumably non-zero this unique and I presumably non-zero this should you know because this is not until this should always terminate because this always gets small and it's always that this I don't know how this happened what did I even do yeah this should not happen like who needs to drag text drag and drop text I don't know okay in any case um yeah uh and maybe you could even if you're responsible you can do something like this uh the reason the difference between this and this is just given how you want to do the memorization uh if you want to use the in library or yeah in standard Library memorization uh you actually could be a little bit sloppy with respect to you know uh because negative one and negative two are technically two different inputs and you will recalculate for both of them or as you may at least store two Stone in two places if you're not careful but you know just kind of um limits that kind of branching I don't but I mean it doesn't really matter this particular case because we're going to cash mem uh cash manually and yeah and I think that's pretty much the idea this is it let's give it a quick run uh before the memoization so that we can see it everywhere it is wrong because we don't it's always going to return zero because I forgot uh a base case which is to have a Target is exactly zero we can return one right so yeah so this looks good this looks standard um and then now of course we're branching out a lot in every case so the first thing you should do is memorization right uh well I mean maybe that's not the first thing you should do is ask yourself if memoization can possibly solve it and the reason is because Target is going to be going from zero to well the other Target or t maybe uh let's go this t right and so yeah and because the only T input was the complexity right well the time and space complexity so total time is going to be you go to a number of inputs times time per input and so the number of inputs is as we get from here it's going to be this o of T number of inputs and for each input we do it takes o of n time because of this for Loop right and of course each input also does all of one space because you're just only storing down a number and so total time is equal to of T times R of n which is of course both and T and of course this is pseudo polynomials because uh n is well just a polynomial part and the t is the pseudo part and then Total Space is obviously all of T times o of one if you want to write it out and yeah and that's basically the idea and now we know that this is going to be fast enough we could we should try to clash it of course you probably should do you actually even do that even earlier because otherwise you won't all this stuff enough no reason but I don't know and yeah so if it's not that then it has cash of Target then return cash of Target otherwise right and for funsies we should probably stress test this a little bit um so the worst case is probably going to be Target as you go a thousand and we have 200 numbers so maybe I'm a little bit lazy on the stress test because I'm not going to write that much but let's do at least 20 right oh dancing okay so well so we already overwhelmed the thing so uh I don't know that's at least get something to say okay that's actually a pretty big number but yeah uh let's give a quick summary and there we go 12 57 day streak uh we already did the complex and everything and yeah that's pretty Gucci uh what did I do last time I guess I did exactly the same last time how long has it been it's been a year and change time flies when you're not having fun and even this one and that was two years ago I guess you know at a certain point I suppose I uh I pretty much you know I don't know anyway that's what I have for today's Forum apparently I do the same thing now maybe I gotta end my streak this streak is getting pointless if we're just gonna do Palms that I've already done so I don't know anyway that's all I have today let me know what you think and yeah stay good stay healthy to good mental health I'll see y'all later and take care bye
|
Combination Sum IV
|
combination-sum-iv
|
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`.
The test cases are generated so that the answer can fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\], target = 4
**Output:** 7
**Explanation:**
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
**Example 2:**
**Input:** nums = \[9\], target = 3
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 1000`
* All the elements of `nums` are **unique**.
* `1 <= target <= 1000`
**Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
| null |
Array,Dynamic Programming
|
Medium
|
39
|
139
|
Came in welcome to line repeat saturday will be looking and 10 this is absolutely challenge the name of the problem is border one this is a common problem which has been around product companies cylinder problem shatter given in this edition award containing laptop not limited to Manifest in this sentence Pet Saaf Mana Mode Own Words Se Building Dish May Be Used Multiple Times Administration and Management Department and Difficult Words Yesterday Morning Example S Given Her Sleep Code We The Distance of Living Legend Code Word Sorry Sentence with Word List Code Can Be Accepted S Lead And Code Word Present In The Dictionary Slave To Return Gift Play Store Play Services This Example And See How Can Build A Logic Write The World Disney World And Share And Subscribe To Like Yes Uday Singh Will Be Built At Samsung Electronics First Character and healthcare sector 19 me balance present in different tenses consulting data is my singh us consisting of only two characters 800 olx in this present in the dictionary dainik amar singh is consisting of 19 free characters that in this and check weather app itself from former chief Will be only and repeat from this written state to singer preventive medicine rate on giving literature value welcome half confirmed 10 and a formality quality and can form a yo ruby business where correct word set yo ruby business where correct word set yo ruby business where correct word set Dhol Singh clearly flat for rent in Delhi are Little Boys Pendant and V LED TV Mukesh I am on this very occasion trying to two years were trying to divide this whole problem of string into this problem Balbir Singh data is my Singh and 151 length and in this singh12 inspector Nirmal Singh weight real character half velvet singh In the dictionary's in the string into semis after crushing 67 per cent in the dictionary and share all say can have all 's comedy cid officer one thing and again past this again on 's comedy cid officer one thing and again past this again on 's comedy cid officer one thing and again past this again on purpose belt combination sweet sister per off two cigarettes can be multiple singh shift Distic under content and journalists have been a proper segment world rate 108 inch point any picture puzzles present tense f-18 ok thank you brings into it's there any f-18 ok thank you brings into it's there any f-18 ok thank you brings into it's there any to conservatism deputy director nbt and person electronic store nfc turn on this problem share And Subscribe Our Divided Into Vyeti Subscribe And Journalists Don't Forget To Subscribe And Subscribe That Shahjahan Now Belt Singh Dictionary Or Not And Can Take Dar Pad Media Report Was Not Valid Singh Dhindsa Cancer Welcome My Favorite Festival To The Next Particular Segmentation Print Only For Delhi Chief Security first subscribe like this problem in undhiyu subscribe and subscribe the members record on logic fifth guidance city doing same calling function and choice hotspot of the word dictionary 3D music has it researching sinha acid is open operation head Secretary Indra Singh List Because No Problem The World Service Provider of Lists Converted Into Yes Set The Museum The Amazing Hai Switzerland Are and Standard 10 Welcome to the Spot Letter Writing Salisbury Amazon Also Called Divya Dah-Si Hai So Examples of How to Create Loot Siddha String Sign in to Go to Itch Nagari Characters and Android Software Doing Hair Fall on Every Character Not Bringing Into a Divided Into Problems of Your Character subscribe and subscribe the Channel and Share subscribe Fennel Well Drowned Scooby Doo Subscribe in a Reader Volume Most Earlier and the expectation of tiffin of earrings today political strength is present in the word dictionary Kundhe requests for any point of no return journey to the time that is the 80s due to which 98100 follow subscribe and subscribe to subscribe our that you are till zero Android 2019 And Will Increment So And Will Be Now 250 Excited Scholar Name Vittu Okay Nice Against Writing Bittu Effigy In The Previous Quarter Doctor Actress Already Calculated For Two To Channel Ko subscribe to the Video then subscribe to the Page if you liked The Video then subscribe to the A Memo And Satin Text Will Not Be Seen That 34 Points Now This Particular Condition This Week Pet Centering This Particular Condition Dhundhu Versus To The School Thing Again Life In This Use Impact In Terms Of Mind Adhir Veervati Calling Function and Find the Total Complexity Subscribe Do the Length of the List of the Year Subscribe Button Improvement in the Time to Time Galaxy S9 NOS OK Rest Tay Approach Sexual Question is Not for Only Ones Again Converted the List 2ND Year Subscription for the Language of The Year And Subscribe To Prohibited GPS 223 Benefit To Sb [ __ ] Ha To Prohibited GPS 223 Benefit To Sb [ __ ] Ha To Prohibited GPS 223 Benefit To Sb [ __ ] Ha For Anti String Right Anything Can Be Examined And Item Hundred Eleven Assigning * Morning Dp Are Evil Spirits Assigning * Morning Dp Are Evil Spirits Assigning * Morning Dp Are Evil Spirits Weather Dot Index With String Can Be Entered With A Great Source Of Marketing Length From This 0403 Liquid OK let's go for android from plane and see the question list subscribe My eyes Share and subscribe the Channel that this introduction for all the combinations starting from zero till it very difficult word is present in the dictionary OK Software testing show and deposit is not Welcome to the spot liter super fast chatting deposit and testing weather arrest to the part that is J2 I so in it 10 and is currently at this particular and extortion oil this right zero two and its present world images1 solve will and its present in the word dictionary present in the word dictionary present in the word dictionary that newly formed users doing this app and checking the latter part person fix part with this present to not always that was elevated to not to deposit been selected Arghya Singrauli Sirvi 80 Chief 2nd Id for 10 minutes with 105 Video then subscribe to The Amazing 550 subscribe to the page these words list is de lit here complete world AIDS patients 2013 day 123 45678910 water dishes true representative singh candy statement and nobody from one is not present certificate for that a quite me dictionary serving list and that and a To Delete Here To WhatsApp Lite 210 150 Gender Tight List Will Give Me Products Pinpoint I Can Find Words A Pilot Word In This Will Give Falls Mukesh Volume Setting Mail ETC To Again 10 1500 This Point Will Give Me Provide To Give Me To Because In the eyes here right eight this year and inclusion or equal to how did the journey to the point and also like share and the value is equal make him listen loud i20 27 2012 songs result disposition 8th 10th in and loop the gel up height introduction Nagari Combination Middle Age subscribe The Video then subscribe to the Video not Loot Jaan Loot Subscribe Coming From That DP Are Retained Only Regret Mother Quotes Present In The Withdrawal Difficult Loot-Loot Elements Result Date Loot-Loot Elements Result Date Loot-Loot Elements Result Date Ki Aapke Sadish How They can do using to forms and repair a guru can see it or to farrukh for the same scotland improved time complexity of residence years into follow switch of avengers alliance for the in the space complexity is the amazing national defense staff in the region for the thing But this which near times and rate weapons can and space equal to of fuel length Ashwin plus it's quite sms the that maybe word dictionary das Play Services meeting set up again withdrawal that last year sid and definition of life into mam a time Complexity will be a square and in that case show by using set the evening time complexity yes ok and select message code that instructor chapter sudarshan pradesh video various questions please do national comment section and width like button thank you
|
Word Break
|
word-break
|
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\]
**Output:** true
**Explanation:** Return true because "leetcode " can be segmented as "leet code ".
**Example 2:**
**Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\]
**Output:** true
**Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ".
Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** false
**Constraints:**
* `1 <= s.length <= 300`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 20`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**.
| null |
Hash Table,String,Dynamic Programming,Trie,Memoization
|
Medium
|
140
|
1,926
|
hey everybody this is larry this is me going with q2 of the biweekly contest 56 nearest exit from entrance and maze so this is a very straightforward breakfast search farm definitely recommend doing you know being able to solve it because that is going to be on you know interviews is the level that everyone expects so you need to be able to do this the other thing is just figuring out how you want to handle it and there are a couple of ways you can handle it um but for me why did i get two wrong answers actually um i was just sloppy this is a breath first search and huh how do i get two wrong answers we could check the logs later but yeah but you know show larry some support this is a kind of a rough contest hit the like button to subscribe and join me on discord but basically i wonder if it got re oh i know because the first time i did it i didn't know it didn't give a response so i did it again what a silliness but uh but yeah okay so basically this is breakfast search there are a couple ways to handle breakfast search you can do it as rudimentary as possible but the way that i did it is i just transformed the graph and or the maze into something that i can handle in the easier way and by that i just i look at the edges of the maze and i set all the order open spaces to exits and that's why i have d here and then i set the entrance to s and um and that's pretty much it and after that this is just really straightforward by first search you should definitely know you should definitely practice it i of course have it uh i'm i set everything up but i forgot to set this to true to my first time or and my second time which is why i have two wrong answers or too long time limit exceeded so that's basically why um this is going to be linear time where linear is the size of the maze because for each cell you only go up down left right once so you only look at each cell constant number of times so it's going to be linear time and linear space because you have this done uh matrix and also this q for q anyway that's all i have i'll see you later you can watch me sub live during the contest next and i forgot because i am sloppy one of those days okay what a silly mistake um okay up down left right newest okay then no exits what empty cell that is at the borders okay ah i feel so dumb now gave away five minutes you know i knew i was doing it while i was doing it but i forgot okay anyway let's focus larry move on and yeah move on and be smarter okay entrance was entrance okay entrance oh it's been empty cell okay x i feel so dumb on that first one i knew how to do it come on hmm okay no okay let's go newest exit okay so hmm and one two negative one okay did i click it i think i did but now it's graded out and i don't know server issues oh man okay just service origin server issues in general so maybe the scott doesn't even count but okay let's just skip ahead then yeah even this way just in reloading okay let's skip ahead let's look at it even length okay so bob is trying to get them to be eco and alice is trying to get them not to be equal that's really weird no guys judging oh man yeah well okay fine silly mistakes again i knew that one bit oh man wow larry just subscribe yeah thanks for watching thanks for the support hit the like button is a subscriber and join me on discord let me know what you think about this contest and this problem and this explanation i will see you later stay good stay healthy stay cool and good mental health bye
|
Nearest Exit from Entrance in Maze
|
products-price-for-each-store
|
You are given an `m x n` matrix `maze` (**0-indexed**) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where `entrance = [entrancerow, entrancecol]` denotes the row and column of the cell you are initially standing at.
In one step, you can move one cell **up**, **down**, **left**, or **right**. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the **nearest exit** from the `entrance`. An **exit** is defined as an **empty cell** that is at the **border** of the `maze`. The `entrance` **does not count** as an exit.
Return _the **number of steps** in the shortest path from the_ `entrance` _to the nearest exit, or_ `-1` _if no such path exists_.
**Example 1:**
**Input:** maze = \[\[ "+ ", "+ ", ". ", "+ "\],\[ ". ", ". ", ". ", "+ "\],\[ "+ ", "+ ", "+ ", ". "\]\], entrance = \[1,2\]
**Output:** 1
**Explanation:** There are 3 exits in this maze at \[1,0\], \[0,2\], and \[2,3\].
Initially, you are at the entrance cell \[1,2\].
- You can reach \[1,0\] by moving 2 steps left.
- You can reach \[0,2\] by moving 1 step up.
It is impossible to reach \[2,3\] from the entrance.
Thus, the nearest exit is \[0,2\], which is 1 step away.
**Example 2:**
**Input:** maze = \[\[ "+ ", "+ ", "+ "\],\[ ". ", ". ", ". "\],\[ "+ ", "+ ", "+ "\]\], entrance = \[1,0\]
**Output:** 2
**Explanation:** There is 1 exit in this maze at \[1,2\].
\[1,0\] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell \[1,0\].
- You can reach \[1,2\] by moving 2 steps right.
Thus, the nearest exit is \[1,2\], which is 2 steps away.
**Example 3:**
**Input:** maze = \[\[ ". ", "+ "\]\], entrance = \[0,0\]
**Output:** -1
**Explanation:** There are no exits in this maze.
**Constraints:**
* `maze.length == m`
* `maze[i].length == n`
* `1 <= m, n <= 100`
* `maze[i][j]` is either `'.'` or `'+'`.
* `entrance.length == 2`
* `0 <= entrancerow < m`
* `0 <= entrancecol < n`
* `entrance` will always be an empty cell.
| null |
Database
|
Easy
|
1948
|
129
|
hey guys welcome back today we're solving the problem some route to leave numbers we're given the root of a binary tree and this binary tree contains digits running from 0 to 9 only our task is to find the sum of the root to leave numbers like in this case we have this Leaf node 5 and we have a path running from the root all through to the node ending at five like I have highlighted we also have another path running from one all through to the root and down to one like I have violated in blue and finally we have the third part running from the root all through to zero this is the shortest path that we have in this entire binary tree if we consider the first path from the root to the node ending at five we can take all the integer values here and sum them up if we do take all the integers running from the root all the way to the node ending at five we will get four nine five our task is to sum all these integers from the approach to all the leaf nodes in these three and get the actual sum so the first values are four nine and five we can take this add it to 491 can be obtained from the root taking through this path all the way to the leaf node we can do the same for the last part that is four zero once we add the path from the root all through to the end node at four zero we'll get a total sum of 10 26 this is how we'll be Computing the sum from the root the actual root here to the leaf nodes were 0 1 and 5 but now you'll realize that we'll be adding these values the integer values along the path of one of the leaf nodes and we'll be doing this recursively for all the leaf nodes that this tree has so how can we approach this the first thing you need to notice that the value of the root node will always be the first value we will take and we will do this recursively using a pre-order traversal of a binary tree so pre-order traversal of a binary tree so pre-order traversal of a binary tree so we'll process the first node the root node and then go to its left child and we'll try to do this until we reach the first Leaf node to the left before going to the right so if we do this we will take the four here and then we will go to its direct left child and it is a nine so how do we add this 9 to this four we want to add this 9 to the right of this form how can we do so we will maintain a value called a path sum and by default this will be zero as we start from the root what we'll be doing with this platform is that for every single level that we Traverse in this tree we'll be multiplying it by 10 before we add the value that we want to check so by default it will be zero so zero will represent this the first layer in this binary tree when we reach this layer of this binary tree we will take whatever the path sum will be multiply by 10 and add the Remain the root node at that given level we will start by zero and when we reach to this node with a value name we'll take the path sum multiply it by 10 and add the value 4 to it so that will represent our layer at this given point we'll also check the 9 and we will try to see does it have a left child and will Traverse its entire left side of the tree so when we go to this level when we approach the node with the value 5 again we'll take whatever the path sum will be so in this case it will be 4 because this will just equal to 4 we'll take whatever value the path sum is multiply it by 10 again and then add this 5. so when we do this the math will look like this so when we compute these values you can see we'll be multiplying by 10 before adding the value that we are visiting so at this given position with the value 5 we'll take whatever we did we had 49 multiply by 10 that will give us a 490 and then we can add the 5. now when we add this 5 it will just be added to this right hand side of the zero so it will be added to the zero and that will give us 495 and you can see if we take all the integer values from the root of these three down through this path up to the leaf with a node of five it will just be four nine five we'll repeat the same process for all the other nodes they know that this point and that is how we'll be achieving the 1026 value path sum that we had so this part these are the path and this part the total of these to three parts will result in 10 26. now let's cut this like I said we'll be doing this recursively and I like to define a nested function to help me with this so it's pretty simple it's a DFS such that you're traversing within this entire binary tree so I'll just Define a DFS function here and our function will just take the node that we are currently visiting and the actual path sum up to this given point first base case you need to check is if the node is null and if that's the case we can simply return 0 because there is no value here now remember we've said that we want to add the value at this given node to the pattern but before we do so we need to multiply this path from by 10 so we can just say that path sum will be multiplied by 10 and we'll save the result into the path sum and now we can just add to this pattern the node dot value after this we need to check is this node a leaf node does it have the left and the right children so if it doesn't have the left and the right children you can just simply return the path sum so just check if not node dot left and not DOT rate in this case we can just simply return the pattern otherwise we'll do the recursive part of this function and we'll just be calling the node.left passing through the path the node.left passing through the path the node.left passing through the path sum as our current path and we'll add to this the DFS the node.right the node.right the node.right with the path sum now whatever this returns we can simply return it as our value and the only thing that remains is to call our DFS and we'll just return whatever it returns so the main node that will be passing to this DFS call is the root node and the default value that will be passing as our path sum is zero just like we discussed in the drawing now let's run this and as you can see it works and it's very efficient to enjoy this session please like And subscribe for more content just like this and I'll see you in the next one
|
Sum Root to Leaf Numbers
|
sum-root-to-leaf-numbers
|
You are given the `root` of a binary tree containing digits from `0` to `9` only.
Each root-to-leaf path in the tree represents a number.
* For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`.
Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer.
A **leaf** node is a node with no children.
**Example 1:**
**Input:** root = \[1,2,3\]
**Output:** 25
**Explanation:**
The root-to-leaf path `1->2` represents the number `12`.
The root-to-leaf path `1->3` represents the number `13`.
Therefore, sum = 12 + 13 = `25`.
**Example 2:**
**Input:** root = \[4,9,0,5,1\]
**Output:** 1026
**Explanation:**
The root-to-leaf path `4->9->5` represents the number 495.
The root-to-leaf path `4->9->1` represents the number 491.
The root-to-leaf path `4->0` represents the number 40.
Therefore, sum = 495 + 491 + 40 = `1026`.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `0 <= Node.val <= 9`
* The depth of the tree will not exceed `10`.
| null |
Tree,Depth-First Search,Binary Tree
|
Medium
|
112,124,1030
|
24
|
Ko Ek Hello Guys Welcome Parivartan Se Aapne Subscribe And It's Not Removed It's Not Modified Subscribe To Hain To In Forces Loot-Loot subscribe In Forces Loot-Loot subscribe In Forces Loot-Loot subscribe Video subscribe The Video then subscribe to subscribe and subscribe the Channel that will update the future point of second Next to fourth half minute research labs subscribe then skin subscribe and subscribe this Video plz subscribe ki appointed person ki end safe banal point sunao vikram swabs pendant widow queen money loot subscribe Video ko subscribe to ki and the next of the mid point To The Doctor That No Recursive Function At All The Amazing Spider-Man 2 E Agree With You Will Be In The Immediate Next Will Return Servi Media Award In Maths Of Note All Pure References Of Note Amazon Also That Van Wyck Simply Written And You Can Correct Condition Chapter Note 4 Find The Most Will Not Next That Nau Will Define The Second Remedy Not For Subscribe To That Nau Give Only President Null Medium Flame Per Logic Middle School Civil Services * Exactly Subscribe To Services * Exactly Subscribe To Services * Exactly Subscribe To That Sister Updating Node Daughter At 2102 First Dot Research can be done next this lineage garden shopping 251 adheen on the reference subscribe absolutely dream under adheen do this temple end scored here come tablet swift on road number of notes set alarm bring to front time the to a saturday submitted successfully country approach her time Complexity of over in the us the complexities of space Video then subscribe to subscribe our ka note which will be id m id its will remove the doctor will take its logical reasoning subscribe now to receive that now institute of calling same function again minute or dead value With pointers first comment here half to add 1992 video channel subscribe to select time from this side whatsapp meet space complexity in this case victim of wave all time complexity will be off world channel subscribe to ajay ko
|
Swap Nodes in Pairs
|
swap-nodes-in-pairs
|
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
**Example 1:**
**Input:** head = \[1,2,3,4\]
**Output:** \[2,1,4,3\]
**Example 2:**
**Input:** head = \[\]
**Output:** \[\]
**Example 3:**
**Input:** head = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 100]`.
* `0 <= Node.val <= 100`
| null |
Linked List,Recursion
|
Medium
|
25,528
|
446
|
welcome to september's leeco challenge today's problem is arithmetic slices 2 subsequence given an integer array nums we turn the number of all arithmetic subsequences of nums a sequence of numbers is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same for example one three five seven nine seven all these are arithmetic sequences because the differences are all going to be the same here this is 2 this is 0. here 1 2 5 7 is not an arithmetic sequence essentially because there's no real pattern yeah so subsequence is of an array is a sequence that can be formed by removing some elements possibly none of the arrays so 2510 is going to be a subsequence of this sub right here you can see it right here two 510 and you can actually find another 1 2 5 10 as well okay so we can certainly try to go the recursive route and just do a debt first search and check every single path that we can take for our subsequence but that was my first approach and it hit a time limit exception and it's because it's just exponential it's gonna be two to the nth power now looking at the length of the nums we see that's a thousand so i think we can make the assumption that we wanna go for an n squared solution here so let's go straight in and see what the algorithm looks like say that we had this example here um normally recall questions like the longest increasing subsequence what we want to do is check every single sub not sub array but sub sequences available to us by using an ending pointer a pointer that's going to point to the ending index and the pointer that points to the start index so what i mean by that is if we had an i is going to equal the ending index and j checking every single index that comes before that so if we started with i here there's no js before this so this is going to be nothing but we had i here then we want to check every single j that comes before like this we'll come here we want to check jf2 and jf4 so on and so forth and normally usually we have a dp solution we have some sort of array that's going to store information right but with this one we have to store more than just one thing with longest increasing subsequence we just wanted to like store what was the total number but we also need to remember that it's possible we have different differences that come from before so what we'll do is instead of just an integer inside these values we're going to have some sort of dictionary that's going to keep track of the difference as well as the number that came before that so with this example we'll have i starting at index one and we're gonna check before that what's the difference between four or minus two that's gonna be two right so we know at least there's going to be a value of two um one subsequence here with a difference of two now let's check to index two here uh first we're gonna check six minus two that's gonna be four right so that's four uh but what about two here there's also six minus four that's two but we can see that two als at that at this index we also had a difference of two here so why don't we start accumulating we'll carry over whatever values in here and we'll add one because we know at this point we have at least one more subsequence that we can add to this difference of two right so this would be two and one plus two so this would be two and now we just continue this algorithm down all the way and what this is going to do is tell us how many subsequences of length two do we have with these difference of values so if we like summed up everything at the very end of all these values that would give us the list of the total number of subsequences with a length of two inside of our array right but that's not good enough because we have to remember there's only three has to be at least three elements uh so to avoid that what we'll do is only add to our total what comes from before so like here uh at 10 we're only gonna add the numbers that come from before that way we don't we have we can ensure that it's going to be at least a length of three so now let's just start coding this out and hopefully we'll begin to make sense uh first thing let's get initialized length of nums and we want to create some sort of lookup our dp array this will be an array with a default dict integers for blank and range of n right now we also want to have our output which starts with zero so we're going to do is say 4 i this is going to be the ending index in range of n let's check all the starting indexes so for j and range of i so this will be our start index and this will allow us not to make sure we're checking the same index here so what are we doing we want to first calculate the diff between the nums of i which is the ending index and the nums of j so this is going to be the difference now to our dp array let's calculate the dp of i this is the ending index this is going to equal to well whatever this difference is we're going to add at least one but remember we want to accumulate here so this would be dp of the j that we're checking if there's a value of the difference before that then we're going to start accumulating like this now finally to avoid checking only lengths of two subsequences what we'll do is whatever value is here we're going to add that to our output and i realize that's confusing but you could certainly sum up the values and actually subtract the n times n minus 1 divided by 2. you can do that as well but this just seems a lot cleaner so let's see what this looks like and that looks like it's working i'm going to also print out the dp array just to kind of show what it looks like here so you can see we have a bunch of dictionaries on order and each one of these essentially accumulates the number of subsequences that we've seen with this same value so with this example we'll be adding once we get here we see that 2 right we're going to add 1 first then we get here we're going to add 2 and then we get here we add 3 so that's total 6. now as for 4 we get 4 there's a length of 2 here but here there's actually no four this gets carried over because we're checking for it but it's just it's actually not there once before increases two then we add the one so that's gonna be seven so that's it like this is the entire algorithm and let's go and submit this and there we go so time complexity is n squared space complexity is also n squared so i should admit that i did not come up with the solution it looks really easy and it's very simple but i think coming up with this is actually very difficult i tried a lot of variations of this i knew we had to do some sort of dp solution but i was trying to carry over a lot of things and just wasn't working out once i saw one of the solutions i realized this is very clever but it's also very difficult to come up with on the spot uh what can we do i guess we just have to continue and believe you know if these questions ever got too easy then that means you're not learning anything right so thanks for watching my channel remember do not trust me i know nothing
|
Arithmetic Slices II - Subsequence
|
arithmetic-slices-ii-subsequence
|
Given an integer array `nums`, return _the number of all the **arithmetic subsequences** of_ `nums`.
A sequence of numbers is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same.
* For example, `[1, 3, 5, 7, 9]`, `[7, 7, 7, 7]`, and `[3, -1, -5, -9]` are arithmetic sequences.
* For example, `[1, 1, 2, 5, 7]` is not an arithmetic sequence.
A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
* For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`.
The test cases are generated so that the answer fits in **32-bit** integer.
**Example 1:**
**Input:** nums = \[2,4,6,8,10\]
**Output:** 7
**Explanation:** All arithmetic subsequence slices are:
\[2,4,6\]
\[4,6,8\]
\[6,8,10\]
\[2,4,6,8\]
\[4,6,8,10\]
\[2,4,6,8,10\]
\[2,6,10\]
**Example 2:**
**Input:** nums = \[7,7,7,7,7\]
**Output:** 16
**Explanation:** Any subsequence of this array is arithmetic.
**Constraints:**
* `1 <= nums.length <= 1000`
* `-231 <= nums[i] <= 231 - 1`
| null |
Array,Dynamic Programming
|
Hard
|
413
|
198
|
hello everybody and welcome back to another video today we're going to be taking a look at leak code number 198 known as House robber now this is actually a very popular problem that's assed a lot of companies some of these companies include Google Amazon Adobe and many more now an important thing to note is a few years ago this problem was actually an easy problem but nowadays is marked as a medium problem regardless of the difficulty one of the reasons why I like this problem so much is because I feel it's a great introduction into dynamic programming the problem itself is pretty straightforward so hopefully by the end of the video you'll have a better understanding of dynamic programming in any case let's look at what the problem is asking us to do so essentially we're given an array called nums which contains houses each index is a house and in these houses we have some monetary value or money stashed and our goal as a House robber is to well rob houses and so initially you might be thinking well if you want to maximize the amount of money we can steal why not just Rob all the houses well that's where the problems constraint comes in you see if you rob a house let's just say the first one right here you cannot Rob the neighboring house and the reason for this is because if you do that if you rob a house and then Rob the house right next to it you will trigger an alarm which contacts the police so in order to avoid arousing suspicion if you rob a house then you cannot Rob the next one so if you want to Rob another house you'll have to rob the house two doors down in this case three so again starting with our first house if we rob this one then we cannot Rob this one instead we would have to Rob this one as our next house but here's the thing if we're looking at our first house we can always make the choice not to rob it instead we can move to the next house right here and Rob that one instead again the same rules apply if we rob this one then we cannot Rob three so then next we could Rob this notice how this problem basically boils down to two decisions we either choose to rob a house or we skip it and that's really important to understand because at every house we stop at we can either make one of those two choices so to help you understand this let's draw a decision tree for this problem so if we start at the first index and make the choice to rob it that sets us down a path so we rob this house for one now what else can we do well we've robbed this house so we cannot Rob the next one we'd have to look over here robbing this house Nets us three so we would net three but here's the interesting thing I didn't mention this before but if we decide to rob this one we don't have to just Rob this one we can also choose to Rob this one because remember at every house that we can rob we can either choose to rob it or not to rob it so starting from here obviously we cannot Rob this one because we've set off the alarm so that leaves us these two so we can either choose to Rob this one or we can actually choose to Rob this one and so that splits our decision tree because from one we can either go to three or we can rob the house at index three to net us another one so then we can break off and net one but now bringing it back to the beginning remember we start here but we don't have to Rob this we can start by robbing this house so then that leads to another path on our decision tree so we can go rob this house for two now from here if we decide to rob this house for two we can never Rob this one because they're right next to each other so the only choice is from here we can either choose to Rob this house or not in this case let's say we do rob it which in that case will add to our decision tree so then from two we can net one so just looking at her problem and adding everything up if we go right here we can get a Max of four if we come right here we can get a Max of two and then if we add all this up we can get a Max of three and so looking at all these different decisions that we can make essentially all the different houses that we can rob then it's pretty clear to see which is the most optimal if we want to make the most money then we need to rob the first house at index zero and the house at index 2 1 + 3 = 4 zero and the house at index 2 1 + 3 = 4 zero and the house at index 2 1 + 3 = 4 which as you can see is the max amount that we can get and coincides with the output of the first example now right now this is a pretty simplistic example but imagine if our nums areay had more houses so let's add a few more on the end here so by adding three more houses this whole decision tree will look a lot more complex in fact one of the issues with this approach is that we'll be doing a lot of repeat work because if it wasn't clear this whole decision tree is what a recursive solution would look like now the thing with recursion is that we are exploring every combination of house that we can rob within our nums array but invariably we will introduce a lot of repeat work we will recalculate a lot of sub problems and sub problems are really what I want to focus on here because remember at every house in our array we have two decisions we can either Rob or not Rob those are two choices and so with our recursive Brute Force solution we're exploring the paths that can lead to the maximum amount of loot that we can take from these houses so by calculating all the possibilities of houses that we can Rob and not Rob we'll eventually find the solution the thing is we can make our solution a lot more efficient if we didn't do any repeat work or at least cut back on it as much as possible so how can we do that well that's where dynamic programming comes in you see dynamic programming is a way for us to calculate the optimal solution to a problem by the sum of its sub problems so in our case if we want to calculate the max amount of loot that we can steal from these houses then at each step we can either rob a house or skip it and the thing here is we can use past sub problems to help us with our decision at the current house and that's the beauty of dynamic programming we don't have to go down a bunch of paths and repeat a bunch of work because we can just look at our past Solutions or the past sub problems that we solved to calculate our current solution let me erase everything I have so far and then we can see how a dynamic programming solution would work with our example all right so how would this look if we use dynamic programming well again remember if we start at our first house right here we can either choose to rob it or not rob it so in our case let's just say we do rob it which would mean up until this point so at this house the maximum amount that we can possibly Rob is one because this is the only house that we Rob so far but remember we always have the option of not robbing this house so let's say instead we chose to skip this house and look to this one so the second house will give us a value of two so if we rob that one then we will have two but if we choose to Rob this house we cannot Rob this one remember we cannot Rob adjacent houses so to help you understand let me draw these lines right here and so what I'm trying to represent with these lines right here is up until this point the max amount that we can get is one because we're only robbing one house up until this point we have two houses so we either choose to Rob this one and skip that one or we can skip this one and Rob this one instead so up until this point the maximum amount that we can rob from these two houses is obviously two so now if we look at the third house here which has a value of three remember we have two choices either we can rob it or not rob it but remember since we're using dynamic programming we have to calculate the max amount of loot that we can get up until this point which will give us three now if we do Rob this house that implicitly means that we didn't Rob this one because again we cannot rob houses that are adjacent to each other so if we rob this one then that implies that we've already robbed this one so then that would mean it would be 3 + 1 then that would mean it would be 3 + 1 then that would mean it would be 3 + 1 which equals four because if we rob this one we cannot also get the two from here we would have to get the one from over here because these houses are not next to each other or we can say we're going to skip this house and just go with the maximum value up until that point so the maximum value between these two is two so in looking at this house we have two choices we can either accept two or we can do 3 + 1 now obviously looking at can do 3 + 1 now obviously looking at can do 3 + 1 now obviously looking at this four is greater than two and so the max amount that we can possibly Rob up until this point is four all right and finally we come to our final house which has a value of one so again we can either choose to rob it or skip it in the event that we choose to rob it that means that we cannot get the value from this index because the houses are right next to each other so that means should we choose to Rob this house then that means we can choose the maximum amount of loot that we robbed from these two houses now obviously between these two houses two is the greater number so that means our calculation would be 1 + 2 = 3 means our calculation would be 1 + 2 = 3 means our calculation would be 1 + 2 = 3 and just for clarification this one is referring to this one not this one so if we choose to Rob this house we can look at our past values of the houses that we robbed up until this point because we cannot Rob adjacent houses so between these two houses that we robbed this one yields the most amount of money so obviously we're going to want to go with this one which is how we get three so again up until this point if we choose to Rob this house the maximum amount that we can rob in total would be 1 + 2 that we can rob in total would be 1 + 2 that we can rob in total would be 1 + 2 for a total of three otherwise if we choose to skip this house that means we can just pull over the number that we have here because this is the maximum amount that we've robbed so far and of course the maximum amount of four is greater than three which means up until this point in our nums array four is the maximum amount that we can rob from all these houses and this is essentially dynamic programming and action notice how all this doesn't need to be stored in an auxiliary array we can just incrementally build up our answer and then just look at past answers to determine our decision at the current house now before we jump in the code I want to calculate the runtime and space complexity so our runtime is going to be o of N and the reason for this is because since we're looking at past data to per our current decision we can actually do this entire problem in one pass and so because of that we'll be looking at upwards of n items hence why we have a runtime of O of n now I will say that we will be making use of the max function so max essentially just Compares two numbers and then Returns the maximum value but that has a constant time complexity so that doesn't really hinder our runtime in anyway so the final runtime is just o of N and then our space complexity is going to be o of one or constant time and the reason for this is just simply because we don't have any auxilary data structures again this problem is done just using the information we have in the array and just incrementally building up our answer until we arrive at the final solution so it's not necessary to use a data structure for this problem although there are solutions that do make use of a data structure ours isn't using one all right so now let's jump into the code all right so the first thing we have to do is initialize two variables remember the current house that we're looking at is made by looking at previous data so when looking at a house we can either choose to get the max value of the previous house that wasn't robbed or get the max value of the previous house that was robbed and so the way we can denote that is just by simply having two variables called preve No Rob and preve robbed and these will both start at zero because when we start out obviously we haven't robbed anything so they'll just be zero so to recap this variable means the max amount of the previous house that wasn't robbed and this one means the max amount of the previous house that was robbed now that we have our two variables we can use those variables to incrementally build up to our final solution so all we have to do now is just iterate through our nums array so we can start with four Cur house value in nums and so one of the first considerations we want to make is to get the max of either PR no Rob or pre Rob because we always want to keep track of the max amount that we have robbed up to that point and so we can get that information by checking the max value between pre no Rob and pre- Rob so for now we can just Rob and pre- Rob so for now we can just Rob and pre- Rob so for now we can just store this in a temp variable and calculate the max between the two variables preve no Rob and preve Rob so 10 temp will always hold the max value up until that point up until our current house that we're looking at so once we have that information we can update our variables so we can continue the process as we move through our array so first let's update pre robed which is simply updated to the sum of preve no Rob plus the current house value this is because we can only Rob the current house if the previous one was not robbed so this is how we update this variable and then finally we have to update preve no Rob and so this will store the temp variable that we calculated up here which again the purpose of this temp variable is to track the maximum amount that we can get by either robbing house or not robbing in because if we choose not to rob the current house that we're looking at then the maximum amount is either the best of either not robbing the previous house or robbing it so now that we have both of these updated this Loop will just continue until we reach the end of our nums array at which point we can break out of this for Loop and then return the max of preve no Rob or preve robbed so again the last check here is really just to make sure that we're getting the max value between these two variables so after everything's said and done we will have our final answer so let me run the solution to see if it works all right so that's going to do it for this video hope you guys learned a lot and I really hope dynamic programming makes more sense to you now in any case I have a lot more coding videos like this so check those out if you haven't and I'll see you guys in the next video
|
House Robber
|
house-robber
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 2:**
**Input:** nums = \[2,7,9,3,1\]
**Output:** 12
**Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 400`
| null |
Array,Dynamic Programming
|
Medium
|
152,213,256,276,337,600,656,740,2262
|
1,784
|
that won't start with zero and then we have to attempt to i guess yes contains at most one contiguous segment of ones and this means contiguous blues one should i cure continuously and that should be one continuous segment opens so here are two continuous setup also uh so we will return falsies uh in example two uh yes equal to one ten i here first character is one and second guy just one this is continuous and next we need zero uh the continuation breaks and this is a one continuous element according to the statement we want to control yes contain at most one continuous second one here only uh one continuous segment of all circuits so we were done true let's go into the coding part first we have to create two million individuals name you can name it as a find one's equal to house and we have to find the job and job basically means uh when we find a one on the next two and next to it i finished zero i cures uh that is a job uh so we need to stop to false uh then we have to i trade through the string so we go with power lock hey uh now we are going to extract that if yes oh no we are fighting and i can't have zero undefined and if any character you know and we are already finding the cat and means find one will become true or yes if um you find one if you already found the uh one character and then find one becomes true so we will take the final condition and then we will make the gap equal to true and then we are going to do and here if any element is and if the character is one and the gap this also move means we are already found at a one and a zero and that means one continuous second of ones that are already accurate then again we found the uh continuous segment of once that is uh if i guess not then we will a little false because uh this condition satisfiable uh one continuous segment of ones are already like yours and another character is one that means a more than one continuous segment like this so here so we will return pulse then finally we i trade through the loop and if we don't find any gap and only one continuous element then we will return true y'all uh yeah it's accepted we'll submit it yeah it says accepted um if you find this solution on video please subscribe and thank you
|
Check if Binary String Has at Most One Segment of Ones
|
minimum-initial-energy-to-finish-tasks
|
Given a binary string `s` **without leading zeros**, return `true` _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.
**Example 1:**
**Input:** s = "1001 "
**Output:** false
**Explanation:** The ones do not form a contiguous segment.
**Example 2:**
**Input:** s = "110 "
**Output:** true
**Constraints:**
* `1 <= s.length <= 100`
* `s[i]` is either `'0'` or `'1'`.
* `s[0]` is `'1'`.
|
We can easily figure that the f(x) : does x solve this array is monotonic so binary Search is doable Figure a sorting pattern
|
Array,Greedy,Sorting
|
Hard
| null |
1,431
|
Question Bhai Kids start with the greatest number of Candice. Let's see what he is saying. Bhai, Candies is okay. Brother, every number in which there will be number of Candice will be revised. After cricket, it is okay brother, that is, two. What is three punch, one three, candies, okay, this is on zero, this is on child, this is on first, this is on second, by doing this, another interior will be given, okay, no problem, we have to return one quote, okay, true or false key. But each element will represent rectangle kid okay what is this true what is zero this is the first kidding like this okay but will represent true and false when I will give to the extras okay and after giving those extras to Candice she The child will have the maximum number of candies. Give it to the first one, brother, the punch is done. Okay, so it has to be seen whether the punch is the maximum or not. There is one more punch in the punch maximum but it is given here. Note date multiple kids can have the greatest number what does it mean it will be true for the first one okay then I gave it to the second one they have six hands is the maximum so I am sitting here a gone then I gave the punch to the kids with 30 and three eights And the maximum is this, so I have given a hero here, then given three and one, four to the fourth children, if four is not the maximum, then there will be false, three and three, six are the maximum, here, there will be true, this story is simple. It's nothing new, it's a simple question, so brother, what will you do, it's simple, look, take out the maximum from this anime, then add three to each element and see that each element, when I am adding three, is maximum. If it is equal to or greater than that then push the row there otherwise it is false, it is just this little less, there is nothing wrong, okay, so let's take one, wait and max, it will take equal to minus one, okay, very good, then loop. Changed it to 'For' and 'I' good, then loop. Changed it to 'For' and 'I' good, then loop. Changed it to 'For' and 'I' in 'Kiss' and 'Candis', okay brother, and in 'Kiss' and 'Candis', okay brother, and in 'Kiss' and 'Candis', okay brother, and wrote here if I give it a greater max. If the current candy is bigger than max, then update the max. Okay brother, there is nothing else in it. Gaya, max will be gone, now it's okay, Han Bhai, maximum has been gone, now what do we do, let's take a list in which we will keep the answers, she said, there will be a list of types, that's right, her name is RAS, okay, what type is she? Hey, it will be of list type, brother, there is no problem, okay, we will run one more loop, forint eye, we will run it in candies, brother, what was in candies, it is iterating in andes, okay, what is it, that is, one candy, then the other condition, if. I Plus I will return, what is going on, let's run brother, let's see what happens, okay, it has been accepted, okay brother, everything has become very sweet, nothing is very good, time complexity in this question is big of N, we have run a loop and space. What is complexity? Complexity in 1s because we have not taken any extra space, we have taken only juice and it is not counted in auxiliary space because it is for the result
|
Kids With the Greatest Number of Candies
|
all-ancestors-of-a-node-in-a-directed-acyclic-graph
|
There are `n` kids with candies. You are given an integer array `candies`, where each `candies[i]` represents the number of candies the `ith` kid has, and an integer `extraCandies`, denoting the number of extra candies that you have.
Return _a boolean array_ `result` _of length_ `n`_, where_ `result[i]` _is_ `true` _if, after giving the_ `ith` _kid all the_ `extraCandies`_, they will have the **greatest** number of candies among all the kids__, or_ `false` _otherwise_.
Note that **multiple** kids can have the **greatest** number of candies.
**Example 1:**
**Input:** candies = \[2,3,5,1,3\], extraCandies = 3
**Output:** \[true,true,true,false,true\]
**Explanation:** If you give all extraCandies to:
- Kid 1, they will have 2 + 3 = 5 candies, which is the greatest among the kids.
- Kid 2, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
- Kid 3, they will have 5 + 3 = 8 candies, which is the greatest among the kids.
- Kid 4, they will have 1 + 3 = 4 candies, which is not the greatest among the kids.
- Kid 5, they will have 3 + 3 = 6 candies, which is the greatest among the kids.
**Example 2:**
**Input:** candies = \[4,2,1,1,2\], extraCandies = 1
**Output:** \[true,false,false,false,false\]
**Explanation:** There is only 1 extra candy.
Kid 1 will always have the greatest number of candies, even if a different kid is given the extra candy.
**Example 3:**
**Input:** candies = \[12,1,12\], extraCandies = 10
**Output:** \[true,false,true\]
**Constraints:**
* `n == candies.length`
* `2 <= n <= 100`
* `1 <= candies[i] <= 100`
* `1 <= extraCandies <= 50`
|
Consider how reversing each edge of the graph can help us. How can performing BFS/DFS on the reversed graph help us find the ancestors of every node?
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
1912
|
968
|
welcome to mazelico challenge today's problem is binary tree cameras given a binary tree we install cameras on the nodes of the tree now each camera at a node can monitor its parent itself and its immediate children now calculate the minimum number of cameras needed to monitor all the nodes of the tree so if we have this binary tree right here we can see that obviously we want to put the camera right smack in the middle so that's going to minimize the number of cameras and it's going to cover all the nodes here to be monitored here we can see that the minimum is going to be two cameras two in spec in the middle and that's it now how do we do this so yeah this is not an easy problem and it took me a while to kind of figure this out let's start off by imagining if this was a 1d array and if we had the same problem where the camera could monitor itself the one previous and the one after how would we go about doing something like that so say we had a bunch of indexes like this like we know at the beginning say that we start here would we want to put a camera here and when it's at the edge like the bottom say that this was like a leaf we know that we don't want to put a camera here it'd be much better to put the camera at its parent right so what we can kind of do is mark whenever a note is a leaf so we can call it like n i guess or we'll call it l say if it's a leaf then we know we want to put a camera on top of it's parent okay now if we put a camera on this parent here we kind of know that the next one is going to be monitored by this camera from the beginning right and we have to keep track of that with some sort of bullion or some value we have to keep track of this as we move up in our recursion we know we're probably going to do some sort of that first search recursion but like here we can already tell okay we don't even need to know what comes next we just know that the camera is going to be at the parent and then the next parent is going to be monitored by this camera here now as we move forward though uh what do we want to put here do we want the camera here because it's not this one's not going to be monitored right well technically yes we need needs to be monitored somehow but it wouldn't be very efficient if we just like the camera right it makes more sense to make this one uh monitored by the camera that comes after here right so this is almost as if uh once we say like we have a camera and then we move up then it's monitored then we move up it's almost like this is a new leaf this is like the condition with here it's like almost the same as a leaf so really there's no difference it's like we can just mark this as monitored and then as we move up and said hey if the previous one wasn't the camera we want to mark it with the camera next so right here we can see two cameras right one here at index one and one here at index three four and that's going to cover all our cameras that's gonna be the minimum number now one thing to note there is an edge case though say that we had one thing at the end here like as we move up here we'll say okay this one we're going to monitor with the next camera but we know that there's no more nodes at the end right so we have to kind of check also at the root uh do we um is this one monitor or not because if it's not monitored we actually need to install a camera here and that's gonna be a minimum three okay so that's probably the key thing to understand here we have to have two well three states technically but uh the main thing we wanna check is hey is this a leaf is this um do we wanna install camera here and next one have we already installed the camera and could we um just not have anything to do at this parent node here uh it does get a little bit tricky though because we have to do this on both sides and i'll show you how that's going to be done so the first thing we want to do is create a gold variable i'm just going to start off with zero cameras okay now we want to have our debt for search helper so we'll hold def search and we'll say node and we're going to have two booleans here one for um say camera okay to mark we want to put a camera at this node and one for um well next one's gonna be monitored okay so we'll call it camera monitor uh first thing we have our base case if not node what do we wanna do well we wanna return false for the camera uh obviously we can't put a camera here but we do wanna return a true for the monitor okay because we know that the next one is going to have a camera so this is going to be monitored so uh two things i'm going to start off by having two variables here one for camera and one from one and we want to start the left side so this can be that for search no dot left and this will be for the right side see two and two that for search no dot right side okay so the first thing you want to check to see is um well let's see if either side um let's see if either side is a camera then we're going to mark the monitor as true okay so we'll start off is initialize two variables camera and monitor and these will both start off with false but we'll say like if either side if c1 or c2 has a camera then we're gonna mark monitor as true because that's going to be what we want to pass next up to the parent now if not m1 or not m2 what does that mean that means we have to um put a camera here right because it's not monitored so we're gonna have to put a camera and we'll say camera equals true and therefore we're gonna increase our output by one and we're also gonna mark monitor as true because obviously this has a camera here so it's going to be monitored and we just want to return what our camera and monitor and finally call our deafer search here and then return the self.output return the self.output return the self.output now this would normally work for most cases but remember how that edge case i talked about at that root it's possible that we say oh this is not monitored but we're not going to increase our camera here because it doesn't have any more parents so to take care of that i'm just going to return the value for the monitor here because if uh let's see if not monitor then we actually want to return self.output plus one because we have to self.output plus one because we have to self.output plus one because we have to have a camera here all right so let's see if this works uh okay let's see monitor oh if not m okay so that looks like it's working so submit it and there we go accepted so time complexity it's going to be of n and space complexity we do our recursion here and it's going to have our recursive stack so that actually ends up becoming oven as well uh but that's i don't think that's avoidable we have to do that okay hopefully that explains most of my thought process i haven't gone too deeply into it because there's definitely lots of variations to this uh but i think that's the key thing to understand is you know like one more the condition where you're at the leaf is kind of the same as if it was um the node right after the monitored node with the camera so it always goes monitored camera monitored and then if there's one on top then we want to say monitored camera monitor all the way but we have to do it with both sides because if either or uh one of those is gonna cascade up so okay all right well thanks for watching my channel remember do not trust me i know nothing
|
Binary Tree Cameras
|
beautiful-array
|
You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children.
Return _the minimum number of cameras needed to monitor all nodes of the tree_.
**Example 1:**
**Input:** root = \[0,0,null,0,0\]
**Output:** 1
**Explanation:** One camera is enough to monitor all nodes if placed as shown.
**Example 2:**
**Input:** root = \[0,0,null,0,null,0,null,null,0\]
**Output:** 2
**Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val == 0`
| null |
Array,Math,Divide and Conquer
|
Medium
| null |
870
|
hey everybody this is larry this is day 24 of march nico daily challenge hit the like button to subscribe on drummond discord let me know what you think about this problem offended shovel coming to a razor b of equal size the furniture of a with respect to b is the number of indices i which is returning implementation of maximizing b what does that mean oh so we basically okay um n is ten thousand so i have to do something smarter so i think it's just greedy right uh i mean a lot of bookkeeping but you know given b we basically just match as many as we can um going down this list and it's just a lot of uh keeping track of stuff um but the idea is still greedy right so let's just say we have a sort of b let's say b is sorted you know we can sort and then unsort that's trivial uh you know it's doable maybe it's not trivial but yeah it's doable and then from there you just go down yeah for 32 what's the next number that it could hit 24 what's the next number that you get and so forth i think given that should be okay uh yeah let's do that so basically first we have to um i mean it's a little bit annoying but that's fine so i think are they unique numbers i guess they don't have to be but um oh yeah so we have enumerate b we have index x in here uh what do we want to do now i guess that's fine yeah i think it's just implementation keeping track of stuff so we'll just do bs code to someone like this and then we can sort it right so then b should have uh the number and then the index together but in a way okay yeah so now it's in um in ascending order so we actually want to reverse this to be in uh in descending order and then a we also wanted to sort it because the order doesn't matter or like we don't the original order doesn't matter so we can uh yeah let's do this i guess technically we actually just need to sort it yeah that should be just making sure that compiles because i've always sometimes messed up on the syntax okay um and then now that means that you know we go through the b array uh a array by one no do we now we want hm so basically what we said was that okay here's the 32 and then we find no so okay yeah for each a we want to find the next number so okay so yeah let's just say answer is equal to um whatever negative one to some value times n where n is you go to length of a or i guess it doesn't matter they should be the same and then now you know for x and a so this should be from big order to small order um we let's keep a variable from b pointer is equal to zero while b pointer is less than length of b and x is less than does have to be strictly less than or equal okay it has to be so if it's equal you keep moving as well you go to b or b pointer uh then you have b pointer increment by one otherwise if b pointer is less than length of b that means that this is in the array then we have an answer so we have answer of oh b actually now includes the index as well so this is actually connecting to zero uh and this is actually we want b pointer of one is equal to x someone like that um except for now we want to increment b pointer because we used it um this is not yet done but let's run it real quick uh it should give us a subset of the answers i guess in this one actually maybe it just happens to be working but here i think it doesn't work because we have to um it doesn't match up perfectly yeah so now there's a negative ones here um that's because some numbers in a just never match so if it never finds a match then it really can't just be anywhere so okay um i think actually after this is not true then we just go through the entire way to find them but uh but i think we can actually i'm gonna do it another way where i just keep track of um uh unused is equal to list uh else that means that x is not good for anything then unused.pandavx for anything then unused.pandavx for anything then unused.pandavx um you know when you see me actually i just want to point out that when um yeah when you see me you kind of make these decisions actually i'm just thinking about it and playing around with it just like you might be so i don't necessarily know that this is the best way to do it or there may be other slick ways of doing it but that's the way i'm doing it so yeah um yeah uh and i am solving these lives so yeah i forgot about the disclaimer but yeah you know because people always ask me why i take so long to explain the problem sometimes uh okay so then now we can just do another pointer for um oh yeah for b pointer and range sub n if b if ends of the pointer is you go to negative one i guess this is more like an a pointer fine it's got a pointer then um then uh answer a pointer is you go to unused pop and it doesn't matter which one because it's not bigger than the one that's in b right so that's why you know so i think it will happen to you know in this case because you cannot um you can return any answer so we don't have to you know do anything with the optimization i think this is good um let's give it a submit maybe i've missed the case but hopefully that this is good cool uh yeah and what is the complexity of this well there's two sorting so that's gonna be n log n um and space is gonna be o of n but that's the size of the n server so i think the unused one you don't need it so you if you are smarter about unused you could even reduce this to just all one extra space on top of the return space the question is then can you do this in linear time can you do this without sorting i guess that's the question i don't think so i think you need to be greedy on this sword because imagine you have used the 32 on the 11 then it might be that um you know then you then nothing can beat the 24 right so you have to do that kind of ordering that's my guess but i'm not sure about this one whether there's anything cleverer at least not given that these are ten to nine if they were or not then you may be abused a little bit um let's take a look at the solution i'm just curious whether there's a better solution i'm actually not confident that i did the best complexity and i don't know that i could prove to lower about uh greedy okay that's basically my idea okay so i guess not um yeah and you just have to keep track of i don't know how they're doing they did it much slicker than i did though but the remaining and used is what i did but um actually now this is pretty much how i did it oh assign this hmm oh i guess they assume that the numbers are unique because otherwise this might doesn't make sense maybe oh no they don't they just kind of randomly okay i guess i could see it but uh but yeah uh okay so i guess i do have the optimal answer anyway that's all i have um greedy problems are hard so uh so you have to really the thing that i would say is the same as some other problems is that you just have to practice a lot of greedy problems um because then you get the patterns you get you able to see proofs and you understand you know how numbers and different things work in relation to each other so that you're able to do things without proving it per se so in an interview that's still going to be tough um yeah that's why i have this one let me know what you think hit the like button to subscribe on drum and discord hope you do well hope you have a great week i'll see you later and to good mental health bye
|
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
|
974
|
Hello friends today I'm going to solve with good problem number 974 sub errorisms divisible by K so in this problem we are given an integer array nums and an integer value K we need to return the number of non-empty Subaru return the number of non-empty Subaru return the number of non-empty Subaru that have the sum divisible by K now how can we solve this problem we are given this example let's look at this example here so in this example we know that 4 is not divisible by 5. what about five is divisible by 5 what about 0 is also divisible by 5 and what about minus it's not but what about minus 2 plus minus 0 it is right and how do we know that these are divisible by 5 well basically by calculating the remainder of these sum right so if we take the remainder of 4 that is take the modular operation of four with five what do we get the remainder 4 right what about when we take the modulo of 5 with respect to five of course it's equals to zero because five is divisible by 5. what about zero it's the same case it's divisible right so since we know that we can find the modulo operator at the remainder helps us identify which is uh divisible by 5 and which is not now let's look at we'll actually be using prefix remainder here what this prefix remainder means well what's the remainder of 4 it's 4 right so we have the remainder 4 for index 0. what about index one well remainder of 5 itself is equals to zero so we get the remainder of 5 equals to zero and then we add the remainder 4 to it and the resulting remainder is equals to four now what do we have here we initially had a remainder Z4 now we again have a remainder 4. what does this imply this implies that um any sum between um well the remainder for a previous one was at this Index right and the next remainder we found is at this index so the sub array between index suppose this is I and this is J then the sub array between I plus 1 2G inclusive will be divisible by 5. so this will be divisible by 5 that is the value the remainder will be equal to zero and that's true because if you look at the value 5 only it's divisible right now I plus 1 is equals to 1 um and the J itself is equals to one so this sub array is divisible by five similarly if we take five uh prefix sum of four five and zero that is four plus five plus zero that would still be equals to the previous sum as equals to four previous prefix and then and the remainder of 0 with 5 is equals to zeros at the remainder here is again equals to four so now we have another sub array we found another sub array starting from index I to J and what's the index I where index I here is this index starting from this index so the next sub error is this and we have already found this sub error right so one sub array is 5 download the sub area we found is um zero but we also know five comma zero this is also another sub area which is divisible by five right whose sum is equals uh divisible by five so how can we achieve that well what are we going to do is we are going to use a map so we use a map and we for the remainder full how many times did we encounter it well while we've we're at index 0 we encountered it once when we moved at index 5 we encountered it the next stem right but before updating this value we update our result with the previous value so that is one and then we update this value to 2. in the next step what was the remainder we again found the remainder equals to four and since we found the remainder 4 so what are we going to do is we are going to add this value to our results so 1 plus 2 and then we update this value to be equals to 3 because so far we have encountered three sub arrays which remainder uh three well some areas in the sense like it starts from index 0. so that is what we have done here and what's the result so far so if we look from index 0 1 and 2 for only the first three elements then the result is equals to three and the sub varies are equals to 5 0 and 5 comma zero right so that is what we needed and we have achieved that and for the first three elements and that is what we'll be doing for the remaining of the results so now that we understand how we could solve this problem let's try to code it so what if we need a prefix remainder so let's initialize it to zero first and then we need our result which is initialized to zero we need a map to store the number of the remained as prefix remainders that we encounter so and what do we do is we initialize the values for the map Y is less than k I plus so we are only taking for K because uh this map is for the remainders right and the remainders will range from the value 0 to K minus one so suppose for example in case of five the what are what would the remainder be 16 minus d 16 remainder of 16 is equals to 1 right remainder of uh 28 is equals to um three so remainder of 29 is equals to four remainder of 30 is equal to zero so it never exceeds five so that is y so what we do now is map of index I it's all initialized to zero and what we're also gonna do is we initialize the value of 0 to 1 um if in case we encountered uh sub array which in itself which has a remainder zero and it's from the very first so suppose for example uh if we have a sub array which has um the value minus 2 and minus 3 and suppose the model values here so minus 2 is not divisible by five have a minus 3 sum of minus 2 plus minus 3 which is equals to Minus 5 is divisible right so if you'd not update the remainder 0 if it's not equals to 1 that is if it's equals to zero then our result we add to our result the value 0 and we do not want that we want it to be value upon right one so that is why we uh initialize the map for index 0 to be one so that is what we are going to do here now for each of the values of the nums array we find our prefix remainder so prefix remainder would be calls to prefix remainder plus the initial prefix remainder plus num modulo of K so what are we doing here is this thing so we take the previous prefix remainder that is a remainder of 4 and then we take the remainder of uh the current value which is five modulus 5 which is equals to zero and then we get our new prefix value so that is what we do here but here we are also going to add plus K in order to eliminate any uh negative values that we might get from these uh evaluation so plus K would result in a positive value and then we take the modulo again and we update our result to the value of prefix so this number of pre um number of times we have encountered this prefix previously and then we obtained our prefix remainder by one and then finally we are going to return our result let's run our code great let's submit it so the time complexity here is of n because we are just doing a linear iteration over the nums array just once and the space complexity is of K because we are um creating a map of Max size equals to K right so that's the final answer
|
Subarray Sums Divisible by K
|
reorder-data-in-log-files
|
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible by k = 5:
\[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\]
**Example 2:**
**Input:** nums = \[5\], k = 9
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `2 <= k <= 104`
| null |
Array,String,Sorting
|
Easy
| null |
377
|
The The The next question we're going to look at is combinations on distinct integers and a target interior target return D number of possible combinations come up tu target dance Okay so what we've done is tell us the number of combinations to make a four. How many combinations do we have, 1, 2 and three numbers? Here they have listed them and shown them as one two one three. So one thing is to be noted here also, then this combination is written as 211. Even though we are writing this, we don't have to list it, how many ways are there to solve it, how to make it, ok, we will put one inside zero, if minus is one, then we will add one, if minus is three, then leave it -1. Here it is written 'A', now look on our phone, let's see 4 minus one three working, this answer is 'A' but 'A', then is 'A' but 'A', then is 'A' but 'A', then we saw that if the last number is one, then in how many ways can we make one, then one Mines One Zero can be made in how many ways, it cannot be made, how many ways one can be made for free, if you watch it for free, you will understand a little clearly, after all, if we do it, then in how many ways can we make it for free, in how many ways can we People can make one there, at the end you can make it in two ways, so only one way, your four then minus three, all the ways of making one, that is only one way, write it in its class, your three becomes four again. So there are these 7 ways, we will make four, we will complete it in this way and we will return whatever is the last value, there will be same number of ways to make the last number, we will create a target, let's code it and see in a DB. Let's create an era named Era and size it. First we will check that if I is the minus of the greater, then it is equal to zero. If we do not consider it is equal to zero. Then the rectangle location of DP. If we have all the test cases, then in DP. You see one thing carefully that whenever we are asking any question of DP, we are storing at every level what is the answer there, like in this also we have to give the target answer but we are also storing it at one level. There are so many ways to make a forest, we are doing it on tube also, we are doing it on three, we are doing it on four because in future, we are getting less results, this is called memorization and in DP, we are not using it but we are also using concepts. Are
|
Combination Sum IV
|
combination-sum-iv
|
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`.
The test cases are generated so that the answer can fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\], target = 4
**Output:** 7
**Explanation:**
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
**Example 2:**
**Input:** nums = \[9\], target = 3
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 1000`
* All the elements of `nums` are **unique**.
* `1 <= target <= 1000`
**Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
| null |
Array,Dynamic Programming
|
Medium
|
39
|
849
|
today I will be writing the solution for the problem maximum distance to closest person okay so it's an easy level problem so as I've already explained the logic so I'll start writing the code so first I need totally five variables so initially I'll need previous one which will be initialized as minus one and then I need future which is zero and I need an answer this is a return behavior usually it will be zero so then I start traversing the given input first thing a the check is if the currency whatever am I sitting it or whatever I am iterating it if it isn't one so in this case my previous becomes I then I continue so now let's say we have found the previous one so we need to find where's a future one so for that we start a while loop where we have two conditions one is future should not be out of bound so future should be understand the seeds outside and if C dot future is equal to zero so we go on increment till that or the second condition is if future is less than and both the cases we just keep incrementing our future so at the end of this we have the previous and future pointing to the exact ones where the previous one is and the future one is so we need to calculate left and right now from left we have a condition if previous is still equal to the initialization value which all minus one then we assign to see its lot size if not we do I - please so if anybody has not we do I - please so if anybody has not we do I - please so if anybody has not watched my explanation for this logic please go and watch the explanation video first the link is in the description below so that so then you can come back to this coding video and you will understand this properly right we check your future is equal to see its dot size if it is then equal to zero right else future - I we have our answer as maximum of answer gamma minimum of that comma right then we've done dance let's sum it and see if this worked fine this is cooler again this works fine so the runtime is 32 milliseconds or the time complexity in this case is in the worst case it's or yin-yang being the site n being the size yin-yang being the site n being the size yin-yang being the site n being the size of the seeds or the number of elements in the seeds vector so this is one of the important problem it's an easy level problem please do solve it yourself you connect with me please connect y instagram the link is in the description below and do like share and subscribe until next time keep learning every day
|
Maximize Distance to Closest Person
|
maximize-distance-to-closest-person
|
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**.
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized.
Return _that maximum distance to the closest person_.
**Example 1:**
**Input:** seats = \[1,0,0,0,1,0,1\]
**Output:** 2
**Explanation:**
If Alex sits in the second open seat (i.e. seats\[2\]), then the closest person has distance 2.
If Alex sits in any other open seat, the closest person has distance 1.
Thus, the maximum distance to the closest person is 2.
**Example 2:**
**Input:** seats = \[1,0,0,0\]
**Output:** 3
**Explanation:**
If Alex sits in the last seat (i.e. seats\[3\]), the closest person is 3 seats away.
This is the maximum distance possible, so the answer is 3.
**Example 3:**
**Input:** seats = \[0,1\]
**Output:** 1
**Constraints:**
* `2 <= seats.length <= 2 * 104`
* `seats[i]` is `0` or `1`.
* At least one seat is **empty**.
* At least one seat is **occupied**.
| null | null |
Medium
| null |
57
|
today we are going to discuss the liquid daily challenge which is insert interval uh this video will and this would be consist of this section in first section we will show the question in the second section we will show the approach and in the third section we will discuss the C plus solution now coming to question it is given that you are given an array of non-overlapping intervals non-overlapping intervals non-overlapping intervals where intervals I equal to start and end represent the start and end of the ith interval will have a start and end value which is the starting and ending of that ith interval now it is given that you are also given the new interval which are the start and end that represents the start and end of another interval we will also be given a new interval and we have to insert a new interval into intervals at appropriate position and it is also given that we can merge the overlapping intervals if necessary for understanding this question let us and the first and first understand what is uh what is merging the overlapping intervals ah let us say for example we are given with the intervals like 1 4 2 5. and 6 7. so here we can see that first interval starts at 1 and end and ends at four one two three it's seven we can see that first interval starts at 1 and ends at 4. and second interval starts at 2 and ends at 5. here we can see that these two intervals are overlapping each other so we can merge this interval and the resultant interval will be 1 and 5. so after merging this to interval the resultant interval will be 1 and 5. now looking at this 2 meter one you can see that these two intervals are not overlapping so after merging this whole interval the resultant interval will be 1 5 and 6 7. so this is our resultant intervals now let's understand how we can implement this what we will do we will take two variable start and end and initialize this two variable over the first interval which is one and four and now I will create this list from Index 1. this will index 0 and this is index 2. I will iterate this to the from index 1 and I will compare this to with this n value and check if this value is greater than 2 then we can merge this to interval so uh our e is greater than 2 so our new value of a will become this which is 5. now we will assign our e value like this E equals to Max of e comma this 5. why I am using Max because if our interval would like this if our interval If instead of 4 it was 6 then we can see that these two interval overlaps but if I will assign e with value 5 then it will say that our resultant interval is 1 and 5 which is not true because our resultant interval will be 1 and 6. means after measuring these two interval we will get this as resultant interval and not this so I will use max which will take Max of these two value so if so the max of 5 and 6 will be six so our e will be assigned with 6. so I am using Max now coming back to our test case which was four now the value of our e will be 5. now the next iteration it will move to the next interval and again we will compare the value of e with 6. and we can see that he is smaller than this the starting value of this interval so uh these intervals are not overlapping each other so what I will do I will post this result into our resultant into our result which is one and five and I will assign a start and end as 6 and 7. uh not in the next iteration the loop will go out of the list and our start is 6 and 26 7 and I will stay and I will post this 6 and 7 into our result six and seven now we can see that this is our result and after merging this interval now we have on uh now we have understood what is merging and how we can apply merging on the given intervals now come back to the coming back to the question coming back to the question uh we will give an interval and new interval we have to insert this new interval into intervals at the appropriate position and then apply merging that we have discussed previously now coming to the approaches first we will discuss the Brute Force approach in Brute Force what we can do that we will insert this new interval into our intervals and apply sorting on this interval sorting in this interval and then apply merging to this interval the time complexity of this boot for suppose will be n log n now coming to the optimize approach which is of O of n nowadays and now we will discuss how we can Implement that we will take this discuss now let's understand the logic with the given distance in this optimize approach we will apply merge on this interval along with that we will insert this new interval a new interval hour name interval into our intervals we have discussed normally logic previously that we will apply here now we will take to variable start and end and initialize it with 1 and 2. now these are the index of this list two three foreign in the Merlin logic which we have discussed previously we were comparing this end value with the starting value of the next interval but here we will do the same but we will do one extra thing that before comparing at this comparing this e with the starting end starting value of the next interval we will compare this starting value of this interval with the starting value of new interval if this new interval is smaller then this starting value of this interval this means that this new interval comes before this but here we can see that this new interval well starting value is greater than the starting value of this new interval and this interval means this interval comes before this interval so we will process this first now I will compare this e with uh where the starting value of this interval and we can see that is smaller than three which means this interval doesn't overlap with this interval so I will push this one and two into our resultant list one and two and I will assign start and end as 3 and 5. now in the next iteration we will continue with the second index and again I will compare this interval starting value with the starting value of the new interval and we can see that starting value of this new interval is smaller than the starting value of this interval means this new interval comes before this so I will process this new interval first and in the next iteration I will continue with the second index only so I will compare this 5 with 4 and we can see that 5 is greater than 4 means these two interval overlap these two interval overlaps so I will assign e as Max of a and eight and we have discussed why I am using Max so the value of e becomes eight not the next iteration we will continue with the same index which is 2 and 6 and 7 which is six and seven now we have process the new interval a new interval and after processing this new inter we will assign this value with end Max this value with inter Max now we'll compare e width starting value of this interval and we can see that now we can see that 6 is smaller than 8 so we will assign a as Max of 8 and 7 and we can see that it is next now in the next situation it will move to intervalid and then now again we will compare this eight with this new level and we can see that it is on a new interval as it was already process so we will process this interval only now we will see and we will compare a with the starting value of this interval and we can see that it is equal so I will assign e with the even the E with Max of 8 and 10. so 10 is Max so I will assign t as 10. now in the next iteration it will move to interval 12 and 16. and again I will compare the starting value or the starting value of new interval and you can see that is greater so we will process this with the starting value of this interval and we can see that e is smaller than the starting value of this interval which means uh this interval cannot be most so I will push this into our resultant list and assign start and another 12 and 16. now in the next iteration it will be out of the list and our list is finished so I will post this value into our resultant well 16. so this is our resultant list after inserting the new interval and margin now let's see now we can see that the output matches now let's discuss C plus we have given the insert function which have intervals and new intervals first of all what we will do we will check if the size of interval is zero then we will return new interval means if our interval list is empty then our resultant interval will consist of only name interval so here I am returning new interval now if on the side of interval is greater than 0 then here I am declaring a resultant vector and here I am checking is the new interval is smaller than the starting value of the intervals means this new interval comes before all the intervals in the interval then what we will do we will swap the first value of intervals first value of interval with new interval in Newton now here I have taken to variable start and end and assign this start engine with the first interval value from the intervals and now I'm iterating over the intervals starting with index 1. now as we have discussed in the logic I am comparing the new intervals first value red the with the interval which I am going to process ah starting value of the interval which I am going to process which is in the test case which is 6. so if it is smaller if the new interval is smaller then the interval which I am going to process then we have to first process this new interval name this new interval comes first then the interval and the intervals then the current intervals and now um if the solution satisfies we will come into the safe and we are checking if the new interval is the starting value interval is lesser than equal to the end value add value of the interval means the new interval means we can merge our new interval so we are assigning a with the max between e and the random value of the new interval and if this condition doesn't satisfies means this new interval doesn't overlap so what we will do we will push back the s start and end value and assign our start and end value with the new interval 0 with the starting and ending value of the new interval and if this condition doesn't satisfy it will means that a new interval doesn't come before the interval which I am processing now then it will check if interval starting value blender which I am processing is lesser than the end value means the interval which I'm processing is able to merge it is able to merge or not if it is able to merge then we are signing a signing and with the max of end and the end value of the current interval and if it is not merging with the interval then we are pushing the start and end into our resultant vector and assigning a start and with the starting and ending value of the current interval and after this Loop after this will look we have used this if we have used the safe to check if the new interval doesn't lie in our and doesn't lie in between our intervals means this new interval lie at the end at the ending at the end of this interval this if is for this condition uh now how we will know that whether this new interval was process or not uh while processing we have means if new interval has been processed then we have assigned the stacking value of the new interval as into max intermax and at the end we are checking if the name interval value is lesser than internet means the new interval has not been processed so we will process it here we will check if the new interval is able to merge or not if it is able to merge we will assign e with the max of e and the end value of the new interval and if it is not able to merge then we will push the start and end into the resultant into our resultant vector and assign S and E with the starting and ending with the numerator and at the end we are pushing back ascending to our resultant vector now let's submit this code now let's first run this code now we can see that it is passing all the equivalent space now let's submit it now we can see that the code has been successfully submitted with the runtime of 19 millisecond and the memory of 720 17.1 MB thank you
|
Insert Interval
|
insert-interval
|
You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval.
Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return `intervals` _after the insertion_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[6,9\]\], newInterval = \[2,5\]
**Output:** \[\[1,5\],\[6,9\]\]
**Example 2:**
**Input:** intervals = \[\[1,2\],\[3,5\],\[6,7\],\[8,10\],\[12,16\]\], newInterval = \[4,8\]
**Output:** \[\[1,2\],\[3,10\],\[12,16\]\]
**Explanation:** Because the new interval \[4,8\] overlaps with \[3,5\],\[6,7\],\[8,10\].
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 105`
* `intervals` is sorted by `starti` in **ascending** order.
* `newInterval.length == 2`
* `0 <= start <= end <= 105`
| null |
Array
|
Medium
|
56,715
|
416
|
hello welcome to my channel today we have leeco416 partition equal subset sum so given and non empty arrays nums containing only positive integer find if the array can be partitioned into two subsets such that the sum of uh element in both subset is equal so what's that mean is the input in this situation and we can partition them become 115 and 11. so uh separate them in two groups and they add up equal to each other so in this case we cannot add them up each other then we turn fast and let's take a look at this question so uh we are going to use uh we try to simplify this question first and we are looking at splitting terms in two separate subsets so the total is sum for example total sum and then each of them sum up it will be some equal to 2 if they can be divided by 2 so the sum for each subset will be some total sum divided by 2. so now we have a condition and we can just basically after this analysis we just uh transfer this problem into a small problem that we are coming to here original array and looking for uh numbers end up equal to sum divided by 2 so that problem is become like this right now so let's write some code in here we just try to add some uh what's that called edge cases in here sorry about that um equal to zero num uh actually uh started from if num equal to zip no or num stop playing equal to zero then at that time we return false okay like what we mentioned first we get the sum first the pin sum equal to started with zero and we have a for loop through the whole num and add those value integer in sum so now sum is a total sum of the whole entire array so if sum it's odd i was like god 2 is equal to 1 then we turn false why because uh if two equal um sub subset that they're the same is so equal right that mean the subset time two would not be an odd number so when the sum is odd number that won't uh divide equally and that's the condition and also yes we will have divided sum equal to let me see some divide equal to two so what we're looking at is sum divided by two so we're looking at the sum which is target is equal to sum total sum divided by two and we're going to use dp to solve this problem separate in here so now dp actually boolean dp equal to new boolean of we only need sum plus one that much space and we will have dp zero started with true so this is boolean so all of them are uh false the as a default and for zero is a default number it's always set to true so if we don't pick any number that's always true so now we can uh let's go through this example first and then we explain what that flow is so now we look through the whole entire nums and also loop through a j start with sum and j have to be bigger or equal to zero and j minus counting backward so it's like a so if j is bigger or equal to i and dp j equal to dp j or dp j minus i so now i make i'm going to explain now and dp means um let's see so could the current number could be equal to the current number or um the j is the total minus the current uh integer right here so if the problem is uh if you're looking for 5 and we see a 5 then it's definitely correct because 5 minus 5 equal to 0 because the base is 0 right now so now 5 is correct in here because 5's total it's a target so now if you're looking for 10 as the target since 5 is true because of this period operation and then we're looking at 10 as a target so 10 is equal to 10 tens false as a default or 10 minus 5 because we have 5 in here then uh so we're looking for dp5 tp5 in the previous operation is already true then we can see dp10 is also true based on that situation and at the end we go to the end of the dp which is dp sum we turn the truth or false from there and i will try to write this situ example right here so now we create things the total is 22 and the half of them is 11. so we need to look at this array and find any number combined equal to 11 then cool so we start with zero one please bear with me it might take a while uh four five six seven eight nine ten almost there 11. so we have this 11 number here because we set it as a boolean so d4 sd4 they all false you can imagine that all false right now and in this case we make 0 always true because 0 is nothing right here so um we come to here we're looking at um cosine from sum is uh j is equal to sum and if this situation we check if dp 11 or dp 11 minus 1 because now currently i is equal to 1 then check this one if it's one and they both of them are false then fine then j will minus one and check both of these are false no and keep going to one right here so dp1 equal to dp1 which is false or dp j is 1 right now 1 minus current i is 1. so true i mean dp 0 is true then 1 is true it's pretty intuitive because if we're looking for a target as 1 and we have 1 here then sure one is correct right and at that time we change his false become true at that case you can keep looking at this for loop you will see if we're looking at i mean we can see five we if we look through five right here we see five is also true um we also come to see if the target is six right now okay we have one it's true zero true five is true so how about six so dp six right here six 6 is fast no good and if 6 minus 5 equal to 1 is true then six should be true then in the same thing i mean if we at five you're looking at 11 right here there's two way you can make it true which is 11 itself minus 11 starting from sum is 11. and we have a 11 in this part then sure minute is eleven then true because reach out uh becomes zero right now the divorce case is true and also you can find this right here 11 minus 5 then also you see 6 is also true so there's two way you can make this uh sum up to the sum and that's how you solve this solution and so i mean i might take it so long to explain this one but it's really intuitive just to make this uh example right here so now let's take a look at the code so it's true and it passed the cases but the problem is in here a small little not really after my problem because we didn't use three two three four seven eight nine and another optimization for this one is try to save this t which t0 to the hashmap put this in hashmap and after that we found 5 and put those all trues in a hashmap then we save a lot of space for this dp and also time too um this is for this solution and if you have problem please comment below and i will see you in the next video thank you so much bye
|
Partition Equal Subset Sum
|
partition-equal-subset-sum
|
Given an integer array `nums`, return `true` _if you can partition the array into two subsets such that the sum of the elements in both subsets is equal or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[1,5,11,5\]
**Output:** true
**Explanation:** The array can be partitioned as \[1, 5, 5\] and \[11\].
**Example 2:**
**Input:** nums = \[1,2,3,5\]
**Output:** false
**Explanation:** The array cannot be partitioned into equal sum subsets.
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 100`
| null |
Array,Dynamic Programming
|
Medium
|
698,2108,2135,2162
|
222
|
hey guys welcome to my channel and in this video guys we are going to solve a really interesting coding interview question video which is question number 222 of lead code count complete three notes so without wasting any time further let's get started with the problem statement so basically guys the problem statement says that we are given the root node of a complete binary tree and we want to return the total number of nodes in that tree now what is the complete uh binary tree you can see here that this is a binary tree is a tree where every parent node can have only two child nodes left node and right node now in case of the perfect binary guys every single parent node so in this case parent node one two and three so every single parent node would be having both left node and right node except the leaf nodes right so Leaf nodes are the nodes which are at the end however in case of complete binary although every parent node at every single level can have or must have both left and right node but there is an exception in case of your last parent level okay so basically all the parents in case of a complete monetary must have left and right node except the parents at the last level there is a possibility that the last level parents may not have both left and right notes okay so that's the complete binary tree for you can see that in our case the last level parents are node two and three where two is a perfect binary tree by Perfect binary subtree is having both left and right child however three is not because it's only having a left hand so this makes it a complete binary because only uh the parents at the last level are not uh you know perfect mandatories okay now the examples are pretty straightforward guys we are just counting the number of nodes and returning them so if the root is null you will return 0 but in all other cases you'll just count the notes and return now the number of nodes are in the range of 0 to 5 into 10 to the power 4 and same is the node value the tree is guaranteed to be complete okay now in this uh question guys there is also something that you have to design algorithm that runs in less than order of n time complexity now let us see first of all let's design an algorithm which will run in order of n time complexity and then we'll optimize it right now let's see uh how we can do that so first of all guys uh this is the uh so I'm sorry I kind of deleted that solution function structure but this is a solution function structure that is given to us we are given a function called as count nodes now the really simplest approach for solving this problem is just do a uh in order traversal if you just reverse all the nodes and you add the number of nodes you Traverse you will eventually become you know you will eventually return count nodes so this is really straightforward guys and just understand this code because it's gonna help us later so what we do in case of a simple traversal we check that if root is equal equational if root is equal equals to null then we return 0 because that's a special case but if root is not equal to null then what do we have already traversed root so we will add our number one count for root because we have counted the root note and then for the rest we are going to individually count the number of nodes in the right subtree and in the left subtree so all you do is you do call the recursive function count nodes again but this time you don't watch the root note but you have the left node and the right mode okay now if I run this you will see that it is actually passing it's actually going to pass all my test cases and this is actually gonna you know get accepted as well uh however guys this is not something that we want because this is the order of end time complexity solution because we are visiting every single node twice so this is not something we want we are going to optimize it but just remember this line and we are going to take it forward we are going to use it now let me delete this code and let's jump to the optimized approach okay let's see how we can actually uh optimize this so uh I don't know guys if you know about the properties of binary tree but one of the really interesting property of binary tree is that if this is a perfect monetary so let's say if this three were also having another right node and this 3 was not incomplete but it was having a right node then the height of this binary tree would be 2 to the power of you know the height of this binary is actually three because you can see that this is level one level two level three but the number of nodes in this binary tree would be 2 to the power of height minus 1 okay so this is the formula for the total number of nodes in a perfect binary tree to raised to the power height of the 3 minus one okay only in case of perfect binary if you don't believe this then we can simply draw Iron this so you can see that the height of this tree is one two three there are three levels to it so 2 to the power 3 minus 1 and that is actually equals to seven so if 3 was having a right node here it would definitely be numbered as 7 and there would be 7 node we are going to use this height calculation property to actually uh count the number of nodes so let's see how this is how this goes right so the first step would be to find out the height of the left subtree of this root node and the right sub tree of this root right so if I just find out that my right side and my left side is having the same height so let's say I have calculated my left subtree height and I have calculated my right Supply height so if the left subtree height and the right subtree height is same what does that mean basically guys it means that this is a perfect binary so in that situation what we are going to do we are just going to Simply return this now return this where for height we can use left height or right how it doesn't matter why because both are same problem is when they both don't match in this case it won't write because if you just go and calculate the no uh height of the left subtree here the left type you will see that the height will come out to be three whereas if you calculate the height of the right three it won't come out to be three because after three there is no right mode so this can never be a perfect binary because the depth on the left side and the depth on the right side is actually not same okay let's actually call this uh this depth because that is more you know uh that is more explanatory because height of a tree will also be called as the number of levels in a tree so in this case you can see that the right tree has actually three levels but the depth of the right tree that means if you just go from root to right the depth is not actually because the depth of the left tree okay so I'm going depth now so the problem either when this left depth is not equals to the right depth then what we are going to do now in this situation guys we know that we cannot apply this formula so what we do is just exactly what we did in our traversal case we would Mark the root node as Traverse so we'll take you'll count the root node as one node and then we'll go to the right Circle we'll go to the left subtree so we will count the nodes of right Supreme let's say first let's subject and then we'll count the nodes off right safety and then we'll add them and that will become the high that will become the total number of nodes in my tree now you guys I'd say that isn't it like reversal but actually it's not guys because if you see when I will call this function count nodes root dot left so when I will reach this node 2 here we are going to find out that this 2 this left sub tree this whole portion is actually a perfect binary so you do not have to uh you know Traverse all of its nodes you don't have to Traverse all of its nodes I know it is a very simplistic way so you kind of are traversing all its node but if this was a complex subtree then you won't be traversing all its own you would just see the left depth and the right depth and determine that yes this is same then it basically means that you can use the formula to actually that you can use the formula to just you know calculate the higher calculate the number of nodes in this left subtree so basically guys using this recursive function uh for the sub trees you won't be traversing each and every node but just using the depth to find out the total number of nodes so that would save us time and that would be much more optimized then actually traversing or visiting each and every node and you know counting it okay so that's why this solution works much better because we are using a formula to calculate the total number of nodes okay so now that this solution is clear guys I think we can move forward to the implementation part okay so I'm just gonna keep uh I'm just gonna delete so I'm just gonna keep it I'm gonna delete this dry run thing and we are going to start implementing our solution so the first thing guys is to Implement our depth functions right so left depth is G node and then you do integer depth equals to zero until the node is not equals to null you will keep on going towards the left okay so node becomes equals to move dot left and that will keep on incrementing finally you are just going to return the depth okay that becomes my left depth function now what I'm going to do I'm just going to copy this and just replace wherever you have left just replace the left with right and that will actually become your right depth function okay so that's done now we have both the functions to calculate our left and right height what was the first step was to calculate the left depth right depth compare if it's equal or not right so let's do that let's go to our count node function and let's say the left depth is equals to left step and you pass your root node in that so that is the left depth of my root node and then similarly you calculate the right depth of your root node okay now let's say if left depth is equal equals to your writer so in that case it's pretty straightforward we are going to use the formula right so you return and you return an integer in Java we are going to use math dot power function to calculate the power of 2 and what is the power of 2 is either that left depth of the right dip doesn't really matter I am going to use left here and then you subtract one for M from here and that becomes your answer basically right but the problem is when left is not equals to write when it is not the perfect binary tree what are we going to do then so in that case you don't do anything you don't apply this formula what you do is you just take that node as one add that root node as one and then you individually apply the same function to the right subtree and the left sub tree so you just call count nodes and pass root dot left and add them together okay so we just passed the individually count the notes of left sub three individual accounts or nodes of right subtree and add that one for your root node and that becomes your answer and when you will call this secretive function this recursive function will now use the same formula for the child's sub trees also thereby saving us time let's run this code guys let's see if this works for our test cases now you can see that it is accepted so what I am going to do I'm just going to Simply uh submit this okay and there you go guys here you can see that the answer is accepted as well now yo you might ask this question that how is it uh you know how is it doing the complexity well how is it managing to make sure that the complexity is much better so let's see that as well uh so basically guys you can see here that we have a count nodes function right and in this countdown function we are calculating the height of the right tree and the height of the left tree right so let's say that this is your account node function which is called for the first time and you are passing the height okay you are calculating the height right so for the root node let's say the total height is H right so you calculated H for left depth and for right depth so it actually h plus h but we are not going to use uh you know differently here we are just going to say that both of these things cos it as H because H is the height of the total root tree and at the first step we are actually going through the entire result will be H right for when we go into the left subtree and when we go into the right subtree what's happening here so at every single uh every single recursive call of count nodes we are reducing the height by one right because now we are at this sub tree level so height becomes equals to minus 1 and same thing height minus 2 and same thing height minus 3 and this is going to continue further unless my height is actually close to 1 because once I reach the leaf nodes then there is no height right then we just uh return it through this power function right when you reach a leaf node there is the left and right height becomes the same which is 0 so you just return it from this power function right so you don't actually go to this call but other than that if there is a difference between left and right every single time you are just adding the height okay hiding the height adding the height right okay so now you see that this height function is being called as the sum of natural numbers right what is the sum of natural numbers sum of natural number becomes uh sum of natural number is H into h plus 1 or minus 1 divided by two I do I'm not 100 sure but it's something like that I think it's h into h plus 1 divided by 2 but that doesn't matter but what matters is that if you take this formula and you multiply H with h eventually your complexity will becomes equal to H to the power 2. okay so basically guys this height function this depth function whatever the complexity of this depth function is you are powering it by 2 and that becomes the complexity of your count node function now let's see what is depth function is doing so depth function is actually going from node to node right on node to node left but it is actually going in a direction which is just down right it's just going in One Direction it's not reversing all the nodes just going in One Direction now how I came up with this I that's not part of that video but basically guys this depth calculation function is nothing but a uh function which is a logarithmic function so it has a complexity of log uh it has a complexity of log n because the number of nodes let's say the number of nodes are n then the complexity will become equal to log n right so if this is a logarithmic complexity then basically it will become equal to log in to the power of okay now you have a log n function to the power of 2. and this complexity is definitely less than your order of end time complexity so that's why guys this solution is a much better solution than the original traversal solution where we are just visiting each node and Counting the node okay so that was all about this video guys I hope you guys understood that why we went with this approach why this problem is so important and how actually time complexity is calculated for three questions ah really important to have memorized the you know complexity of at least height calculation logarithmic complexities because they come really handy during your interview okay well thank you so much for watching guys if you have not yet subscribed to my channel then please do subscribe and hit the Bell icon for future notifications of more such programming and coding related videos I'll see you guys in the next video guys uh if you have any questions comments suggestions until that time please write down in the comment section below I would be really happy to address them and uh please like this video share this video subscribe to my channel thank you so much for watching I'll see you guys in the next video Until then take care bye
|
Count Complete Tree Nodes
|
count-complete-tree-nodes
|
Given the `root` of a **complete** binary tree, return the number of the nodes in the tree.
According to **[Wikipedia](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
Design an algorithm that runs in less than `O(n)` time complexity.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** 6
**Example 2:**
**Input:** root = \[\]
**Output:** 0
**Example 3:**
**Input:** root = \[1\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5 * 104]`.
* `0 <= Node.val <= 5 * 104`
* The tree is guaranteed to be **complete**.
| null |
Binary Search,Tree,Depth-First Search,Binary Tree
|
Medium
|
270
|
1,748
|
so this is the sum of unique elements problem on lead code and it's pretty simple uh classified isn't easy and the premise is okay given a list of numbers if something appears once uh returns of the sum of all those numbers otherwise you know ignore them and they use the word unique elements so right off the bat when i hear the word unique in a programming question i'm thinking oh there's probably a set involved because they have the property that you know you can't add two of the same key to a set so i'm already thinking about that and i'm also thinking how would i do this in my head because if i like you know if i was just giving this program this problem to do in my head like that's probably and how to just do it manually that's similar to how i would want to press a computer to do it so as we're going through we're probably going to need to add all these items to a set and then just sum those numbers up so pretty simple um but it does miss the subtlety that um this number two so if we were to use that solution we would return six one plus two plus three and then ignore this one um but uh we want to actually ignore numbers if they appear more than once so we actually need to keep track of how many times we've seen a number so we're not actually going to be using a set but we're going to be using a map so mapping a integer whatever value we see here to the frequency so that's a pretty common data structure but uh let's go ahead and do that so let's uh no before that before we do it up let's discuss the run time in the trade off so here's what we'll do we'll build up a frequency map that will take o of n time and o then space uh oven time because we're gonna have to go through each item in the array and then o event space because potentially all items are unique and that's how big the array could get the size of the um input i guess i can make this a little bigger um so yeah so that would be our first solution um and then so no that would be your first pass so we would build up the frequency map that'd be oven space over and runtime and then we would go through the map again and uh add up elements that have been appeared exactly at once so let's do that real quick so we just need to go through each item in the list eyes left and nose plus and um we have two cases whether it's already contained in our key set of our map or the value is not contained so that's pretty simple and i'll just call that value that we're looking at let's call that val and i'll say okay our key set contains that's one case and then this is our other case so if our map if our key set does over map doesn't contain it that's pretty simple we just want to put that value in there right but if it doesn't we'll just we just want to put the next value in so we'll put um val and then just basically increase that value so math.get plus one so now we've built up our frequency map build up brief map and uh now we just need to go through again and sum it up sum up the values that have appeared once so what is that so for each key in the map um if the frequency is one then we'll add it up into our sum equals one then we'll say okay sum plus equals q at the end don't forget to return the sum zoom out so we can see all of that um so yeah this is one pass this is our second pass this is our omni storage let's see if it works cool ran fast one millisecond um so this is good but your interviewer might ask you can you do better and you might say okay how so and you might or she might say uh can you do it in one pass and then you say oh so a similar idea would be to just use a frequency map but inside there actually keep the running like a running tally of the sun like in there and this is why i tend to use for loops rather than streams in interviews because it's a lot clearer and you can actually add stuff in here a lot easier than you know trying to chain it together um with you know like the lambda function syntax stuff so um so let's try and keep track of running tally this um so we'll do this we'll just put this up here and we won't need this anymore and we will say okay um our or the meat of our logic is probably going to go in here so if we're going to be putting a new value into the map we still want to you know add in that vowel like that makes sense but there's some subtlety here so if we go into this let's look at this example too for this um use case so if we've gone through and we've put in one and the frequency of one is one we've done that we've gone through this step but the next time through and then we've added it into the sum so the next time through we'll be looking at one and uh we'll say okay we've already added that in so we actually need to subtract it out so it's because it's elements that have appeared that have already appeared once in the set um or in the map we need to you know less that out so nav dot key set contains wait oh sorry we are gonna sorry i'm we're gonna say um if amount dot get at val then we're going to go ahead and subtract it out in the case where it's greater than 2 that implies that we've already subtracted it out previously so we can actually ignore those values so let's see if that works and you can see still runs one that one millisecond it's still java is pretty fast um but algorithm algorithmically better run time so this is a better solution and just for you know entertainment purposes um just you know an example to show why like i actually do recommend python um what how long was this solution this was you know let's say 24 lines um in python you could do it and i'm just going to copy paste something i wrote earlier you could do it a lot easier with a lot less pain and i'm sure there are more there's like one-liner python solutions like one-liner python solutions like one-liner python solutions but if you're going to like not use any like built-in functions like this is 14 lines built-in functions like this is 14 lines built-in functions like this is 14 lines so i think this helps making it a lot more readable um you know same runtime same everything so i might start actually using python in the future but for these interviews but interesting all interestingly also you can see that python does run a bit slower but anyway that's the um sum of unique elements problem until next time
|
Sum of Unique Elements
|
best-team-with-no-conflicts
|
You are given an integer array `nums`. The unique elements of an array are the elements that appear **exactly once** in the array.
Return _the **sum** of all the unique elements of_ `nums`.
**Example 1:**
**Input:** nums = \[1,2,3,2\]
**Output:** 4
**Explanation:** The unique elements are \[1,3\], and the sum is 4.
**Example 2:**
**Input:** nums = \[1,1,1,1,1\]
**Output:** 0
**Explanation:** There are no unique elements, and the sum is 0.
**Example 3:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** 15
**Explanation:** The unique elements are \[1,2,3,4,5\], and the sum is 15.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100`
|
First, sort players by age and break ties by their score. You can now consider the players from left to right. If you choose to include a player, you must only choose players with at least that score later on.
|
Array,Dynamic Programming,Sorting
|
Medium
| null |
1,535
|
That Sun should be praised by the ladies in this sense and should be boys and which is again a creation of inches. Now half an hour's time means absolutely there is a solution for this. Login is a matter of work for 200 people. So the first thing in it will be this side of a mixture, Hanuman. G A Fab Four Six Seven and Abhishek Tiwari ji's biggest was Tu Theek Hai's pen everyone takes kitni bar me two in one, then after that 2012 Ki Koi Hum Kisi Ko Ekse Se Mil Jayenge Iss Apna Number Hai and then a That Rishi will go on a fast unto death, while the pattern will go to India 1202, so there are two, yes, now we have given this question of this Mohra film and Suryodaya will go in it, after the line of this, what we are seeing, all the note elements have happened 2019 Inch 80 ML 600 if gifted then this one side all points 90 ok then subscribe this channel also this side is amazing so if this is A and Sonu what will they do like what will they say then like comment ok in this we What will we do, we will check that the edge is greater than the element. Okay, if we see that the edge is greater than the element, then what will it mean that now how many time inches will we cut for our dipper? Okay, like you have a tablet. This one is definitely worth taking 136 and everything is looted, this period is limited, find the one without the account that is alive from us because then what is the fruit after washing that you Yasmin element now see 200 What happened now our enrollment is three do It has been said that of course, now we are from the last side, now Amazon should make this thing equal to one and from here questions are being raised, then what will happen after that, now we are ours, what happened now after Play Store, what happened? Gift happened, we did the subject, so now what will happen, infidelity, what are you going to do today, sofa, The Amazing spider-man, David today, sofa, The Amazing spider-man, David today, sofa, The Amazing spider-man, David will take the frilled skirt, the person, the president, element, it is good, okay, after the ideal, look at this point which is from one to two photos. Will you brother please put it in this 200, our accepted end design, small accidents happen only two times.
|
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 |
1,047
|
Welcome all friends Adam will do this question in this video let's 1047 1000 47 question number remove all adjacent duplicates in a string ok so look at our example what is given in the input is given in the output is ka So what do I need to do, what is the right thing to do, first I should know this, now look, whatever means duplicate should be deleted, it is coming twice, delete both of them, it is coming once, it will do, brother, it is okay, that is, if as many as Also and number of, all the number and number of alphabet, all those meanings will not remain the same, if there is an order, only one present will remain, okay, both got deleted, it is 1:00 o'clock, so what is our answer? What does it 1:00 o'clock, so what is our answer? What does it 1:00 o'clock, so what is our answer? What does it mean that earlier it was C? Later a child now let's see example number 2 ok example number ok so what is there in the output brother this is a single element so we have a single element so A is left and This much element is gone, so A is left, so we have to write this operation in coding, okay, what has to be done in the court, first of all, we have to make a string, which has our answer, okay, in this answer, what should we do first? We will push back one of its elements and read whose element is S K element and after that I plus now I am saying that whatever SISI means whatever value it has on the index, what should it be equal to? If you want answer dot back then what to do with it, okay if not means brother what will you do in the answer what will you do brother whatever value is there in the index of s and what will you do after coming out of the form return answer will do return answer Okay, because we have added zero, so what am I talking about if B is the element, if we know the meaning of back, which element is not lying in it, what is read in the answer now, A is lying because A, what did we do here to push back? The first element of this is now when B goes I am of that if B this statement means if B is equal to A then what will happen is it will be pop meaning it will also remove this string from the answer. Will remove the string, if it is from then it will give the string, like we are man, let's B, if it is not from, then it will push back in it, then what will be A in the answer? In the answer, A will be A and B is gone, after that B will come ok What does B say, if you see now which element has gone to answer.back which element has gone to answer.back which element has gone to answer.back B is done, now it will be updated here which element has gone to answer.back Our Jab Aayi Jab Tu Hoga To Yeh Check Hoga Tu Par Kya Check Hoga ki tu pe kya hai b and b is equal to tu and b meaning answer dot back what is b so it is from both so what will happen is pop operation means it will be removed then what will be b from this will also be deleted and This will also be deleted, meaning what is left with us in the answer, what is left in the answer, A is ok, what is left in the answer, now after that look, our I was you, now I, we will go to 3, we will go to I3, what is A, meaning A = back. If A is lying in me, then what will happen now, will it pop, brother, this pop operation, now the answer is what is read in this ring, brother, nothing A B means that our three operations have been deleted, now there is something in the answer dot. Now four will come in the answer meaning that what do we have in the answer and there is null value lying in the back, not null means nothing is lying, keep in mind that it is empty, it is absolutely empty. On which operation the answer will be given. When it is not matching, this operation will become active. When this operation is run, what will it do in it? Answer: What will happen then what will happen after C and C? Answer: What will happen then what will happen after C and C? Answer: What will happen then what will happen after C and C? What is A? If it is not matching with A and C? When he is not matching then what will he do? He will push back because from today onwards he is not matching at all because he is A, so he will push back this too, so in this way, our answer, what have we done, answer we returned. What is the value of C and AI? Now I understand. Let's run it first. Let's run it here. Brother, it is giving an error. What is the error giving? It is not giving anything. Let's run it first and then our answer too. Hey, what should be the answer to this, both will be cut, delete everything, after deleting, submit it, submit brother, I have submitted this question many times, it is ok, it is going perfectly fine, thank you so much, thanks for watching. more videos
|
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
|
1,974
|
all so this question is minimum time to type word using special typewriter and all right and let I'm going to explain the C in my own definition so you got a spinner something like this and um you want to type a letter then you explain this um what this called like a tool right so if you want to say oh I want to type a and I starting a right and I will just enter a so it will be one second if I want to move to C right I will just you know P twice you know uh twice to the right and I will plus C for the time right uh if you look at a look at the constrution uh it's starting at letter a right initial starting at letter a and you can go counterclockwise or clockwise so if you add letter a and then if you want to type z um you don't want to go all the way from you know um clockwise to here you can actually doing the counter clockwise you know one step to the left and you get it right so that will be the solution so how many so what do you want to return the minimum number of a second to type the character in the word right so um we want to find out like what is the current position the current value from here uh sorry from here to the previous value so we want to find out the previous value is what the value you were have so imagine that you at right here you I mean the initial value is a right but the next character is G right so from a to G you know there's a distance you either go clockwise or counterclockwise and then you want to find out like what is the value you should add into your result because it has to be in minimum right so we want to find out which one is you know which one has a better option right so we have to compare clockwise and con clockwise so this will be the solution all right how do I do this Traverse um the clock right so I'm going to say in result so I'm going to initialize to the world. lens right and then my previous value should be what letter a right so initial it was starting at letter a and I'm going to Traverse my toay and definitely I'm going to return result right all right so let's look at this so I'm going to say the D is going to be what the absolute value between uh C minus previous so it has to be positive number so at this in this scenario I don't care it's counter clockwise or clockwise I mean I know it's one of them right so the other direction is going to be what 26 minus a d right so um the other direction going be um say this another way since another way go to 26 minus d right and then the result will plus equal I mean you have to keep adding right so it's going to be minimum between the D and another way something like this right and don't forget you want to update your pre to the current charge right let's look at this yes so for time in space this space constant times all of them yeah so a little bit Improvement is going to be we don't need another web variable we can just do this and this plus and then submit and if you F this is irrelevant you can do this wrong oh and this have this has to be this guy and submit all right so which one you prefer I mean all of them works but I would prefer this one oh sorry this one this is actually more readable and understandable and the time is space you know all of them for the time space for the constant and if you have question will comment and I'll see you later bye
|
Minimum Time to Type Word Using Special Typewriter
|
find-customers-with-positive-revenue-this-year
|
There is a special typewriter with lowercase English letters `'a'` to `'z'` arranged in a **circle** with a **pointer**. A character can **only** be typed if the pointer is pointing to that character. The pointer is **initially** pointing to the character `'a'`.
Each second, you may perform one of the following operations:
* Move the pointer one character **counterclockwise** or **clockwise**.
* Type the character the pointer is **currently** on.
Given a string `word`, return the **minimum** number of seconds to type out the characters in `word`.
**Example 1:**
**Input:** word = "abc "
**Output:** 5
**Explanation:**
The characters are printed as follows:
- Type the character 'a' in 1 second since the pointer is initially on 'a'.
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer clockwise to 'c' in 1 second.
- Type the character 'c' in 1 second.
**Example 2:**
**Input:** word = "bza "
**Output:** 7
**Explanation:**
The characters are printed as follows:
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer counterclockwise to 'z' in 2 seconds.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'a' in 1 second.
- Type the character 'a' in 1 second.
**Example 3:**
**Input:** word = "zjpc "
**Output:** 34
**Explanation:**
The characters are printed as follows:
- Move the pointer counterclockwise to 'z' in 1 second.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'j' in 10 seconds.
- Type the character 'j' in 1 second.
- Move the pointer clockwise to 'p' in 6 seconds.
- Type the character 'p' in 1 second.
- Move the pointer counterclockwise to 'c' in 13 seconds.
- Type the character 'c' in 1 second.
**Constraints:**
* `1 <= word.length <= 100`
* `word` consists of lowercase English letters.
| null |
Database
|
Easy
| null |
7
|
hello this is B Mo in our last video we solved the lead code problem to sum we solved it in an interview setting where we heard the problem we thought of ways that we could solve the problem using Brute Force approach we clarified some assumptions and asked some questions to the interviewer to let them know that our understanding is correct then we provided a we provided The Brute Force solution and then we provided a off between the space and time complexities and ask the interviewer in which kind of solution they would be interested in we provided the code for the solution and then we should have commented on the space and time complexities which we did not and therefore today's question will be reverse integer where we will do just that so as I told you in the last question lead code helps us a lot by giving us a lot of information about a solution and removing any need for us to ask clarifying questions but we will assume in this reverse integer question that the interviewer has asked us to reverse number just that nothing else so okay that is pretty straightforward but we will have to ask the clarifying question the number one question which comes to mind is will this number be positive or can it be negative as well the second question that comes to mind is different languages have different uh sizes for integers or different languages have different data types for numbers Java has integer Java has long double and Gang has in 16 i32 which have different sizes so what will be the size of this will we get an integer or can we get a decimal value as well if we are getting an integer then what's the range can it be a long integer and if we are getting a decimal how do we proceed ahead with that then because of the nature of this problem we will have to ask the interviewer will the system accept Any number greater than that range or will the system crash if the system accepts Any number greater than that range let for an example in Java we are getting integers we can use long and then type it to integer and then return the value so it becomes a fairly easy problem but the challenge will be when the system cannot handle any number bigger than that and that's where we need to think out of box and provide a solution so for the purpose of this question we will be assuming the defaults set by lead code itself the number will be a signed number that is it can be positive or negative it will lie within the bounds of integer for Java which is from minus 2 to^ 31 to 2 to the 31 - 2 to^ 31 to 2 to the 31 - 2 to^ 31 to 2 to the 31 - one and that the environment can't hold any number which is outside the bound of that integer so using long or any other data type to solve the problem and then cast it to integer is overruled so now let's start with the solution so let's uh Define uh number num which is equal to X and if x is less than zero n equals minus oneus so one mistake that I did here was uh I did not clarify how I will be solving the problem so let's remove this and let me clarify if y as a candidate to the interviewer how I will solve the problem so what I'll do is I'll deconstruct X little by one so if x is 123 I'll create a number y from 123 by picking the last element last uh digit that is three and putting it in the new one then removing two and then making it 32 the new number which I am constructing will be made 32 then I'll be picking out one and then creating it 321 while doing so I'll keep on checking whether I have crossed that threshold one good way of letting the interviewer know how we are exactly going to approach a problem is by writing pseudo code which we can expand later so here we'll do that and say okay convert the number into and into poster let's say that then we can say instruct the reverse number and we will place this in a loop and this is Loop end and while constructing the reverse number we will check whether the reverse number created till now as cross the bounds and then finally return the reverse number so let's start with the solution we will Define a number in Num and we'll make it equal to X and if X is less than Z we will make num positive so num equals minus num Also let's define the integer we will be returning our solution so let's call it reverse num because it specifies exactly what it is we have num and we will be returning the reverse of it so it's reverse num now we have the Loop condition so we'll say while num is greater than zero and why this Loop condition is num is greater than zero because for constructing reverse num we will be taking the last digit of num every time and putting it into reverse so let's uh do it we'll say I remainder equals num mod 10 and now we'll have to put this in the reverse num so we'll say reverse num is equal to reverse num into 10 so let's say reverse num contained one earlier and now we are getting four we the final result will be 14 so we'll have to multiply reverse num by 10 and then reverse do equals remainder finally num should be num by 10 now okay we are constructing the reverse but we are nowhere checking whether that reverse crosses the bounds of whatever bound we have been provided so let's do that here so we have the remainder now we are making some changes in Reverse num so before doing that let's check whether we can do those changes so I'll be writing a function here so let's write a function keep it modular so if uh number let's call it number exceeds bounds exceeds bound and then we will be giving it uh the reverse num the remainder and we should also give it whether the number is greater than zero or not so X is less than x is greater than equal to let's think we are telling it we have to tell it is this positive or negative so let's give it is positive or is not negative so if it exists this uh exceeds this bound we will say return zero now our number is constructed so okay now we have to return the reverse number now the challenge is now reduced to writing this function number exceeds bound so this will be a volan function number exceeds bound and we are taking in an in number or num let's call it num here and in uh added and uh Boolean is not negative okay so if is not negative if the number is not negative then we have to check with the upper bound and uh we know what steps we are going to perform on reverse num later on so we'll be multiplying it with 10 and we will be adding the remainder so if the number is greater than the maximum number by 10 then that means after multiplying it with 10 we are going to exceed the bound so we'll just say if num greater than integer dot max value by 10 right or if the number is exactly equal to integer. max value by 10 and the addend or whatever the carry is adding that can cause the Overflow then we need to check that as well or num equals integer do max value by 10 and num plus addend is greater than integer dot max value so now uh we have put in Num plus addent this can cause overflow but that's okay this is an inequality and we can just uh subtract the same number from both sides so num is greater than integer do max value minus addend in this case okay so in this if this is true then this will exceed the bound so let's uh remove the if condition and placing a return here else if that is if we are not going into the if condition that is the number is negative then we'll have to think about this so we'll say return num but everything is positive right so return num is greater than integer Dot uh max value sorry max value by 10 so the difference between the max value and the main value is uh of one digit like uh the difference is one if we consider the absolute difference that's it that is or num is great equal to integer do max value by 10 and num plus addend greater than integer do max value + one because the difference is + one because the difference is + one because the difference is one now again we are exceeding the bound here num plus add can be greater than integer do max value and integer do Max Value Plus is definitely greater than integer. max value so and as I already told you this is simple inequality so we will just subtract the add in from here as well as here we had a plus one here let's subtract one from both sides so this will become the one will disappear from that here and we can have number minus one here let's put in put this in bra brackets so okay we have the return condition done so let's check it this out let's uh run this and see what we get also if uh we if we have had a negative number because we put in a number equals minus num here then we'll have to return a negative number here as well so return X is less than Z if x is less than zero then we'll have to return minus reverse num otherwise we can return reverse num Let's test this out there is okay uh we forgot to put in semicolons here yeah any other error that we receiv let me check this out okay two errors yeah we have multiple errors Max okay yeah let me correct that max value here max value is correct max value okay uh this has been accepted so let's see for 123 we are getting 321 for negative numbers we are getting this for uh 120 we are getting 21 and that was expected so let's check uh what's the let's create a test case of our own test case plus and have the number 1111111 or let's see what's the upper bound Java fure or rather than that we can have Java d. max value so this is the number let's copy this and uh let's paste in here so what we have to get is okay if we get if we give it this reversing or if you give it a number less than that reversing this number should cause the upper bound to exceed now let's check the minimum value as well in value this is this number and let's paste it here if we are going to reverse it this is an eight and this is a two definitely it will increase exceed the bound let's check with these two test cases so run okay this has been accepted both of these have been accepted Let's uh try to submit the solution so we know that this is correct but we will also say what's the time and space complexity for this so let's see what time complexity this is a constant time operation this is while loop so this will require uh some time like addition in the time complexity and that will be so what this is doing is hacking off the last digit of the number 1 by one so it is dependent on how long the digit is so if uh let's say the number is of the order of 10^ the order of 10^ the order of 10^ X then the time complexity will be o of X here for this Loop uh not including number exceeds bound if we go to number exceeds bound then this is a constant time operation so we can say that if the length of the number is or the number of digits in the number is X then the time complexity is O of X because that's how the how that's the number of times this Loop will be run but since we are operating within a bounded range so we know that the maximum length will be bounded cannot exceed uh this bound so the time complexity is officially capped space complexity we tooken one number and nothing else so the space complexity will be o of O of sorry o of one let us submit this solution and it is accepted so great so what did we learn we learned that we will hear out the question clarify that asks uh we will ask questions to clarify understanding clarify edge cases it's good to write uh pseudo code and then expand on that pseudo code it's better to write modular code supportive functions which we can then expand later on it's okay to make mistakes right uh but we will be introducing a separate step later on where we will be dry we will be doing a dry run what is greatest we can look up for things we don't know because this is in no way contributing to what we are doing as uh What uh the solution we are building right this is a piece of fact so it shows that uh okay this person has uh is looking into the edge cases so that's a good thing and then finally giving providing the interviewer with the space and time complexities so thank you for listening to me this is B Mox and we will be back with other videos soon
|
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
|
151
|
let's discuss a programming question reverse words in a string so the problem statement is given an input string and we have to reverse the string word by word so in this problem we have given input a string and we have to reverse the string word by word so let's uh take few examples to understand this problem statement so in the first example the input string is the sky is blue so we have to reverse the string word by word what it means is so the blue uh will come first then s then sky and then uh so basically uh the words uh the character in a word is not reversed the complete word will be reversed so blue will come first then is then sky and then d so in the second example uh so we have the leading and trailing spaces and then the string which is hello world so world is a complete word it will come first world width exclamation mark then hello and hello comes here so when we reverse a string so it should not contain leading or trailing spaces so we have to remove this leading and trailing spaces now let's uh see the third example in the third example the input string is a good so yeah here is the multiple spaces and then example so when we reverse this string the example comes first then single space then good then a so when we reverse our string so we have to reduce multiple spaces between two words to a single space in the reverse string so we have to take care these conditions uh these cases while do while reversing a string word by word and here are few important points so word is defined as a sequence of non-space characters so non-space characters so non-space characters so it is clear then the second point is input string may contain leading or trailing spaces how where however your reverse string should not contain leading or trailing spaces so we have already seen in example two and in the third point you need to reduce multiple spaces between two words to a single space in the reverse string so this point we have already covered in the example uh in the third example so this is the problem statement and now let's discuss multiple approaches to solve this problem now let's discuss how we can solve this problem using two pointers so the idea here is to take two pointer pointers one is pointing at the beginning of the word and other pointer points to the end of the word and then we traverse the string and when we encounter space we insert them in a string bundlers so let's visualize uh the complete process so uh i have declared one string and this string is java ebook and so in this string so there is leading space and there is a trailing space so now we know its output and its output is first ebook come and then one space and then java so the output is the string which is e-book the output is the string which is e-book the output is the string which is e-book and java and the this reverse string does not contain any leading and trailing spaces so how we can solve this uh using two pointers so now let's say one pointer is start i'm in short form i am writing as s and one pointer is i so what we can do is whenever we encounter space we keep moving this start pointer and now when we encounter non-space and now when we encounter non-space and now when we encounter non-space character so start pointer remain as it is and this i pointer will keep moving until it does not encounter any space so it moves ah it goes here then it goes here now it when it points at this uh this character so it is non-space so it this character so it is non-space so it this character so it is non-space so it is space character so what we can do is we can take this substring and we can insert them in a string builder so first java is inserted and we insert them at zeroth offset so what it means is you will understand shortly then now what we can do is so in next iteration again so we encounter so till now we traverse this string at this point now in next iteration so when the value of i is incremented it will point at this index now start will point at this index and again we move i until this space is encounter so again we take this substring so we take this substring and we insert them with space so here space and this string so now finally now after in next iteration uh it moves at next index which is space so it will continue moving and now so the value of i so this loop will run if the value of i is less than a string length now so this condition is not satisfied and we came out of this loop and we finally return this final string which is reverse word by word and now let's see the code so here i have declared string builder and now i am traversing this string and the value of i start from zeroth index and here is the condition so we move so now we start from uh the character which is present at zeroth index so it is a space character so we keep so we continue what it means is so we move to next iteration from this step so this is a space so we move to next iteration now the value of i is 0 in next iteration it is 1 again it has a space we move to next iteration now it is j so in start pointers we assign the value of j now the value of j is 2 so and we run this loop and we keep incrementing the value until it encounter space so we keep incrementing the value of i so i will move to this step then this so till this point this s and i pointer points at this index now we have to uh keep as s at s as it is so at s stands for start pointer so as start pointer as it is and we keep moving i so we keep moving i until it encounters this space then we came out of this loop and we take this word and if we have not inserted any word in a string builder it means its length is zero so we insert this uh java at zeroth offset and in next iteration again the i will start from this point and uh the start pointer so we assign the value of i to start pointer it means s will start pointer will now points at this index and we do the same process we keep incrementing the value of i until in it encounters a space and then now we have already put java in a string builder so this else condition will run so first we insert so let's say initially we put java now we first put space so space and then we put this string which is e-book so this string which is e-book so this string which is e-book so ebook now you can see and after that in next iteration uh so there is uh two trailing spaces so we keep continue from this step and then we came out of this loop and we return this string which is a reverse word by word now let's discuss our second approach in which we will solve this problem using inbuilt functions now let's understand our second approach and what these three line does so the idea here is to first split this string into an array of words and here i am using the regex and what it does is basically if there are more than one spaces in a string so it will not create multiple words so if you use split without this regex so this string will be splitted like this so at zeroth index it is the empty word then java and then ebook and then again the empty word so if we use this split without this regex so it will split like this so if we use only this space this empty so this is one space without this plus so it will split like this so we have used this as uh plus so that if in a string if there are more than one spaces it will not create multiple words then so now the word will be uh the string will be split like this java and then ebook then we are reversing uh this array so we are reversing the array of words so it so at this step the array will look like this after this step the array will look like ebook and java and after that so at the end we are joining uh the words so ebook then this delimiter and the delimiter is space so space and then java and finally we are returning this string so we get this string and we are returning this string using the these three line of codes we have solved this problem so in this uh tutorial i have explained two approaches to solve this problem and if you know any other approach to solve this problem you can let us know through your comments and that's it for this video tutorial for more such programming videos you can subscribe our youtube channel you can visit our website which is https thanks for watching this thanks for watching this thanks for watching this video and please don't forget to like this video
|
Reverse Words in a String
|
reverse-words-in-a-string
|
Given an input string `s`, reverse the order of the **words**.
A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space.
Return _a string of the words in reverse order concatenated by a single space._
**Note** that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.
**Example 1:**
**Input:** s = "the sky is blue "
**Output:** "blue is sky the "
**Example 2:**
**Input:** s = " hello world "
**Output:** "world hello "
**Explanation:** Your reversed string should not contain leading or trailing spaces.
**Example 3:**
**Input:** s = "a good example "
**Output:** "example good a "
**Explanation:** You need to reduce multiple spaces between two words to a single space in the reversed string.
**Constraints:**
* `1 <= s.length <= 104`
* `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`.
* There is **at least one** word in `s`.
**Follow-up:** If the string data type is mutable in your language, can you solve it **in-place** with `O(1)` extra space?
| null |
Two Pointers,String
|
Medium
|
186
|
375
|
everyone welcome to my channel so in this video i'm going to cover the solution to this question and at the same time do some lab coding work i'm also going to follow the general stuff so you should follow in the coding interview when we solve this problem so let's get started before we start the real content for today i would really appreciate that if you can help subscribe this channel so let's first resort this problem you're playing the guessing game so the game will work as follows i pick a number between 1 and 10 and you guess a number if you get the right number you win the game if you guess the real number then i would tell you whether the number i picked is higher or lower and you will continue the guess every time you guess the real number x you will pay x dollars if you round the money then you lose the game so given a particular end return the minimum amount of the money you need to guarantee a win regardless of what number i pick so let's take a look at the example it says that n is equal to 10 we need the minimum amount of the dollars in the pocket is 16. so let's see the constraints the concern says that n is anywhere between one two hundred so i think we pretty much understand what the problem is asking us to do not too much to think about edge case so actually it seems to be like a binary search but it's not like a traditional binary search question that is because uh it is not like asking us to search something within the array instead it's asking us to see what is the minimum word cost to search this thing this kind of stuff so um let's see how to solve this problem so i think one profile solution which is pretty obvious is um what we could do is we can do like an exhaustive search um when i say exhaustive search is something like a newer and other pivot so for example when i say when we get the keywords when we choose the p17 uh we need to search in the left part or the red part depending on which number we are going to choose so suppose the function we define like a dfs function we define is going to return the minimum amount of the money we need to have in pocket to guarantee a win when we search within a range from idj then it's something like when we search the left part we have the minimum amount of the money we need when we choose people that are seven i mean we have similarly you have the minimum amount of money we need to guarantee a win when we choose uh when we search the number within the right part so essentially when we choose p17 is pretty much like a 7 plus whichever is more costly uh on the left part or the red part and then we enumerate all of the pivots and decrease the minimum amount among all of the people we choose so essentially this kind of the question is choosing the minimum among all of the maxima so having said that the profile solution is not actually good regarding the runtime uh wasting a lot of the competing resource uh recomputing the solution to the same problem so instead all you could do is we could use dynamic programming to actually uh memorize the solution to the sub problem and then use reuse it to recompose uh to compose the solution of the original problem so for the dp if you usually go bottom up but it's okay to go top down as well but if you choose to go bottom up we need to define like the dpr right here so here the array is actually a matrix so let's let me define like a dpij is the minimum amount of money needed to guarantee a win when searching within i and j so that's how we define the dpij and how to compute the dpij so the dp formula dpij is actually uh suppose i is so when i is equal to j then it is like a zero because we know that we are searching within i and i then it's essentially we know the number what the number is so um let's see um so dpij is uh actually like i said it is a minimum ammo on all of the maximum suppose i just choose a pivot um and uh the p but it should be something like research on the live part which is i pivot minus one and then okay so this should be like a mass dot max so the maximum among whether we search on the right part or why the research on the left part so this would be something like pivot plus one to j so that's essentially the formula dp formula we are going to use to uh to compute this problem so having said that the runtime is going to be n squared that's because we have two layers of the for loop outside and then within and the inner for loop is actually we will need to enable all of the pivots so that makes the runtime to be n cubed and the space wise is going to be n squared that's because this is like a 2d array we are going to uh to have so having said that let's actually do some coding work on this approach so first of all we need to define the dp array so let's say have like the dp area as and plus one and m plus one and then finally what we do is we just return dt one to n and that's pretty much it and uh then it comes to the rest of the combination as i said it's like two layers of for loop so since this one um it's actually enumerating all of the middle points so instead so we cannot actually do a uh do a like a first layer is i uh second layer is j we cannot do that otherwise we are going to get the wrong answer just that we need to like enumerate all of the lens uh so when i see the lens is actually the distance between i and j so i'll say i would just say the lens is two starting from two like we try to include two numbers um and then lens is anywhere from two to n plus the length and then we are going to have like go into let's call it instead of i let's call it a start which makes it more meaningful so start is actually anywhere from one and starts should be smaller or equal to this is uh and minus the lens so if it is n minus lens plus one okay and the plus the start uh and then the n is so n is actually the j here so i just give it uh a more meaningful uh name so start plus lens minus one so this is the lens so let's say we have yeah so it should be it should work so this is the start and this is the lens and the rest of the job is the first two numeral pivot so p is equal to uh well this should be starting from start pivot is smaller equal to end plus the pivot and dp uh we need to have like something uh at the first place because we are trying to get the minimum of that so let's say we have the carbon defined as integer dot max volume so current man is among all the minimum apartment this is pivots plus the second choice is the pivot plus i said it's like the maximum among the right part or the left part dp so the left part is i which starts to pivot minus one the right part is py plus one to the end and then finally we are just going to have like dpij or dp start to end set as cardman so that's pretty much it let's try to do some debugging work on this platform okay so it says that it is out of the range okay so that i think that's because we have the p of plus one and the p it could be uh like equal to the end so that's uh that's essentially why it is wrong so instead what we could do is like we could define this we can add another dimension on top of this i think this can solve this problem all right so let's do some more testing all right so it seems like it takes uh some time all right so accepted let's do a submission for it all right so it seems like we are done with this problem and uh we are good hearing pretty much in good shape if you have any questions regarding the solution or regarding the code uh feel free to leave some comments below if you like this video please help us with this channel i'll see you next time thanks for watching
|
Guess Number Higher or Lower II
|
guess-number-higher-or-lower-ii
|
We are playing the Guessing Game. The game will work as follows:
1. I pick a number between `1` and `n`.
2. You guess a number.
3. If you guess the right number, **you win the game**.
4. If you guess the wrong number, then I will tell you whether the number I picked is **higher or lower**, and you will continue guessing.
5. Every time you guess a wrong number `x`, you will pay `x` dollars. If you run out of money, **you lose the game**.
Given a particular `n`, return _the minimum amount of money you need to **guarantee a win regardless of what number I pick**_.
**Example 1:**
**Input:** n = 10
**Output:** 16
**Explanation:** The winning strategy is as follows:
- The range is \[1,10\]. Guess 7.
- If this is my number, your total is $0. Otherwise, you pay $7.
- If my number is higher, the range is \[8,10\]. Guess 9.
- If this is my number, your total is $7. Otherwise, you pay $9.
- If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.
- If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.
- If my number is lower, the range is \[1,6\]. Guess 3.
- If this is my number, your total is $7. Otherwise, you pay $3.
- If my number is higher, the range is \[4,6\]. Guess 5.
- If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.
- If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.
- If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.
- If my number is lower, the range is \[1,2\]. Guess 1.
- If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.
- If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11.
The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.
**Example 2:**
**Input:** n = 1
**Output:** 0
**Explanation:** There is only one possible number, so you can guess 1 and not have to pay anything.
**Example 3:**
**Input:** n = 2
**Output:** 1
**Explanation:** There are two possible numbers, 1 and 2.
- Guess 1.
- If this is my number, your total is $0. Otherwise, you pay $1.
- If my number is higher, it must be 2. Guess 2. Your total is $1.
The worst case is that you pay $1.
**Constraints:**
* `1 <= n <= 200`
|
The best strategy to play the game is to minimize the maximum loss you could possibly face. Another strategy is to minimize the expected loss. Here, we are interested in the first scenario. Take a small example (n = 3). What do you end up paying in the worst case? Check out this article if you're still stuck. The purely recursive implementation of minimax would be worthless for even a small n. You MUST use dynamic programming. As a follow-up, how would you modify your code to solve the problem of minimizing the expected loss, instead of the worst-case loss?
|
Math,Dynamic Programming,Game Theory
|
Medium
|
294,374,464,658
|
26
|
in this video we'll be going over remove duplicates from sorted array so given assorted array numbers remove the duplicates in place such that a new element appear only once and return the new life do not allocate extra space for another array you must do this by modifying the input array in place and over one actual memory so in the first example we're given one two so when we remove the duplicates one we get one and two and then our i mean the length of the output list will be equal to two so we output two let's first go over the dot process and we can implement a two pointer approach one pointer i will be used to populate unique numbers and then one pointer j will scan forward to find unique numbers we should note that we should know that the input array is sorted in ascending order this means all of the duplicate numbers are grouped together after we have accounted for the elements at nums j we will want to skip all of the future elements that is equal to nums j after we have processed all of the numbers with pointer j the value of i will determine the size of the output array without duplicates let's go over pseudocode so we'll create a variable i to keep track of our current left pointer or to keep track of our to keep track of the current location we are populating then we iterate through the impulse indices of the impulse denoted sj that will populate nums j at nums i this is a unique number so we populate the numbers i and then we'll increment i now we will need to skip all of the duplicate elements so while j is not at the last index and the next number so j plus 1 is equal to the current number j we want to skip that number so we increment j after we process all the numbers of j we can return i the length of the new array without duplicates let's go over the time is time and space complexity so time complexity is of n where n is the length of the input ray so if o n visit each index once and space complexity is off one because we do not create a new data structure to hold on elements we just modify the array in place now we can go over the code then we iterate through the indices of the input array place the unique elements at i and we want to skip all duplicate elements then return i the length of the new array let me know if you have any questions in the comment section below
|
Remove Duplicates from Sorted Array
|
remove-duplicates-from-sorted-array
|
Given an integer array `nums` sorted in **non-decreasing order**, remove the duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears only **once**. The **relative order** of the elements should be kept the **same**. Then return _the number of unique elements in_ `nums`.
Consider the number of unique elements of `nums` be `k`, to get accepted, you need to do the following things:
* Change the array `nums` such that the first `k` elements of `nums` contain the unique elements in the order they were present in `nums` initially. The remaining elements of `nums` are not important as well as the size of `nums`.
* Return `k`.
**Custom Judge:**
The judge will test your solution with the following code:
int\[\] nums = \[...\]; // Input array
int\[\] expectedNums = \[...\]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums\[i\] == expectedNums\[i\];
}
If all assertions pass, then your solution will be **accepted**.
**Example 1:**
**Input:** nums = \[1,1,2\]
**Output:** 2, nums = \[1,2,\_\]
**Explanation:** Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Example 2:**
**Input:** nums = \[0,0,1,1,1,2,2,3,3,4\]
**Output:** 5, nums = \[0,1,2,3,4,\_,\_,\_,\_,\_\]
**Explanation:** Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-100 <= nums[i] <= 100`
* `nums` is sorted in **non-decreasing** order.
|
In this problem, the key point to focus on is the input array being sorted. As far as duplicate elements are concerned, what is their positioning in the array when the given array is sorted? Look at the image above for the answer. If we know the position of one of the elements, do we also know the positioning of all the duplicate elements? We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. So, we ought to use a two-pointer approach here. One, that would keep track of the current element in the original array and another one for just the unique elements. Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element.
|
Array,Two Pointers
|
Easy
|
27,80
|
731
|
hello friends now lessors really similar questions my calendar to in my calendar three so our employment my calendar crass system your events a new event can be added if adding the event will not cause a double booking so you see we will call a master to name the book and there have start and end time if we can book that event we return true if not we return force once the event has a conflict with previous events let's see this example mmm first we booked her event from 10 to 20 we return true then we try to book 15 to 25 return false because you see if Ron's at time 15 to 20 we already booked us or if we try to put again we just return false so that means when we try to book an event we need to know it's a previous event and its next event to see whether we have enough space to book the event so we paid her use a data structure to save their older event let's say we saved their time of these events and there is a good idea structure in Java there is tree map or tree set so let's think whether we needed to use a tree map as their tree set if we only save the start time we also need a know when it ends so we have to use a tree map and the key will be its start and very well beats end time and when we try to book event we will first get its previous event and its next our following event if the current list item is later than previous events in time and the current end time is earlier the answer following events start and I will we will return to an darrell's any event into our counter otherwise we return false so okay that's a write code we will use a tree map it will be integer we never need to book and we will initialize it put a new tree map then we will capture its previous time and the fallen tab we should write integer because there may it may be known so it will previous you got you booked yet start and there next you got you booked get her enter we need to make sure the current event has no conflict with previous and dirt their next event so it is should be end if previous event is no or we can his endtime book to get prison time is less or equal then a start time and their next time equal to naught or book - oh no because we just need to book - oh no because we just need to book - oh no because we just need to compare the start time so the next is greater then enter we have to return true but before that we need that you put that event into our tree map data will be start and under enter otherwise return force no it's wrong um let's organize our time yes oh sorry this should be start because we just saved their start ha now save their end time I made a mistake because the previous should be the flow floaty not just a gap so every froakie because the previous so you should be its flow so if Loki start and next there shouldn't be there sealing key great oil eco against sitting is sealing is greater than sir start time okay let's see the next question there should be my cannon to chew in this question are true if we trigger a Tribble who can we return for otherwise which I return sure that means we can book one time twice so this is ten twenty will return true and fifty six or ten sure and 1040 we also return sure but if we try to pick five fifteen will enforce so can we still use a treemap to solve this question the answer is yes but the difference is in this time we can book one time twice so we need to save the frequency of an event so it seems like her folder tree map the key will be attacked also a startup but this value seems to be a frequency but we also needed to save their anthem so how do we combine these two requirements because we need to take use of the older feature of the tree map so weight is a starter we let Lucas plus one but when the key is the end time we just let the value frequency minus one so that means when you meet a start-up we that means when you meet a start-up we that means when you meet a start-up we know they're active events increment by one but when we meet a anytime we know we can decree meant active events so we just need to check whether sir we have a active investor is greater or equal than three is yes we trigger a triple booking so we cannot book that event so our algorithm is we use a tree map to save their time point and it's a responding frequency and then when we try to book a event we first change the frequency we make the start time frequency plus one max is our end time frequence minus one and we iterate the other frequency and accumulates at that frequency was an active event secret code and three we return force and there we deep Buchta we unhooked at that event so let's write it there will be three map also integer and integer there will be booked and there will initialize it I've booked a new tree map okay we will try to books that put your start and they're booked yet or default there will be start and zero plus one and the book to put her in time doctor yet or default and zero minus one okay we also needed to accumulate that actively events equal to zero then we either it order frequency in their book to values active events plus frequency if the active events is greater than 3 we unhooked that event because we cannot focus that we let the start time doctor yet further start - 1 right because we yet further start - 1 right because we yet further start - 1 right because we +1 each time we - one in the book - food +1 each time we - one in the book - food +1 each time we - one in the book - food and time there will be book to get in time plus 1 and the way return force if not we return true oh yeah we return boolean yeah okay for the third question which I needed you because you don't want to get to there k is the comment you okay because that means our return 1 and this is also return 1 they returned to because between the time 10 to the 20 we have two events so it didn't just need to return the maximum booking largest integers are exist ok booking the counter so we just needed to change the serve this part we will get a max and every time we need some Q plus in frequency if their sum is greater than the max we update the max so final generator max okay thank you for watching see you next time
|
My Calendar II
|
my-calendar-ii
|
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **triple booking**.
A **triple booking** happens when three events have some non-empty intersection (i.e., some moment is common to all the three events.).
The event can be represented as a pair of integers `start` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`.
Implement the `MyCalendarTwo` class:
* `MyCalendarTwo()` Initializes the calendar object.
* `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **triple booking**. Otherwise, return `false` and do not add the event to the calendar.
**Example 1:**
**Input**
\[ "MyCalendarTwo ", "book ", "book ", "book ", "book ", "book ", "book "\]
\[\[\], \[10, 20\], \[50, 60\], \[10, 40\], \[5, 15\], \[5, 10\], \[25, 55\]\]
**Output**
\[null, true, true, true, false, true, true\]
**Explanation**
MyCalendarTwo myCalendarTwo = new MyCalendarTwo();
myCalendarTwo.book(10, 20); // return True, The event can be booked.
myCalendarTwo.book(50, 60); // return True, The event can be booked.
myCalendarTwo.book(10, 40); // return True, The event can be double booked.
myCalendarTwo.book(5, 15); // return False, The event cannot be booked, because it would result in a triple booking.
myCalendarTwo.book(5, 10); // return True, The event can be booked, as it does not use time 10 which is already double booked.
myCalendarTwo.book(25, 55); // return True, The event can be booked, as the time in \[25, 40) will be double booked with the third event, the time \[40, 50) will be single booked, and the time \[50, 55) will be double booked with the second event.
**Constraints:**
* `0 <= start < end <= 109`
* At most `1000` calls will be made to `book`.
|
Store two sorted lists of intervals: one list will be all times that are at least single booked, and another list will be all times that are definitely double booked. If none of the double bookings conflict, then the booking will succeed, and you should update your single and double bookings accordingly.
|
Design,Segment Tree,Ordered Set
|
Medium
|
729,732
|
252
|
hello everyone in this video we're going to be doing leak code problem 252 which is meeting rooms so this is an easy problem and it states given an array of meeting times intervals where intervals I equals the start and end time determine if a person could attend all meetings so in example one here we have these three intervals and the first interval covers 0 to 30 which there's no way you can attend five and 10 and 1550 and 20 when this one encompasses both those meeting times or overlaps so that's false now here we have seven and 10 and two and four now you can definitely go to the two to four meeting before you go to the 710 so that is true and to code this is actually fairly straightforward so they give us the array of arrays called intervals and we're going to pass back a Boolean true or false the first thing we want to do is sort these intervals sort these arrays and the Syntax for that is basically you pass in the intervals and then you call the compare rators comparing int method and that passes in an inch array and this is Lambda expression so this is basically just a syntax that you need to learn for the comparing int method or the method uh starts at a Zer and it's going to Loop through and compare everything so just by running this one command we'll sort all these intervals then we need to Loop through the intervals that are now sorted so basically if the interval at position zero so we're to start with i equals z so if the position one which is basically the meeting this end time is greater than the start time of the meeting right after it then you're going to return false because you can't end the meeting before you start the next one or yeah you can't end you can't start the next meeting while the first meaning is still going on otherwise we're going to return true and that is pretty much the entire method fairly straightforward let's debug this and I'll show you exactly how this works so I did the first example 0 to 30 15 20 and 5 to 10 so we pass that in you'll notice the first thing it does so look at here the intervals are 0 30 15 20 and 5 and 10 exactly how they uh written up here so now when I do just did the comparator method there now they're in oh s they're already n okay now sorry psyched myself up now they're in order based on start time so 030 510 and 1520 we're here at 030 1520 and 510 all right so now we need to go through so interval I of one so if you look here interval I is zero interval one is 30 or I'm sorry index one is 30 if that's greater than I + one so that's one and index zero so if 30 is greater than five you're can return false which is exactly what it what happens so returns false there now let's try it again with uh the second example I'll run that and again you've got s 10 and two and four but just running this compare comparing in method now we've got 2 4710 and they're sorted based on start time so this is basically saying interval 01 which is going to be interval zero position one is going to be four comparing it 2 I + one so to be four comparing it 2 I + one so to be four comparing it 2 I + one so which is one interval zero so four is greater than seven which It Isn't So then and that's the only thing we need to compare there's only two meetings and so that will return true that is pretty much all we need to do let's run this through leite code see what we get whoops o if I put the code in there that is successful in start time or submitted time looks like we're not Hing any faster than 33% 33% 33% and 39 megabytes less than 44% all right so let's go through the 44% all right so let's go through the 44% all right so let's go through the space and time complexity okay time complexity we take a hit there because we have to sort the arrays so if we were just going if we're just looping through the arrays it would be over but because we have to sort the Rays it's going to be n login which is this line right here but the space complexity is just one which is this green line down here we're not adding any more space to run this solution and that is it so thanks again for watching let me know if you have questions and we'll see you next time
|
Meeting Rooms
|
meeting-rooms
|
Given an array of meeting time `intervals` where `intervals[i] = [starti, endi]`, determine if a person could attend all meetings.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** false
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** true
**Constraints:**
* `0 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti < endi <= 106`
| null |
Array,Sorting
|
Easy
|
56,253
|
224
|
cool 2:24 basic calculator implement a cool 2:24 basic calculator implement a cool 2:24 basic calculator implement a basic calculator to you elevate a simple expression string the expression string may contain open and closing friends parentheses the plus or minus sign non-negative integers and empty spaces non-negative integers and empty spaces non-negative integers and empty spaces why it's not a good they get spaces oh and empty spaces right okay who do not use to you go in function I guess that makes sense because I thinking like JavaScript or something like that like you just thinking about and in groovy or something and that'll kind of make this trivia okay you know these things are always tough especially we can an interview and I think I've seen variations of this on an interview but usually did not just they give you know we wish reverse polish notation which is very easier because you could do everything in one stack and stuff like this but a like could in fix as always that they were tricky but this one is pretty straightforward so it's something that like most people should have seen before and it's just and this one I think there's a this one is actually a bit easier in the sense that didn't know but these are observations I'm noticing where there's no consideration for order of operations because I plus and minus are on the same the only thing that makes it trickiest prevents but you can actually because of that reason you can actually yeah figure that out and I would do something a couple ways to do it you could do it with a stack especially in this case it seems pretty okay you could do with recursive descent which is always fun yeah I guess I would just do it with weaker septa sign type Frank Whittle recursion we Croatian like it's not funny because it's that but uh okay because I think everything is where you go I guess you just do a wrist ACK yeah that's just sort of a stack okay let me actually first replace all the empty spaces and now we can just I think the other thing that they don't tell you is mmm that may be a little bit tricky and they don't show you an example of this it's kind of numbers with multi digit numbers definitely something that maybe is a little troubling Tepera how do you throw in anyway yeah okay I gotta remember not to use wild loops or folders because I feel like I do silly things okay so now let's say we okay so now we want to take Kearney okay so then we push the current number in it I guess is a little weird actually or like in the beginning because then you there's no operation so then stop number would just continue to be on the stack I guess this is a rather strange okay mmm-hmm let me be more precise and I'm mmm-hmm let me be more precise and I'm mmm-hmm let me be more precise and I'm gonna do a zero balance okay otherwise then we have two current aptitude this is a little weird mmm maybe the way I'm talking it's a little weird actually I mean I guess I'm just doing it in position okay I'm gonna do it with a natural stack maybe I mean an implicit stack they're not keep my states a little bit easier to maintain okay naming is hard it's to calc now give me an index we want to yeah okay I mean maybe I think that every recursion is DFS it pissed me off a little bit when everyone yet everyone neighbors every recursions fingers Deva DFS but I get your point okay if - this return I would say this should be returned Cal index quest one that's why because I do need a corporal ething it's been a while since I'm from that stuff like this actually and then it's more like that they turn cooler now okay now gets a fun part index if you could that's let's get number can um oh yeah and now here my job is given in current index hmm naming pigs is so hard that's time trouble and index finger the index Wow oops this is where you have a Proctor I said that as I make a typo but sorry you can start a no negative numbers you're naming it's all right mm-hmm in this case I'm instead I'm not terminating somewhere what is the count I know I do I know spaces ready so it's everything I was always increments so everything should be moving forward plus today huh yes technically this might be pricing well that's right hmm yeah that one that part is right oh I just don't do anything of it starts about number okay so that's difficult about that case okay so well in this case we don't need things for you cause you again number starting of an expression okay one thing I would also say that and I've gone unfortunately good about this is learning to debug but I say this is I have to demonstrate this a little bit but here's something that is actually why your bow in an interview I asked about that over time so it's something that I think about me and all of us have done it before so yeah because of course the better way is to get it right the first time which is easier said than done but uh okay one two three why I'm not hitting here dad it's weird oh because I took Plus and then I get the next one okay I guess that's fair I did not handle that case hmm I actually got ya have you gone down interview once and I think I didn't express myself super well but by god the Barga which is like i'll yeah this is clearly wrong cuz you're full up sir we worse or something like that but hmm I guess when you pass it doesn't always have to be a number so I mean maybe this is better no but then view actually we had a number they're nuts okay let's just take a look and see what happens oh no -1 -1 Y 2 minus 1 plus happens oh no -1 -1 Y 2 minus 1 plus happens oh no -1 -1 Y 2 minus 1 plus 2 is definitely 300 cuz mmm okay so maybe that's too aggressive cause it takes the entire finger hmm but that now is treating the entire thing as a suffix hmm which can be a thing like for example which I want to put it an example but like 3 minus 1 plus 2 should actually be 0 but every time to be a little bit smaller I don't like pauses enough yeah maybe I need to practice out Nick's okay but that part is behead but for the same reasons - at the next point Wow how do I ensure that this only had for the next entity but only of the next entity is not a prevent hmm that's a tricky one I guess I could just check it out don't cry know me from the bahai or adidas quite this check I guess it could only be after paisa going to be numbers of program but this is now getting ugly there's tough ways some opportunities for drying myself as well let's see nothing we're close even if it's very yaki there some complicated cases that I want to try what should the hens it be actually 5 minus 3 is 2 minus negative 1 is 2 e yeah and by N's as well because it now assumes that it's the same as this which is not that is interesting okay and that's why you stick to establish patterns huh how do I fix that then we have two paper yeah how does this work well we just won it doesn't negative that's one plus two but then it should end here and then we should pop but I am doing something silly quickly I guess I shaft on it a little bit better with the recursive descent just thinking about how I wanted it fix this really once and I know what it's doing why is it doing that yes I just don't match the friends correctly at the end of the day should we turn no hey thanks for the follower GC Bourbon I'll put it in whoops hope you have a good day what University ah I graduated University a number of years ago so but I am just practicing doing some wraps I'll be having a good day oh did I think someone told me to make it short as I try to make it shorter but I don't know these things so well yeah I have a lot of years of experience and I don't need to say there's a braggy kind of way I'm just you know but uh yeah Stastny Road and then to been nice to return why doesn't this happen does this happen Oh nobody's haha no I'm yeah is if you're confused that means it's my I didn't do a good job of making myself clear so no worries I don't take revenge on it at all I also get the other thing where I look young I get that as a comment a lot so yeah no worries ah no ma'am I think right now I'm just in general try to find what somebody that's a good fit what I'm popping both good times your same index yeah ma'am right now I'm just practicing general trying to find something that's a good fit nothing really specific try to figure out what to do in my life in general perhaps but uh yes one does from time to time I guess this pops thirteen and then again well because then now whilst at the end so that it had goes all the way back up hmm Chris I get it because I'm using calc assuming that or like when I vote this has a presumption that it started with that for n so if it doesn't because I do this hacky thing it doesn't pop enough okay it's that make sense hmm oh no worries thank you oh yeah definitely there's a lot of luck in this world so that we could use as much of it as possible Debbie yeah it was a very lucky chance that got me to my last job so you know such is weird life no but this only happens if actually this only happens if here is a program but I don't we increment maybe that's why okay let's try that cuz we have to eat up a character I should really learn recursive descent it's been a while I think since I do it because I think I'm doing some like hockey thing instead of like passing tokens and then matching stuff my god we read that up it doesn't come up that often but when it does it always makes me a little sad that I'm not as familiar with it because that is actually somewhat practical in that you know people do implement these things all the time so it's good to have a mental model of it anyway so how long did that end up taking me 26 minutes not too bad not too great I know pretty straight for it in understanding this problem I mean it's just implementation except that implementation is like this not big algorithms on this problem but definitely implementations always a little tricky to get all the tokens right and this is a case where like everything is well-formed I think if everything is well-formed I think if everything is well-formed I think if it's not Danny could be really messy in I made assumptions here that you couldn't get away with so I think one thing about this my comment in general is that so I have back actually gotten an interview question like a bio I would say and this was in the finance days so quite like I was like 15 years ago or something like that on parsers I think these things are very important parsing is something that some people really like especially of you in turn Malone that was stuff or for whatever that reasoning you have to do some like language parsing thing which is something that I don't advocate at all in general but that's way and yeah and we were into that definitely read up and study up and actually practice a little bit on recursive design but I would also say that find out the best bang for your buck something that I will do because I actually do want to get a little bit better about this because I feel like every time I've seen this was something similar I'm like ow yeah I'm just gonna do this hack here and then we'd have to do a clean way later and it's been a while possibly a decade since I've done it cleanly so I gotta think about it again any spot in fixed type stuff definitely if it gets where usually if you don't like postfix notations or the reverse polish notation stuff like this but yeah but what a fun bomb I mean I look at each character most one so this is linear time you know it's a bit of a mess but yeah cool that's all I have for this one really yeah that is yucky there's my coat is yucky the polymers are fine but yeah actually we cook with solutions we might as well maybe farms about is saying funny following that's good I mean that's what I was that's right I think I mentioned these in the beginning I mean parenthesis I don't know tricky one oh yeah I guess I should have done a stack and then toss out the way that I was kind of doing it but you have to be really careful to do it right we were stack another stack one oh I guess they didn't think about the way I would do it but just I mean to be fair I did use the central using a stack it's just that I did an implicit stack instead of an explicit stack over running grambo so but you can get new troubles so you have to be careful about stuff like this I think they're having the cases as essentially the same except they're much cleaner stuff they have a lot more comment so maybe that's why but same idea though okay cool I just didn't want to deal with putting signs and stuff like this on the stack that's why whether maybe I should have yeah
|
Basic Calculator
|
basic-calculator
|
Given a string `s` representing a valid expression, implement a basic calculator to evaluate it, and return _the result of the evaluation_.
**Note:** You are **not** allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`.
**Example 1:**
**Input:** s = "1 + 1 "
**Output:** 2
**Example 2:**
**Input:** s = " 2-1 + 2 "
**Output:** 3
**Example 3:**
**Input:** s = "(1+(4+5+2)-3)+(6+8) "
**Output:** 23
**Constraints:**
* `1 <= s.length <= 3 * 105`
* `s` consists of digits, `'+'`, `'-'`, `'('`, `')'`, and `' '`.
* `s` represents a valid expression.
* `'+'` is **not** used as a unary operation (i.e., `"+1 "` and `"+(2 + 3) "` is invalid).
* `'-'` could be used as a unary operation (i.e., `"-1 "` and `"-(2 + 3) "` is valid).
* There will be no two consecutive operators in the input.
* Every number and running calculation will fit in a signed 32-bit integer.
| null |
Math,String,Stack,Recursion
|
Hard
|
150,227,241,282,785,2147,2328
|
589
|
what's up nerds welcome back to tee time with your favorite software engineer if you guys haven't already subscribe and join my slack channel i have the link in the description i post um leco questions every day for us to discuss and solve so today i'm going over nre tree pre-order traversal i'm nre tree pre-order traversal i'm nre tree pre-order traversal i'm actually going to do this recursively first and then iteratively i don't think it's as easy as some people make it out to be but so let's jump right into it given an nra tree return the pre-order traversal nra tree return the pre-order traversal nra tree return the pre-order traversal of its nodes values so pre-order is in case you guys don't so pre-order is in case you guys don't so pre-order is in case you guys don't know they want us to return it in order of so when you pass the left side of the node um that's when you add it to the list so we do one and then we pass the left side of three we'd add three five and then we'd add six because we're at the left side so um in order would be when you pass the bottom so in order would be five three six uh two one four um so here we see my track pad is not working good we see we have like i said one three achilles one three five six two four um we're going through the left side so whenever we patch the left side we add it to the list so let's solve this problem um recursively we're just going to have a helper function hi so let's create a linked list we know we need to return this integer so that's how it list equals and then we just want to return our helper function that we're going to write and we're going to pass it root and list we're going to be returning list so here's our helper function we know we need to return a list again so helper node root oops and then a linked list with integers okay so the first thing is if this is if the node is root is null then we just want to return the list that means we when we're checking the children um we're not going to add anything so if root this is our base case we just return list and then so pre-order where pre-order where pre-order where as soon as we pass it we want to add well we have uh root we want to add it right away so let's add the value to the list because we know we're adding it on the left side so we do list dot add root dot val and so what's the correct order for this recursively so we're supposed to add three so we want to check the children and then add them so let's check all of the children we're gonna do this recursively so let's do four node and let's call it child we're gonna loop through all the children in root.children so this is looping in root.children so this is looping in root.children so this is looping through these three it's so what it's going to do is after we write the recursion so i believe it's just helper root and child and we just want to return the list at the end because we need to return a list so what this is doing is it's passing in the child first so the children are three to four it's going to um call the recursive function for three first because it's the first child and then it's going to add it and then it's going to call the recursive function for the child so it's going to add 5 or it's going to recursively call 5 and then add it because we go up here so that's how that works um pretty simple recursively i'm going to do it iteratively right after this if my mouse pad would work and i messed something up node cannot be converted to oh i okay so this is child and then this that was a dumb mistake and there we go okay there you have it and now i'm going to jump into it recursively okay so i have my ipad open now um this one's going to be a little bit more visual so we're going to go over it iteratively so obviously we're going to need a data structure to store them in and pass them into the our answer array um or a list as in the right order so let's go over the problem to figure out what data structure we should use um we know that we want to add one right away so if we add one here and then push it into here one so that's the easy part and then we're gonna do the children so if we add uh three two and four well the next one is three um so we could go from the back if this is the back to get the three out or um if we do it in reverse order so if we add if we reverse them add four first two and then three and then we can pop three off add it to the answer three that's still in the right order and then we add the three children in the right order so we'd add six and then five so what is this we're popping off the top so it's um last in first out so or no first yeah last in first out so this is a we're gonna use a stack i'm sure you could use a deck here if you wanted to but in this example i'm just going to use a stack so let's do this real quick let's create our stack so we're going to add in the stack we're going to be adding nodes and so i'm going to call it stack and then we want our list so i'm going to use a linked list interface this is going to be enter so this is what we're going to be returning and so the base case is if roots null then we just return list so and then obviously we want to add a add root so stack dot add root and then we're gonna loop through so we're gonna loop through while the stack isn't empty because we have to add all of these into answer so we're just going to loop through um so while the stack is empty is not empty um we're going to want to first we're going to pop the we want to put the root in first so we're going to pop it off so let's create a new node stack dot pot and then we're going to add it to list so this dot add node and then we're going to loop through all of the children in node so i've seen other people use collections that reverse basically what that's doing is it's just reversing the children you could also just go from the back using a simple for loop so that's what i'm going to do node so we're going to do node.children.size node.children.size node.children.size one and i greater than or equal to zero i minus okay so we right now we just have we've added um the root so we're just we just have the one in here um now we're gonna add what we did is we added all the children into the stack and then we're just gonna you know it's gonna loop through this while loop and pop them off in the right order add them in the right order so um stack that add node dot children dot get and it's going to just be i okay and then we just need to return the list and so hopefully this works oh so i always forget this is supposed to be because it's a integer there we go and there you have it so that's both the iterative recursive way to do it um this problem one about to do it iteratively but i also just wanted to go over it recursively so if this video helped you guys smash that like button and i'll see in the next video
|
N-ary Tree Preorder Traversal
|
n-ary-tree-preorder-traversal
|
Given the `root` of an n-ary tree, return _the preorder traversal of its nodes' values_.
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
**Example 1:**
**Input:** root = \[1,null,3,2,4,null,5,6\]
**Output:** \[1,3,5,6,2,4\]
**Example 2:**
**Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\]
**Output:** \[1,2,3,6,7,11,14,4,8,12,5,9,13,10\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `0 <= Node.val <= 104`
* The height of the n-ary tree is less than or equal to `1000`.
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null | null |
Easy
| null |
232
|
hey everyone it's Chaz welcome back to the channel we're going to do another leak code problem in this video we're looking at leak code problem 232 Implement Q using Stacks so the problem says to implement a first in first out Q using only two stacks the implemented queue should support all the functions of a normal queue and Le code gives us some starter code involving the methods push Peak pop and empty and we have to implement those case you're not too familiar with a Q the push method pushes an element that you specify into the back of the que and then the pop method will remove an element from the front of the queue and return it the peak method just Returns the element at the front of the queue it does not remove it from the queue so basically it just Peaks at it or looks at it that's different from the pop method because pop actually removes the element as well and then the empty method simply returns true if the Q is currently empty and false if it's not we're given the rule that you must only use standard operations of a stack so you can push to the top of the stack you can Peak and pop from the top of the stack and you can also check its size and check if it's empty and then the last point is not going to be for us because I'm going to solve this in Java but depending on sometimes there might not be native support for a stack so you're given some additional leeway if that's the case in your language and the constraints are really straightforward if they do give you a number like for the push method it'll just be a number between 1 and n and it also tells you that all of the pop and Peak calls will be valid so we don't have to worry about any situations where there might be a null value or where you might get an exception and then finally they ask us this follow-up they want to know can you this follow-up they want to know can you this follow-up they want to know can you implement the CU such that each operation is amortized in Big O of one or constant time complexity so what does that mean it says in other words performing n operation will take overall Big O of end time even if one of those operations may take longer so other operations will take less time to compensate sort of so the way I think of this is because we're implementing a queue using two stacks if you think about a move taking place or an operation being defined as say a swap between the two stacks like anytime you move a value from one stack to the other they're saying that for example if you had five values in the queue can you get them back out of the queue using five swaps and it's okay if for example maybe it takes all five swaps just to get the first value out but then after that you can get all the remaining values out in constant time so no further swaps are needed then it would take five swaps to get five values out and that's okay so they're asking can you implement the Que in such a way well of course we can so let's do it all right so I'm going to try to solve this one on paper and I've got to be quick because my kitten is going insane so first real quick I probably don't need to explain this to you but let me just show you really quick the difference between a q and a stack to summarize if I add the values 1 2 3 4 5 into a stack I would get them back in reverse order 5 4 3 2 1 and if I put the values 1 2 3 4 5 into a q I would get them in the original order 1 2 3 4 5 our task here is to create the functionality of a queue using two stacks so one very simple way to handle this would be to think of it as having two stacks which I'll just use these little brass rings for my stacks and I'm going to name one of them main let me write that like I actually know how to write here we go and I'm going to call the other one reversed and it's just like it sounds I'm GNA have one stack that I will consider to be my main stack that I'm going to always access from and then a reverse stack that I'll use to perform functions to help me get the correct values out of my main stack one way you might do this and I'll just give you the spoiler now this is not the most efficient way I'm just showing it as an easy way to visualize how this is being done once we do it this way I'll then show you a way that's a little more efficient but for now let's just do it this way so what I might do is if I want to push values onto my Q which is made of two stacks I might move everything off of my main stack then put my new value on the main stack so it ends up on the bottom and then move everything back on top of it so let me show you what I mean by that let's say I want to push a one onto my q and now I want to push a two onto my queue and see I said the kitten was going to be the one the first one to jump up here it turned out it was lucky can I finish my video all right I think it's time for a food break all right and we're back what were we doing okay so we have a one in our que we need to now add a two to the que but we need to do it in a way so that the one is still the first value we can access so I can't just push this onto my main stack that's not going to work because then it's covering the one and I can't access it one thing that I could do is take everything in my main stack and just push it onto the reverse stack so the one would just move over here then push my two onto the main stack and then put everything back from reverse back to main now one is on top and if I go to push the three I can do the same thing move everything from Main to reversed of course that will flip the order then push the three onto Main and then put everything back and the one will always remain on top if I then were to pop from this Q then it would be the one that gets popped that's exactly what I want if I wanted to then push a four move everything from Main to reversed push the four and then move everything back the two stays on top and now anytime I need to access the next value in the Q all I have to do is access whatever's on the main stack so this will work but the problem is it is very slow every time you try to push something into this queue because you have to perform a lot of operations if I need to push this five onto the que well I need to push this two push the three push the four push the five then push the four push the three and push the two that was a lot of work just to get one value into this Q there's a better way so let's reset this and this time I'm going to think of these two stacks a little differently I'm going to consider this one to be my input stack and so this one is my output stack now here's the way it's going to work this time every time I want to push a value into this que I'm just going to push it into the input every time I want to pop a value from this Q I'm going to read it from the output as you can see right now the output is empty so obviously we have to do something first so if we want to remove a value from this Q the first thing we're going to do is check if this stack is empty and if it's not empty I'm just going to read whatever is here right now it is empty so we need to do something so when this stack is empty I'm going to push everything from the input stack into the output stack so it would look something like that then once I've done all of that now I will read whatever is in the output stack in this case it's a one and so I would successfully get the one out of this stack so I mean it's pretty straightforward when there's only one item so let's see what happens when there's more than one let's say I push a one into the que and then I push a two into the que so I said we're going to check if the output stack is empty it is empty when it's empty I'm going to push everything from the input to the output and then read the output so let's push this two push this one and now I can read the one and there it is I have the correct value now what happens if I continue pushing items into this queue let's push the three let's push the four and now I want to access the first value so I'm going to check if this output stack is empty but it's not because it's not empty all I have to do is just read whatever is here and it's a one so I can take my one and everything is fine if I wanted to access the next value in the que check if the output stack is empty it's not empty so just read whatever is there so there's my two everything is fine now I want to get the next value but how about we just push this five onto the que before we do anything else we'll just push it on there now I want to get the next value out of this que so I'm going to read the output stack it's empty whenever this stack is empty I will push everything from the input stack to the output stack so let's push the five push the four and push the three now I can read whatever is at the top of the output stack it's a three and then if I wanted the next one there's the four and if I wanted that last one there's the five everything works and this is faster than the previous method because every value only needed to be moved once throughout the whole process so before when I was using Main and reversed every time I wanted to push a new value I had to move the old one push the new one and then move the old one again every time I had to push a single item I got to move this one then move this one and move that so this one has been moved what like four times already so this is a very slow process but when I do it this other way with input and output I put the one in the queue and then I put the two in the que the one never had to move I put the three in the queue the one never had to move only when I have to read something excuse me lucky only when I have to read the first value like if I want to peek at it or if I want to pop it from the que only then do I finally start moving these values so I can then move the three move the two move the one but notice that I only have to move them once and then I can successfully read this one if I wanted to read the two I could no extra movements are needed if I wanted to push a four I don't have to move these if I wanted to push a five I still don't have to move them and if I want to access the next value in the que all I have to do is read it from the output stack still nothing has to move I can read the three nothing has to move and now that this is empty I will finally move these final two so move the five move the four and then I can read the four and that's the next value in the Q and then finally read the five so there's a lot less shuffling of values using this method before we go I just want to give a shout out this little boy right here he was such a good boy he just stayed on the side he never got in the video hey baby unlike some cats all right so we've seen our algorithm there's only one thing left to do let's code some job all right I'm going to do things a little different for this video I'm actually just going to type the code uh in real time using what we learned from the demonstration on paper so I know I need two stacks and the way I'm going to do it I'm going to use the more efficient method where I have two stacks an input stack and an output stack for the Constructor I'm just going to initialize both of these stacks and then we saw that whenever we push we always pushed to the input stack so let's just Implement that and then for pop what I wanted to do was check if the output stack is empty it turns out I need to do that for both the pop and Peak methods so what I'm going to do is write the peak method first and I'm going to check if the output stack is empty then first of all if it's not empty then I'm just going to peek at whatever is on the top of the output stack but if it is empty I'm going to move everything from the input stack to the output stack and then peek at the output stack while the input stack is not empty while I still have things on the input stack let's just shuffle them over to the output stack so basically I need to push onto the output stack while popping from the input stack and that's how I'll do that and then once I am done moving everything from the input stack to the output stack then I can finally peek at it for the pop method I'm going to perform the Peak method first and once I've done that I know that the value on the top of the output stack is the one that I actually need to pop it's the same one that I just peaked so I'll just pop it and I actually forgot to return this and then to check if our Q is empty I just need to check if both the output stack and the input stack are empty and unless I made a typo everything should be fine so I'm just going to submit and we're good to go all right so that's it for this video make sure to leave a comment down below if you have any questions or any issues about this problem subscribe to the channel for more Elite code and I'll see you next time
|
Implement Queue using Stacks
|
implement-queue-using-stacks
|
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).
Implement the `MyQueue` class:
* `void push(int x)` Pushes element x to the back of the queue.
* `int pop()` Removes the element from the front of the queue and returns it.
* `int peek()` Returns the element at the front of the queue.
* `boolean empty()` Returns `true` if the queue is empty, `false` otherwise.
**Notes:**
* You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid.
* Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
**Example 1:**
**Input**
\[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 1, 1, false\]
**Explanation**
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: \[1\]
myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is \[2\]
myQueue.empty(); // return false
**Constraints:**
* `1 <= x <= 9`
* At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`.
* All the calls to `pop` and `peek` are valid.
**Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
| null |
Stack,Design,Queue
|
Easy
|
225
|
5
|
hey what's up guys Nick Boyd here I did second coding stuff on twitch and YouTube check the description for all my information and do the premium problems on my patreon and you can join my discord reach out to me I'll try and respond everyone I just woke up this is the first problem of the day longest palindrome it is a easy problem got some likes here seems like a really good problem for anyone who doesn't know anything about palindromes just wants to get into algorithms is a good really good starting algorithm out recommend giving us yeah let's just do it given a string which consists of a lowercase and uppercase letters usually it's one of the other but we got a lowercase and uppercase find the length of the longest palindromes that can be built with those letters this is case sensitive for example capital a lowercase a is not considered a palindrome assume the given line the street string will not exceed ten okay so if you guys don't know what a palindrome is a palindrome you might remember something like race car is a palindrome so basically a pound drum can be spelled forward the same way as it can be spelled backwards so racecar spelled forward is RAC e CA are backwards it is also RAC e CA r so race car forwards is a race car backwards so what is the how do we do this it says we want the longest palindrome that we can create from the letters in the string that we're given so we're given in this input example we're given a b c CC DD what is the longest palindrome we can create with these the answer 7 because the longest is d so you take one of the DS then you take two C's then an A then 2 C's then a D so you can see this is spelled forward the same way it's backwards DC c AC c d DCC accd so when approaching a problem like this i guess one thing that i should tell you guys start telling you as the tip that every engineer would give you is that if there's a piece of information in the problem it's probably useful like anything in the problem that specific is probably there for a reason so find the length of the longest palindrome instead of finding the longest palindrome is probably important for a reason and it is because finding the length of the longest palindrome is pretty easy we just have to look at the properties of a palindrome and then we could figure it out so what are the properties well we have a D here and a D here so matching character and then not matching character okay well I guess the only thing that we have to notice is that every character is matching except one character one middle character cannot be matching and that's the only one other than that every other character has to be matching except for the very center because otherwise it wouldn't be spelled the same way forward as backwards if there were different characters somewhere else so we can only accept one different character well if we realize these properties then it's pretty easy after that point all we have to do is okay let's get the count of each character in the string for example there's two DS there's four C's and then all we have to do is we make a count array we put them in and we just say what is if the character count of a current character is even so if there's four if there's two if there's eight then we can add up we could just add that count on to ongoing sum right because if we have you know four if it's divisible by two if we have character that the number of occurrences is even then that can go right into our palindrome if we have two DS that can go into our palindrome somewhere you can just tag them onto the end if we have four C's two of them on each side so we just fill the count and if we go through and if they're even we just add that count on to an ongoing sum so we had four we had two that's six and then in the end if we have Stover if we have one character that's just worth a value of one if that occurs one time or if we have you know three C's or like three B's or something like that we can add that one extra one for the middle so that's pretty much the idea here hopefully you guys know what a char counts array is so HR counts array is just a array to keep track of the number of occurrences of a character we're gonna use ASCII values in this case because we have lowercase and uppercase letters so to do this all we have to do is for char C in string to char array so we loop through all the characters in the string that we're given so this string for example we access the index of the string by just passing in the value C which is the character so just passing in the sea it'll be converted to the ASCII index in this array so if it's a lowercase a it'll say okay char counts of 97 and then we increment the count so we're just counting how many occurrences of each character great now we want to initialize our result like I said this is the ongoing some we're going to loop through each integer in the char counter right now so we could say char count or whatever yeah we could say char count in chart counts and then we would just do this okay if char count is well actually we could do this we could just do result plus equals char count divided by 2 times 2 and what this is going to do is this is going if it was 3 if there were 3 A's and we're looping through it would do 3 divided by 2 which is 1 because this is integer division so we're getting the floor division of 3 divided by 2 so it removes the remainder from the division and then we multiplied by 2 again and we just get 2 so this kind of does the this is just in vision classic integer division to add on any pairs that we see any number that's divisible by two we just add on you know if it was you know eight divided by two is four times two is eight we'd add that on the result because we have eight characters we could put in the palindrome anything divisible by two we could do if it was nine well we would do nine divided by 2 which would count as four times two is eight so we'd add eight on and then what we'll do is in the end if there's a left over one so if result mod 2 is equal to zero so if the result is an even number at the very at any point we can take and char counts mod 2 is equal to one so this will say okay our result we have an even number of characters in the result right now we have a perfect palindrome right now this is like fine but we don't have that extra unique character that we could put in the middle that one extra one well if the current character has a remainder after dividing by two well then that means there's an X either an extra one in the case like three divided by two that would be a remainder one or you know whatever or if it was just a value of one so then we just do result plus equals one and yeah so that should actually be it yeah that's it's a pretty easy problem I might have gone a little bit in depth when I didn't need to necessarily to string dot to char array s to char array sorry can I ever not make a mistake char count we're doing count in the loop there we go so that's it good run time just a linear just linear and yeah thank you guys for watching let me know if you have any questions I want pretty in-depth so I think you should be able in-depth so I think you should be able in-depth so I think you should be able to understand but uh thanks for watching hope you guys enjoy it get good at your palindromes they come up a lot actually an interview so definitely gotta know what a palindrome is you got to know all this math it's just integer division and remainders but I tried to explain it as if this was for beginners anyway talking too much see you guys thanks for watching bye
|
Longest Palindromic Substring
|
longest-palindromic-substring
|
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters.
|
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
|
String,Dynamic Programming
|
Medium
|
214,266,336,516,647
|
106
|
hey everybody this is Larry this is day 16th of the elite code daily challenge in March hit the like button hit the Subscribe button join me on Discord let me know what you think about today's prom uh oh yes which first Tracy get that 10 lead coins uh yeah all right let's get started I hope everyone's having a good week it's really cold here in New York this week so I'm just like I just came from the outside so I'm a little bit uh if I'm sniffing too much my apologies uh okay so today's problem is 106 construct binary from inorder and post order um I mean I think this is a way um I wouldn't say common but it is a very well known problem just because it is one of those things that they teach you in a textbook or something like this um and we'll kind of think about how to do it together I have some of the notes are unique because otherwise it's just you know it's a little bit more Awkward um okay so I think the biggest thing that this teaches is this idea of an invariant right meaning that um you know just trying to keep State and kind of figure out what things mean in each as you kind of make um as you kind of make changes you try to figure out what stays the same that's what an invariant is uh in infancy a word but that's basically and based on that assumption um you know you can create a loop in variant or a recursion in variant or something like this where you can you know solve the problem so this one the invariant uh the idea is that the in order um in order is left um left current uh post oh sorry left current uh right and post order is uh left right um current right so maybe we could type that up hang on in order is left root I guess that's terrible parent maybe uh and then post order is uh left right and then parent right so then here you can see that the left note the current left node wait um is going to be the um foreign you can see that the left node is going to be the common pieces between these two things and then you can kind of maybe play around with that right um okay and then basically um I think the other thing that you can do is also um depend how you want to do it I mean I think maybe that's sufficient but maybe it's not the easiest way I'm not actually quite sure I haven't done this in a while but in this case the post order um the parent is always going to be the last node just the way that it is you know structured so that now you can use this to figure out in the in order which one is left and which one is right I think maybe that's a little bit easier over in variant um or a condition that we can figure out so let's do it right so how do I want to construct this but um so maybe you have something like construct uh left right and this is going to be left right under in order um so this is going to be inclusive just to be clear is that the inclusive one um and let me just by inclusive under in order right and that's the thing that we pause right and in the meanwhile on the post order we can actually use a stack an explicit stack in this case perhaps to kind of um iteratively uh maybe not iteratively may not be quite the right word but just like um you know get the parent or the root node or the current node every time right so maybe we can do something like this um let's just say post stack is equal to I mean I know that in Python did the same but I just kind of want to make it explicit I suppose because I don't wanna I don't want to manipulate the input in that way okay so then now um and then so that one thing that you can do now is that okay I mean I'm gonna be there is an optimization to be made here I'm gonna make it a little bit later so definitely if you already know what I want to do then bear with me but basically now we can say that the current node is the code to post stack dot pop meaning the last item you know we're trying to get this P right here right and then now um we're trying to find in order from oops in order from left to right we're trying to find in here the index that contains the current thing right so I mean I'm going to invite pseudocode a little bit so you know don't worry for now below um yeah something like that maybe just index say let's go do this dot uh fine um I think it's actually called that index but this is a little bit off just uh I mean I guess this kind of works actually uh of current plus left or something like this right something like that give a tick maybe I needed this to be inclusive so it's my plus one but should be okay and then now the current node is equal to a tree node of the value of um well current right because I guess that's what you get on a stack and I know that left is you go to construct from left to the index -1 to the index -1 to the index -1 and I know that right is equal to construct um index plus one to the right and then we return node um we might have to we have to definitely change some base case here meaning that if left is greater than yeah red and white will return none um and I think this is maybe okay I don't know that I mean there may be some like weird not weird but just Larry weird edge cases with respect to popping but I think the structure of the code seems about what I want it to be so then now we just return construct zero and then length of in order minus one because it's inclusive and then let's just give it a spin real quick um 20 is not in the list dong let's kind of take a look at that then left right in order left to do right uh okay so maybe I mean it's very possible that I messed up so first of all it takes the three it looks at the nine and then it oh hmm okay so I am a little bit off here because it tries to do the iPhone I didn't really pay attention to the construction uh timing um because so yeah so that's my fault um but yeah so then post order what does that mean right that means that recursively if we want to call the parent we have to do the right side first because that's the last item is going to be the right size um item first I don't know if this is sufficient to fix it but let's kind of at least give it a spin and that looks okay right yeah I mean the test cases are not so strong that I am confident but that looks okay and in Phil you can submit it now but what is the complexity here right well it's going to take time out limited time limited exceeded because while we printed stuff but also because this is all of N and because we do a lot of construction um if you assume um a balanced tree then it'll be n log n but you cannot assume that so that could be inferior like a linked list and this could be n square if this is like the last item every time or something like this right so the next thing to do is um make this upgrade in over one time uh and that's where all the uniqueness uh I mean well it's also part of that comes in and the thing is to just have a lookup right so maybe in order lookup uh terrible whatever but and then now for index uh X in enumerate in order excuse me friends oh man sorry friend top uh hope it wasn't too loud all right I think I have 80 of that out of the system so maybe there's one more anyway yeah this just looks up to index and then now we can do this in a all of one way right uh could and that's pretty much it let's give it a spin again maybe I should kept track of the timer but let's give a submit um should I yeah I mean okay I was just checking to see whether there's like a zero case like zero uh length case or something like that uh all the other stuff I think doesn't matter unless I mean the only thing that could happen is that time out but it looks okay we got 1080 um so what's the complexity here right well obviously it's still going to be linear space we use a lot of that space um and well this one doesn't have to be honest because you can replace this with an index that goes um through post order because all we do is kind of look up you know uh and in the X lookup right so that didn't have to be I think this lookup needs to happen yeah I mean maybe you could do something a little bit smarter but not really I don't think so ah so yeah linear time linear space linear time because this will take um all the operations excuse me all the operations here are all of one so and we look at each node once and there and node so that's gonna be linear time linear space um yeah that's what I have for this one let me I'm curious what I got wrong previously oh yeah I did do that in index last time didn't I tell you what the wrong answer is anymore oh like I mean I know that is wrong answer but don't give it a test case or something I feel like they used to do that I don't know I guess it seems like here I don't pop one off um uh but now this time I think I wrote it more generically so I didn't have to okay cool uh yeah that's what I have with this one let me know what you think and yeah stay good stay healthy it's a good mental health I'll see you later and take care bye
|
Construct Binary Tree from Inorder and Postorder Traversal
|
construct-binary-tree-from-inorder-and-postorder-traversal
|
Given two integer arrays `inorder` and `postorder` where `inorder` is the inorder traversal of a binary tree and `postorder` is the postorder traversal of the same tree, construct and return _the binary tree_.
**Example 1:**
**Input:** inorder = \[9,3,15,20,7\], postorder = \[9,15,7,20,3\]
**Output:** \[3,9,20,null,null,15,7\]
**Example 2:**
**Input:** inorder = \[-1\], postorder = \[-1\]
**Output:** \[-1\]
**Constraints:**
* `1 <= inorder.length <= 3000`
* `postorder.length == inorder.length`
* `-3000 <= inorder[i], postorder[i] <= 3000`
* `inorder` and `postorder` consist of **unique** values.
* Each value of `postorder` also appears in `inorder`.
* `inorder` is **guaranteed** to be the inorder traversal of the tree.
* `postorder` is **guaranteed** to be the postorder traversal of the tree.
| null |
Array,Hash Table,Divide and Conquer,Tree,Binary Tree
|
Medium
|
105
|
70
|
hello everyone welcome back and today we are looking at question 70 which is climbing stairs so the question is straightforward they are saying that we are climbing a staircase and it takes n steps to reach the top and they are telling us that each time we can either climb one or two steps so anytime you want to make a move you can take one step or you can take two steps so they want to know in how many distinct ways can we climb to the top so example one gives us that we have two steps in the staircase so the output should be two now why is that they are saying that there are two ways to climb to the top either we go one step at a time so one plus one or we take two steps we jump to step number two so we have one way here and the output should be two ways now example two saying that the staircase has three steps and they are saying that you can climb one step plus one step and this is considered one way to climb to the top now we have another way which is take one step then jump two steps this is the second way and now the third way is to jump two steps then take the final step so the output is three now let's go to the blackboard and explain how can we tackle this okay here we are and i have wrote the main question that we need to keep in mind which is in how many distinct ways can you climb to the top i also wrote that anytime we want to make a move we can take one step or we can take two steps okay and as you can see i have drawn a staircase and i have colored each step with a different color so we can distinguish them easier now i have created steps array this steps array will hold n plus one places now we said we have n steps now why am i holding n plus one places in the array and not just n well let me tell you that because i have wrote step zero i know it's not a step it's just a flat surface but i have put it there for a reason just bear with me and you will see why so the question said that this staircase has n steps and i want to add step zero which is nothing but i want to add it so our array will hold n plus one places okay so what is the purpose of this area you might ask me well let me tell you this now this array at each index we will hold the number of ways that we can reach that step for instance how many ways can you reach step one the answer will be here or how many ways can you reach step two the answer will be here so this is the purpose of this array each time we know how many number of ways can we reach step i we will put the answer in the array so let's start i just want you to forget about step zero for a moment we will come back to it later okay so starting with step one how many ways can you reach step one now since the question said that anytime you want to make a move we can either go one step at a time or jump two steps but step one require only one step which is hey go from step zero to step one there is only one way you can reach step one which is just go to step one with one step so we will hold one here okay now in how many ways we can reach step two well step two was in the example and the answer was two well let's see you can either go from step zero to step one then from step one to step two this is considered one way or you can jump from step zero all the way to step two and this is another way so the total number of ways you either take one step at a time or you jump so we have two ways to reach step two so we will put two here now i will come back to step zero let me ask you this question in how many ways can you reach step zero and you might ask me well it's not a step what do you mean how many ways can we reach it i will say yes i know it's not a step so let me rephrase my question in how many ways can you reach nothing well the answer is not obvious but the answer is one there is only one way we can reach nothing which is we can't reach nothing can't be reached because it's nothing so there's only one way to reach nothing which is you can't reach it okay so i want you to notice something when we said we want to reach step two we said we either can climb from zero to one or from one to two or we can go from zero to two so it's two ways now let's look at it from a different angle we can reach step two either from step one or we can reach step two from step zero if we want to reach step two from step zero we need to jump two steps but if we want to reach step two from step one we only need to go one step so in a sense we can reach step two either from going from 1 to 2 or from going from 0 to 2. so 1 plus 1 equals 2 okay so now let's look at this in how many ways can we reach step three well you can go from zero to one to two then to three this is one way or you can jump from zero to two then you can go from two to three this is another way or you can go from step zero to step one but then jump from one to three so we have three ways but let's look at it in a different way we can come to step three either from step two or if we jump from step one let's look at the array we can come to step three either from step two or if we jump from step one to step three so if we add 1 plus 2 this will result with 3 which is the answer we can reach step 3 in 3 different ways did you see the pattern so to reach to a specific step we can either come straight from the step before it or two steps before it so the equation that we want to use the number of ways to reach step i is either by coming from the step behind that which means i minus 1 or by coming from two steps before it which is steps of i minus two okay so in other words in how many ways can we reach step four will you say we either can come from step three or we can come from step two so steps of four will equal step of three plus step of two do we know what a step of three is well yeah it's three do we know what step of two is well we also know it's two so three plus two equals five and this is the trick to the question so now i will tell you the reason i wrote step zero is the following when we ask ourselves how many ways to reach step two we can say oh okay it's by step one plus step zero do we know what step zero is now yes we know it since we included it's one and how many ways to reach step one well it's also one so one plus one equals two and this is the idea behind the question so let's go cut it out it should be so quick okay so we said we need to create an array which will hold the number of ways to reach step i so end i will call it steps to match the blackboard equals new and we said our array will not hold n steps but n plus one steps to make sure we include step zero now we know that step zero how many ways can we reach step zero we said only one way which is you cannot reach nothing the only way to reach nothing is you can't reach it so there's only one way now how many ways can you reach step of one well we know that there is only one way we can reach it which is just go to one take only one step so now we have a for loop so four and i equals what we already took care of zero and one so this should start from two for intel equals two i is less than or equals to n because they saying how many distinct ways can we reach the top or in other words how many ways can reach step n so we need to include then i plus and basically we set the equation as steps of i equals we can either come from the step directly behind that so steps of i minus one or we can come from two steps before it which is steps of i minus 2 okay so in the end just return steps of n will hold the number of ways to reach step n and that should be it let's run the code and let's submit as we can see faster than 100 okay so let's look at the time and space complexity starting with the space complexity we created an array with n plus one steps so the space complexity is big o of n plus one but we can drop the one so the space complexity is simply bing o of n now in terms of the time complexity we have used a for loop to move through the steps now if we have n steps the time complexity would be big o of n minus one since step one we took care of it before the for loop but again we drop the minus one and simply the time complexity would be big o of n i hope you guys enjoy the video best of luck to you and see you in the next one
|
Climbing Stairs
|
climbing-stairs
|
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45`
|
To reach nth step, what could have been your previous steps? (Think about the step sizes)
|
Math,Dynamic Programming,Memoization
|
Easy
|
747,1013,1236
|
232
|
hello everyone this is DSS zindabad and today we are going to discuss the daily challenge of we code which is Implement Q using Stacks let's jump into the problem statement Implement a first in first out queue using only two stacks the implemented queue should support all of the functions of a normal Q which is push Peak pop and MP these are the details of the function so after reading the problem statement I understand that I need to implement when Q right so basically a q data structure is a first in first out data structure right what does it mean how is it different why are we discussing it we'll answer all of these questions we need to implement this using Stacks now what are Stacks stack is a data structure which is last in first out right so you call a q as a F4 and you generally call a stack as a F4 now what is the difference and why am I discussing this for this problem let's understand it for example you had something like an array right it had elements like 1 2 3 4 so these were the elements that were present in my array right so what happens is basically I'll consider a Q right and I'll consider a stack s so once you are traving right so you will start traversing from here that is one right it gets added into the Q it gets added into the stack or let's do one more thing I'll just first do it I'll just put them first in my queue and then I will put them in the stack so basically I was standing on the Zero index I'll add one here I'll move to the next I'll add two in the Q then I'll add three then I'll add four right so this is the Q that I have my pointer will always point to the first element that was added right so now let's talk about if this array was added into a stack so first my zero index is added that means my pointer is pointing towards one then when it goes to the first index two is added into the stack and now my pointer is pointing to two then when it goes to the second index three is added into the stack and my pointer is pointing to three when it goes to the third index four is added and my pointer is pointing towards the fourth index so if at any point of time you have something like s do4 right your answer as your pointer is pointing towards four will be four and if you have something like Q do B right then your answer will be one which is entirely different why because the stat is increasing upwards right whenever you're getting a new entry it is getting stagged over the existing entry when you talk about Q it is getting expanded in a linear fashion right so if you are standing here these are blocks are getting connected to it on its back you can take a example of a railway train right wherein the different compartments get connected behind the engine right and you can consider engine being something which where my pointer is pointing initially right so if you pop it out then it will go then it will get incremented right for example here supposedly if we it's not how it is done but let us suppose I'm just giving an example that here it was on one then it goes to two so it is getting incremented but when you pop something out the pointer gets decremented in the case of Stack so I hope the difference is clear now in the given question they have said something like you can use at most two stacks so at most means that you can use the number of stacks which you'll be using to implement q that should be less than or equal to 2 right so let's start from this value to itself right so basically you'll be given this as a template for writing your code you already have these functions defined in the class MyQ you need to put your code here okay and you'll have an input like this wherein you'll be calling the Constructor and different function calls will be made okay so this is how the input is given to you now after discussing it let's talk about the approach right so when I say let's talk about the approach I have understood that I am implementing a EO that is first in first out data structure using a letho that is last in first out data structure right I have taught you what is the difference between the two right so basically what I do is as I told you that let's start that we have two stacks that have been given to us right initially I am considering that I have been given these two stacks and using these two stacks I need to implement them in such a way that they work as a cube right I'll quickly copy paste the example here right so basically these were the stack and this was the function that I had so what is happening is first this function is called it is a Constructor right so after the Constructor is called and the object is initiated all of it we come here to the next call that is push now for the purpose let's create an algorithm so that we know each time we come across any function that is push pop empty or Peak how are we going to solve it right so basically I'll have functions like push pop Peak and MP okay so let's begin with the function push as I'm standing on this function call and I need to push one right the first step that I will do is I'll check if stack S1 is empty or not right so basically what happens is why I have to do this is because from a data structure that works in last and first out manner I want to have something as first in first out manner right so I'll check if stack S1 is empty or not so I'll have two options that is yes it is empty no it is not empty if it is not empty that means there are certain Elements which are already present in my S1 then what I'll do is I'll quickly put those elements in S2 put X in S2 right and you have to do this while S1 is not empty that means put every element that is present in S1 in S2 supposedly that see initially your stack will be empty right so in that case what you can do is if it is already empty you just take that element and you push it in S2 right so push okay I WR it here again so you will say push X in S2 X is the current value I want to push right so according to this I see that my S1 is empty so what I'll do is I'll push one in S2 once I have done this right my next step will be I'll check if stack S2 is empty or not right so basically if it is not empty my stack S2 is not empty in that case I'll push everything in S1 step why am I doing it is something you'll completely understand once we have a dry run right it is basically so that we can use the concept of Leo as C4 right so I had one here I'll say while I have any element pending here I'll simply pop it out put it in S1 right so again you'll get a push now when you got to push here you have to push two so you'll check this first condition is S1 empty you'll say no it's not empty so what you'll do is he will say okay if it's not empty pop it out from here put it in S2 so now your S1 is empty and your pointer is pointing to one and S2 right after that once you are done with it what you'll do is you'll say whatever is now the value which is two you put it in S2 right it gets added in S2 right so now you'll say while S2 because here we just wrote that the Second Step will be if the stack two is not empty put everything back in stack one so once you do that see now if you see my pointer was pointing to two right but if you see this is according to Leo that means two was the last element for example if I just had these three function calls that were made that was MyQ push right so two was the last element that was added but in case for example just forget about all of this if after this we have a pop my pop will return me where my pointer is pointing to but we know that the answer should be one why because we are implementing C4 we are not implementing Leo right so in that case that is why we have used the Second Step wherein I will pop out every element from S2 and I'll put it in S1 so now two gets popped out right it gets added in my S1 my pointer is again pointing to one right it gets popped out and now one so here my pointer is pointing towards one in S1 and my S2 is completely empty now right so if now the pop call is made I will get the right answer I hope this is clear right why have we used these two steps now again we'll have something like a push when the push call is made we need to push a three but before that we need to check if S1 is empty or not we can see it's not empty it one comes here my pointer for S2 is pointing towards one my pointer now from S1 stack will point to two it gets popped out my pointer is pointing towards two I need to add S3 uh three gets added in my S2 and my pointer is pointing here so again if I get a pop now it will give me a wrong answer it will give me three which was the last element that was added but I need to have a first element when I call a pop function just after this function so what I'll do is I'll say quickly add this back in my S1 so it is here on three gets added gets popped out on two gets added right popped out one gets added pointer and S1 is pointing towards one gets popped out right so now my S1 is having all of this and my S2 is empty right similarly another push Colum is made now when this push call is made we'll remove all these elements put them here add the new element and put it back here so I'll simply do it here only right so because I've already told you a lot of times for different elements so basically I'll have something as S2 will eventually be empty right I'll have 4 3 2 1 and my pointer in S1 is pointing towards the final answer now when I get the next function call which is pop so what happens in case of pop is I'll simply return whatever is present on top of S1 stack right so you can directly use the dot top function of stacks and you can give it and then you can pop out that element because we need to pop it so basically pop does two things it gives you it returns you a value and it deletes that value so as my pointer was pointing towards one it gets popped out right it is no more in my stack my pointer will point to two right so then I am again pushing an element now I have to push five so all of these elements first will be added here so we'll have something like 2 3 4 then five will be added here now all of these elements will back be added right so then finally what I'll have is for S1 I'll have 5 4 3 2 my pointer in S1 will be pointing to two and my S2 will be empty now if I get a pop I have to return a two why because that was the first element initially we had one it has been scrapped and after one we had two as the first element so we need to return a two right so it gets we'll simply use the top and pop function and similarly it's done and as you can see we got these pop functions so this pointer gets decremented we get a three then it gets popped out we get a four and so on so this is how it's working now in the case of peak function what we'll say is we'll say Peak means you just have to give me the top element that means where my pointer is pointing right now you do not have to do not delete that element okay so if you were using a q directly you can say that this is dot front function that means tell me whatever is in the front of my que the first element that where my pointer is pointing to right so the next function that we need to implement is MP so you can simply write a code that at any point of time see what we're doing is we're initially putting everything in S1 right then we're putting it in S2 then you're again putting it S1 so I just need to check that is at any point of time is my S1 empty so it can simply return me a true or false I think we are good to go there's one more thing I would like to add before we move forward towards coding it so guys basically there's one more approach of doing it that is using recursion right so if you are very confident in recursion you can easily implement it's an easy implementation right so here in what you have to do is you can simply use something like an recursion stack space internally right rather than having two stacks you can just work with one stack okay but if you talk about the space complexity it Still Remains O Okay so I'll not be doing it separately but for all the people who like working with recursion can try this it's a really easy code right so let's quickly jump into coding it and then we'll talk about its space and time complexity I'll not be doing a dry run because when we were discussing the approach we did a dry run already right but if there is any doubt you can always comment down in the section okay so this is the code that has been given right so basically publicly I will initialize two stacks that is S1 and S2 right my Q is a construction Constructor that has been called right so what we were doing in push was first step that we were using was that check if S1 is empty or not okay for the function push what were we doing we were saying that the first step is that check if stack S1 is empty or not right this was the first step we were doing right and if it was not empty then we were saying put all elements in S2 right so I'll simply have a value that will say if S1 is not empty in that case what you need to do is have something like in y have S1 do top right you are accessing the top element there you'll pop it out from S1 and you will put it in S2 using the push function right so this is y then the given X element that you have to push you'll directly push it in the S2 stat right so you'll push X now you will again the Second Step that we going to do is that we're going to put everything from S2 stack to S1 stack why are we doing this because still here right from this F Loop to us pushing S2 X right we are working with Leo fashion I want to get a F4 that is first in first out so I need to invert it right so I'll quickly copy paste this code here and we'll just make subtle changes here we'll have S2 is not empty in why we're getting s2. top we are popping it out from S2 and we're pushing it back in S1 right it's a void function we are not returning anything in the case of int pop what we have to do is we will say that you can just have something like int answer right which will have S1 do top and then you can pop that element which was currently on the top and return the answer in the case of peak you can simply return S1 do so right and for the case of function Boolean m you will return if S1 is empty or not I think they're good to go this is the code that we have written let's quickly run it and then submit it and it is working fine let's submit it and yes it's working fine now let's quickly discuss its space and time complexity so basically let's talk about the space complex lexity right when you talk about the space complexity as you can see we are having two stats right so in worst case you'll have o of n that is number of elements that you want to put in the stack right so this is so we know that this code has a space complexity of O of N and as we have two stacks right so forther let's talk about the time complexity here you can see this Loop is running till you have the number of elements in the stack one so in the worst case that can be o of n elements here again it is O of n elements in the case of pop Peak and empty you will have a Time complexity of O of one because your pointer is directly pointing to the answer you want you don't not have to Traverse and then get it but in this case you're going to Traverse the whole stack one first right then put it there and in the second while loop you have to Trav hold the S2 stack and then put it in S1 stack so the time complexi is of O of N and space complexi is again o of n as earlier I talked about the recursion approach it has the very same time and space complexity if you have any doubts or you want to discuss further feel free to comment please like share and subscribe this video thank you so much
|
Implement Queue using Stacks
|
implement-queue-using-stacks
|
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).
Implement the `MyQueue` class:
* `void push(int x)` Pushes element x to the back of the queue.
* `int pop()` Removes the element from the front of the queue and returns it.
* `int peek()` Returns the element at the front of the queue.
* `boolean empty()` Returns `true` if the queue is empty, `false` otherwise.
**Notes:**
* You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid.
* Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
**Example 1:**
**Input**
\[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 1, 1, false\]
**Explanation**
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: \[1\]
myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is \[2\]
myQueue.empty(); // return false
**Constraints:**
* `1 <= x <= 9`
* At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`.
* All the calls to `pop` and `peek` are valid.
**Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer.
| null |
Stack,Design,Queue
|
Easy
|
225
|
847
|
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you've not liked the video please like it subscribe to my channel and hit the bell icon so that you get notified whenever i post a new video so without any further ado let's get started problem is shortest path visiting all nodes it's very easy problem just a new concept we will learn so let's see the what the problem is we are given an undirected connected graph so undirected means like there is no direction between the edges uh between the nodes and the connected graph means that there is a edge like there is a path from every node to every other node so there is a path n nodes labeled from 0 to n minus 1 so what does that mean that means is that like if there are 5 nodes that is n is given to 5 n is given as 5 then there will be 0 to n minus 1 so 0 1 2 3 and 4 that is till n minus 1 these will be the nodes 0 node 1 node 2 node 3 node important so like this is 0 node 1 2 3 4. you are given an array graph where graph of i is a list of all nodes connected with node i by an edge that is this graph i is your adjacency list this graph i this graph array is given so this graph error is this what does this mean so this is a 2d array right if you do indexing 0 1 let's do one thing 0 1 2 3 4. so what does this graph array tells us this tells us that c for this i let's say this is i is equal to 2 means this 2 node is connected with 1 3 and 4. so see 2 node is connected with one three and four right similarly if i is four so four is connected with one and two so c4 is connected with one and two if i is three so three is connected with only two fine so this is your adjacency uh list kind of thing this is given to us so we are taking this example here so now what we need to do is uh return the length of shortest path that visits every node we have to find the length of the shortest path that visits every node you may start and stop at any node you may revisit nodes multiple times and you may you reuse edges so we have to find the shortest path which will cover every node and we can start at any node we can stop at any node we can again and again visit the same node multiple times and we may not reuse edges we may we can reuse edges right uh so let's see this example first let's uh draw this graph so we have uh 0 1 2 and three so what will be the shortest path so one path could be one to zero then zero to see one to zero then zero to two then again from two to zero we have to go back then from 0 to 3 this is one part here we are starting from node 1 what we can do is we can let's say start from two node so from two we will go to zero then from zero we can go to one then from one we have to come again back to zero and then from zero we can go to three so in this we are starting from two similarly we can also start from zero as well so from zero we can go to one then from one we have to come again back to zero then we go to two then from two we have to again come back to zero and then from zero we can go to three right so see how much over here what is the path so in this case uh what's the distance like we have to return the length of the shortest path so what will be the length here one two three and four is the length what is the length when we are starting from two node one two three four here also it's 4 when we are starting from 0 what is the length 1 2 3 4 and 5 so minimum we have to return the length of the shortest path that visit every node so these parts these two parts are covering every node see zero zeros also covered one is also covered two is also covered three is also covered and this is also the shortest path four this is also shortest path but this is not the shortest path although it's covering every a node zero is covered one is covered two and three are covered but it's not the shortest path it's length is 5 right so we have to return 4 so output for this will be 4 that is the length of shortest path length fine i hope you understood the problem let's see another test case so see guys we will see how we can approach the problem because that was what it matters like dry iron also we will see so see this test case let's not draw here so this test case let's take uh this one we have 0 1 then we have 2 then there is 3 and here it's four three and then four and here something like this is given right yeah so see now they have told in the question right they have said in the question that we can start at any node and we can stop at any node so we have how many options we can start from zero we can start from one we can start from two three or four fine let's see each path uh so if we start from zero we'll go to one because there is only that option one then from one we can go to two we can go to four also so let's go to two so we go to two then we can go to three then there is no path from three to we have to go back to two and then we go to four so see all the no all the uh nodes are covered right zero one two three four so this is one part if we start from one we can either go to zero or we can go to two so let's go to zero first so we go to zero and then we come back to one again because from zero we cannot go anywhere so we go to one again and then we can go to two then we go to three from three we go back again to two and then we go to four so see this is one path from two uh if we start from two so two we can go to one we can go to 0 then we come again back to 1 and then from that we can go to 4 2 and 3 something like this we can do and 3 from 3 we can go to 2 then we go to 4 let's say then we go to 1. or what we can do is uh yeah three two to four then four to one and then we could go to zero from one we can go to zero fine and from four what we can do we can go to one we can go to zero then we come again back to one and then we can go to two and then we can go to three fine now see guys here or how much is the distance one two three four five is the distance how much is the distance over here let's so this is the test case we are seeing right here is one two three four five and six so see this could not be the answer six could not be the answer because we have already got five this here one two three four and five and six so this also is not valid this is not valid 1 2 3 4 this is 4 so this could be our answer because 5 is not now on not our answer now because it's obviously 4 is less than 5 right we have to find the length of shortest path and this is one two three four and five so this also will not be so see this is our answer that is four so output will be four one possible path is zero one two so yeah you can start from 0 also so from 0 you can go to 0 1 4 2 3 something like this you can do so there could be many paths right there could be many answers uh here our answer one answer could be like when we are starting from three node there could be one more answer where you are starting from zero that is zero one then you go to four then you go to two and then you can go to three something like this you can do right this is also four length so see guys from this what i'm trying to say is just think what you can do first of all we can start at any node this is one observation second is that we have to find the length of shortest path right we have to find the length of shortest path now you might be thinking that what we see we have to traverse the graph and we have to find the path of the shot like shortest path we need to find so that is so clear that either we will use dfs that is depth first search or we will use breadth first search but now the question is what should i use see answer we can get from both the approaches but see here we have to find shortest here in the question is given to find shortest so whenever it's given a shortest or minimum length then go for bfs that is breast for search go for breads for search because breadth first search will give you the minim the uh minimum path more quickly like more early or you can say more quickly because it's algorithm it's designed in such a way that it gives you the shortest path early than dfs depth for search you have to use breadth first search answer will come with both depth for search also will give us the correct answer but then we have to do a lot of optimizations because depth for search works in a different way that it goes into deep and you know so both have different working so over here we will be using breadth for search we will be using breadth first search right so i hope that is clear why we are using breadth first search now if for this question c if you are not aware that how breadth first search algorithm works so i will highly recommend watch the uh algorithm first like how it's uh how it works then only come to this problem right so see in depth in uh breadth first search bfs we have a cube fine we have a queue and we work on the queue until q becomes empty so that is what gfs is right and in bfs initially we add in the queue the starting node right that is if you are starting from zero node we add that if you are starting from uh whatever we are starting from we add that in the queue initially now over here see over here we can start from any node so i hope you guessed correctly yeah we will be adding all these nodes in the queue initially because all these could be our answer like our answer could start from all of these notes fine so i'm erasing this just a second yeah what will happen this is like this is bfs or problem only it's nothing much than that it's just that there is one optimization which we have to do here in order to solve this problem right so see we will take a q so this is our q fine q and initially we will add all the nodes in the queue right so uh we will uh in the queue now we will add this thing so if we are adding 0 node 0 we will add 0 and along with that what we will add so this pair we will add in the cube right so zero we are adding and then we will be adding the distance that is the current distance like how much is the length of the path as of now length of the path that also we will be uh keeping along with it and we will be keeping something called as a mask fine now you might be wondering why we are keeping this mask right let's discuss that so if you are aware that why we are using mask then you can forward to the dry iron part uh otherwise you can continue so see over here guys see we have to stop when we have visited all the nodes right when all the nodes are we when in our path when all the nodes are covered right all the nodes are covered then we have to stop we have to not go any further because what we need to do we have to just return the path which is covering every node right so let's take an example we have let's say we are starting from 0 and we go to 1 then we go to 4 we go to 2 we go to 3 now at 3 we have covered all the nodes now we will not again go back to from 3 to 2 why to do that fine we have we will stop here because we have covered every node this is our answer just this is the path the shortest path that covers every node fine now we need to know somehow that when we reach 3 we need to know that we have covered all the previous nodes that we have covered 0 also we have covered 1 also we have heard 4 and 2 for that we are keeping this mask so this mask is let's say uh there are how many nodes one two three four five there are five nodes now so there will be this mask zero five zeros this will this zero will be representing the zeroth node this will be the one node this is second node and this is the third node and this is the fourth node if we have see here we have visited zeroth node so for this mask this will be set to one so what this what does this tell that we have covered the zeroth node because it's one when we will go to this one node we will set this one this bit to one so this will tell us that zeroth node and first node are covered fine then when we go here 4 this will tell us so for this 4 we will set this 0th bit to 1 because for this 4 now this number 1 0 this number 1 zero one this tells us that zeroth node is covered one node is covered and fourth node is covered now we just need to find include these two and three nodes in our path fine so for this we are keeping this mask so when this mask will turn 1 all the 5 ones means we have covered in our path we have covered all the nodes because all bits are one so for that when this is happened like when this is all our ones so we can stop here that okay we have covered all the nodes and this is our shortest length this is the length fine why will get the shortest length in the starting only because this is bfs right so in the bfs we'll get the like the shortage parts in the starting only because that is what the algorithm is fine so that's why we are keeping this mask so every time see guys very important every time see this is our mask right how we will create this mask we will discuss that also but every time we visit node we are visiting one so in the mask in the current mask so if we are following this part c right now we are at zero we are at this zero initially our mask will be zero something like this when we are here this mask will turn to this which will tell us that zeroth node is covered then we go ahead now so then this mask will turn to this that is zero and one node is covered now when this mask will be equal to one f five ones because there are five nodes then when this mask is equal to this one this five node five ones then we will stop and we will return the distance this distance how much is the distance fine this is how we will approach and what we have to do is uh over here yeah this is the thing now let's see how we will make this mask so the main like the final mask will be one this thing right five ones so how this will be created this will be one left shift n minus one this is will be the all mask means all bits are once what does this mean left shift means see what does left chip mean when we write uh x left shift y something like this so this means 2 raised to the power y multiply x so this thing will mean 2 raised to the power y is n minus oh sorry multiply x is 1 see x is 1 so this means 2 raised to power n only so 2 raised to power n is what how many nodes are there how their nodes are five total which are zero to four total nodes are five now so two raise to power five minus two raised to the power five minus one this minus one two raised to power five is what in bits one zero this is two raise to five thirty two if you represent thirty two into bits zero one so this will be like this now this is a two four eight sixteen thirty yeah and then you do minus one so this will give you one five ones when you do minus one i if you are not aware how you can subtract in bits then please watch please go through that also so when you subtract minus 1 from this you will get this that is 5 once which is what we wanted so this is how you will calculate the all mask right so this when or when our current mask the current mask will be equal to this mask then we will stop see right this is i hope you understood this so in the code let's see code also side by side so uh here is the total nodes n and this is the all mask we are creating one left shift and minus one so this will be one five ones fine and uh now see now what we will do let me raise this i hope you are getting what we are doing as of now so also you have understood uh how why we are using mask because we need to know that we have covered all the nodes or not right so this is the thing now what we will add in the queue so in the queue what we will add in the queue we will add the current uh node that is i then we will add the distance how much is the distance as of now and the mask current mask so initially when we are adding the zeroth node zero comma the distance initially the distance we will add as zero only so initially distance will be 0 comma the mask and what is this mask so if we have c if we have covered the 0th node what should be the mask 0 1 this should be the mask that is this is telling us that one this zeroth node is covered because it is set to one so this will be what how you can write it will be one left shift n or you can say one left shift i one left shift zero is zero here i is zero that is for this is for zeroth node this node one so two raised to power this is y two raised to the power zero into one that is two raised to the power zero and two resistor zero is this one fine so here you will store the mask what we are doing is we have taken this queue and it is a pair so these are two items this is one full item and this is one zero index and this is one so it's a pair of int integer this i is integer and this is again a pair here so here we are storing the distance and here we are showing the mask so integer so this is what we will store in our queue and we will have a set this is for visited so in the set we what we will be storing we will be we will understand why we are taking this visited also so in this we will be in the visited area so this is a visited area in the visited area we will be storing a pair so here will be the node and here will be the current mask that is i and the mask so we are going to each node because we discussed right if you remember we discussed that we will be adding initially all the nodes because all the because the shortest path could start from all of these nodes so initially we will be adding all these nodes in the queue so we are going to each node and we are calculating the current mask for that node so if we are at two so mask will be one left shift three i is what two so one left shift two is what two raised to power two raise to point two into one that is four so for 4 what is the mask 0 1 0 this is a mask fine so we are calculating the mask for that ith node and in the queue we are pushing that node with the mask initially distance will be zero and we are visit adding in the visited also that node with the mask this is what we are doing see i hope you understood till this what we are done what we have done so yeah now let's go further right so let me make the queue again so q will be something like this initially we will have first of all we will push a comma this in the queue so in the queue we will have zero comma distance which is zero initially and the mass so for zero mass will be what two raised to power zero that is what zero one so one will be the mass fine so this binary we are converting into integer and we are storing that then we will add so then the loop will uh i will be one so we will add this one node that is we can start from this one also so this will be one comma zero comma the mask so if we have starting from one means one will be covered so for that mask will be two raised to power that will be c 1 raise to the power 1 left shift 1 that is 1 left shift i so it will be 2 raised to the power 1 into 1 that is 2 so it will be something like this 0 1 0 this is showing that the 1 8 node is uh visited like covered fine similarly for 2 also this will be there 0 comma for 2 it will be 4. so similarly we will add three also and four also in the queue we will not do the entire dryer and see that will take a lot of time so i'm just giving you an overview how this algorithm is working you can try iron by yourself right so see we have added the initially initial nodes in the queue now we will start the classic bfs this is a classic bfs right while q is not empty we will pop from the queue the first node so in the queue from the queue this is port zero comma one right this is thought so first of all what we will check right uh what we will be doing is we will be going to each enabler right this is a bfs we will be going to all the neighborhoods of zero so we zero has only one neighbor so we'll go to one right if we go to one so new mask how new mask because see now we are going to one so one will be covered we are currently at zero and our mask is this one mask is this now one that is zero one this is the mask now when we go to one node then this bit is also covered now because we have gone to one so this is also covered so for this one what will be the mask it will be this that is it is covered now we have to do what we have to do all of these two so that here one can come so or zero plus zero or comma one or will be one the rest will be as such so this will be the new mask which will tell which is telling us see this new mask is telling us that zero and one are covered zero and one nodes are covered so this is new mask the correct mask whatever the current mask is this was the current mask right this one was the current mask um this was the current mask and we are doing ore of that mask with the mask for the this neighbor node which is one that is one left shift the neighbor node see one left shift the neighbor node so that will be this one and then we are doing or so this is the new mask and if the new mask is equal to all right means if this mask whenever this mask will reach 1 if it is equal to this all walla like all one so then we have to return distance plus one so distance will be having one less so we have to return distance plus one you'll understand when you will try in this thing right as if what we can do we can check whether this node and this mask is already covered if it's already in the queue like if somewhere in the queue it's already present this node and this mask so why do again add in the queue because this will be covered only now why do again adding the q further in future so then we will just continue otherwise if it's not in the queue so that is c uh over here what will be the new uh this thing it will be in one comma the mask is what zero so this mask is what zero uh this will be three now if you convert this binary into integer this will be three so this one comma three will not be in the visited uh set because vista set will have this thing we have not run the visitor set so visited set will be the visited set will be something like this uh zero comma mask for one like mask for zero then it will be uh one comma so if this is not visible one comma two is a mask then for two it will be four something like this will be there right now this one comma three the very one is the node and the three is the mask current mask this one this is not in the visited right so we can add it so we will add in the visited and we will push that in the queue as well and distance plus one we will do with the new mask and the new neighboring node so this will be added in the queue so in the queue what will be added comma the neighboring node which was 1 the distance will be 0 plus 1 and the mass which was 3 so this will be added in the queue fine so see guys at a point of time you will you can dry run once this algorithm at one point of time we will get all the so see what will happen we have we will get this path uh 0 1 2 so we were going from c if you see the test case 0 1 we were going to uh four then two and then three right so zero one four two three this will be the path but when you will reach three now you will get all the mask as one so that will be equal to this new all so then you can return distance plus one fine so i hope you understood the problem right uh this is the function which will give given to us and we can just we have we are making this helper function fine i hope you understood the problem and approach ah it will be more clear if you dryer and right uh here the thing which we have learned in this problem is that how we can use a mask how we can make a mask to store whether this node has been visited or not fine whether this node was earlier visited so if there are c if there are 0 to some n minus 1 nodes you can store it as bits so this will be the zero this bit will be corresponding to zeroth node then there will be one node then this is two node three four like this so if this is set to one means this node is covered so this you can use and you might be thinking why we are using visited set this thing because we do not want let's say in the future to take a test case let's say in future you got the same thing 2 comma 0 comma 4 something like this again you get so that you will not again push in the queue because we have already taken it here why to again push fine so this is to avoid these cases with uh set is being we are using that fine so guys i hope you understood the problem and the approach uh main focus for like i wanted to focus more on the approach in this problem uh try iron part we can all do by referring the code so let me know in the comments if any doubt found the video helpful please like it subscribe to my channel and i'll see in the next video
|
Shortest Path Visiting All Nodes
|
shortest-path-visiting-all-nodes
|
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge.
Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.
**Example 1:**
**Input:** graph = \[\[1,2,3\],\[0\],\[0\],\[0\]\]
**Output:** 4
**Explanation:** One possible path is \[1,0,2,0,3\]
**Example 2:**
**Input:** graph = \[\[1\],\[0,2,4\],\[1,3,4\],\[2\],\[1,2\]\]
**Output:** 4
**Explanation:** One possible path is \[0,1,4,2,3\]
**Constraints:**
* `n == graph.length`
* `1 <= n <= 12`
* `0 <= graph[i].length < n`
* `graph[i]` does not contain `i`.
* If `graph[a]` contains `b`, then `graph[b]` contains `a`.
* The input graph is always connected.
| null | null |
Hard
| null |
122
|
hey everyone welcome back to take you forward so we will be continuing with dp on stocks and it is the second problem best time to buy and sell stock part two so what does the problem state you'll be given prices of stocks on each day yeah so you have been given the prices on each day now you're allowed to buy and sell stocks as the name suggests you're allowed to buy and sell stocks now in this part one what we did was you were allowed to buy once sell once but over here you can buy as many times as you want and you can sell as many times as you want okay so what you can do is you are going into the market you say i'm going to buy it on this day so i'll say okay i'll buy it on this day and i'll sell it on this day so over here i'll make a profit of four i buy it with rupees one i sell it with five i make a profit of four then i say hey listen i'm going to again buy it over here and i'm going to again sell it over here which gives me a profit of three which in turn gives me a total profit of seven right i could have gone other ways like if i write down again seven one five three six four i could have gone other ways as well i could have said hey listen i will be i'll buy it over here i'll sell it over here right now the thing that you cannot do is you cannot go something like this you cannot buy before perform like if you're buying before performing the next buy you have to sell so buy and then you have to sell then again you can buy any day so this buy sell has to be done before performing the next buy sell you can't be like buy then sell that is strictly not allowed got this so performing this buy sell can be anywhere like you could just do a one cell as well this is one where you say okay the profit that i will make is five so you can perform buy sell as many times as you want only with the condition that before buying a stock you should have sold out the previous holding stocks that is the clear instruction given to you so you can perform this as many times as you want and if to give me the maximal profit you have to maximize this profit in this example the answer is seven so you have to just make sure you do this right so how will you actually solve this particular problem is my question to you so let's analyze this problem and try to figure out how will i try to approach these kind of problems so what was i given i was given 7 1 5 3 six four okay so let's assume i will be starting over here okay let's assume i'll be starting over here it's kind of a 1d array and when i'm starting off generically what can i do i can be like i can buy it or i can say i'll not buy it let's move i can buy it and then i can sell it or i'll not sell it i'll sell it here so what am i seeing a pattern of a lot of ways like you can do a buy cell you can probably do a buy sell you can do it on numerous occasions right and whenever there's a lot of ways what do you try always yes you try always and you get the best possible answer from always now when i say try always what comes to your brain recursion because there can be a lot of face so recursion comes to your brain right so how do you write recurrence in dp how do you write recurrence again we will follow a standard procedure what is the standard procedure of writing records the standard procedure is pretty straight forward it is express everything in terms of index now over here yes over here we have a plane array and you know whenever we have a plane array we can have the index working right across here so what i'll say is okay express everything in terms of index that is something which i'll do so we will be expressing everything in terms of index now do i need any other parameters is my question we need to think on this now we have done problems like knapsack if you remember and in that we have to uh we have to take care if our baggage was full or not right now over here if i am standing at here what decision can i make on it i can buy or i cannot buy how did you understand because you know before this you have not bought anything but if you're standing here what decision can you make what if you bought someone here then you cannot buy here for sure you can sell it so what idea i'm getting is on any index i have to know whether i have bought anything previously or not because if this guy was bought here i cannot buy this again i definitely cannot or if this guy was sold here then i can buy so i have to know if any guys were bought right before this or any guys were sold right so do i have an allowance of buying so i can say probably i can carry something like buy a variable like buy which tells me can i buy or not if someone has bought this and he has not sold it so over here i definitely cannot buy so i have to carry a variable as buy which tells me can i buy that stock if i can i'll either decided to buy or i'll skip it and go across and if i cannot buy then there are two options either sell it off or don't sell it off so i'll be like okay we have understood we need one more variable which tells me on that particular index can i buy or can i not right perfect explore possibilities on that day what am i looking for i'm looking for best possible answer so try to add up what i what are you trying to make profits try to add up if you're buying then it is as a minus if you are selling it as a plus i'll explain you when i write the records x or you're looking for profits right so take the addition of states or whatever you're doing wanting to do take the maximum of all profits make because you are looking for profits and then if you follow these and then there will be a base case if you follow all of these conditions i think you will be able to write very easily so without actually wasting any time let's try to write the recurrence okay so what did i say express everything in terms of index and by okay so let's analyze f of index and by so assuming uh the array is seven one five three six four so assuming you start at the zero earth index so this is the price array and it's starting at the zeroth index so can i say at f of zero you have complete liberty of buying because that's the first guy i'm giving you complete liberty of banks i'll be like okay i get the complete liberty of buying which is one assuming uh liberty by one means you can zero means you cannot so i'm giving them complete liberty so what i am asking you is ff01 starting on zeroth day with by what max profit you can give me that is what it signifies starting on this day you're starting to do your trading on the zero day what maximum profit can you give me is the question okay fine so what can be the states so we have understood uh these two states of index buy so let's uh tick mark the first thing explore possibilities on that day so let's analyze what can you do one thing i know for sure is there can be two possibilities whether like if there will be a buy like i'm allowed to buy or else i'm not allowed to buy that is for sure the possibilities will be this and on those basis i can make two profits there'll be two profits that i'll make right so let's assume if i'm allowed to buy what will i do let's come back to this what can i do with this seven i will like striver i'll definitely buy this there's no other way wrong i will definitely buy this or i'll say he's rival oh this is too costly uh let's not buy this and move to the next guy and see if i can do a trading on the next day so i'm saying you can buy or you cannot buy back to the previous days of dp on subsequences take not kick buy or don't buy so assume just for an example assume if you decide to buy over here and you decide to sell it over here what is the profit that you make five minus seven is the profit that you make which is minus two so you're adding minus seven to the answer whenever you're buying you're actually adding minus seven to the answer when you're buying and when you're selling you're adding plus five got this because if you're doing a buy over here and if you're doing a cell over here it's basically 3 minus 7 is the profit so minus 7 is added to the answer so can i say if i decide to buy on that day the profit that i'll add is this guy and if i bought on that day i'll move to the next day which is index plus one and if i bought in the next he cannot buy he has to sell so you cannot buy makes sense and what if i decide hey listen i am not interested to buy on this because the price looks huge i'm not interested to buy i'm like okay fine you are not interested to buy so why don't you don't buy and you go across to the next day and you see you still go with one saying hey listen i will still go with the buy because in the next day i still have the liberty to buy so you know this can be one way which is take if i just write this is take case this is not a case and i definitely know what i require is max of all profits made so the profit will be max of these couple of guys either i buy or either i don't buy as simple as that what about sell because if i come across to the next guy it is sell right so again we'll try to sell because i know we cannot buy if i coming to else we cannot buy we have to sell again assume uh you are somewhere oh where was the example assume you are somewhere over here i'm like hey i'm not interested to sell because the price is very low i'm not interested to sell or you can be like six if you're over here but the price is very high let's sell it so there can be again two ways i decide i'll sell it i'll say hey don't sell it let's move to the next day so two ways again so i'll be like fine let's go across if i decide to sell it i know the profit will be plus because i'm selling the money is coming to me so i'll be like fine let's sell it so if i'm selling it i will be getting something around prices of index plus function if i've sold a stock i will move to the next day and i still have liberty to buy i still have liberty because i've sold it now i'm free in the next junction i can buy but if i don't sell it then the profit made will be this i'll go to the next and i'll say hey listen you're still holding a stock you don't have a liberty to buy i don't know the max of this is what you take and you return the profit at the end of the day so can i say this is what the possibilities will be and you're returning the max of profits so what i can say is okay fine we have explored possibilities on that day what's the next take the max profits has been done peace case you're trying on every day when do you end up when you've tried on every day you've exhausted the days so i can be like when you exhaust the days that means when you reach this index because you started here you go here and ultimately you'll come to the nth index so whenever you come to the nth index there's no profit to be made the array is over there's no profit to be made but you have to be careful over here what if you actually bought a stock what if you bought a stock and you did not sell it so there will be a problem right so coming across when you end all the days so there is no profit to be made you have invested some money even if buyers even if buy is zero that means you're still holding a stock but if you're holding a stock that means you have gone you have invested a money minus so that won't matter so you will return zero no more money you'll get from the market because you're done no more money you'll get from the market so if you have gone with something it will be a negative value so that will not be considered into your answer this is how you can easily write the recursion so if you have written the recursion what is the time complexity will be very simple 2 to the power n because for every index you can either sell like take or not take so to the parent space complexity will be we go off and the auxiliary stack space and you can definitely optimize this because there will be overlapping sub problems if you try to draw the recursion tree you will see that there are overlapping sub problems of f of index and by so you can definitely apply the memoization technique and in order to apply the memory action technique what do you apply the changing parameters are index and the buy what are the values of index from 0 1 2 3 n so n different values what is buy either you say 0 or 1 for you are allowed to buy 0 4 you're not allowed to buy so there are two values zero or one so this will be the dp state that you need to optimize so if you use this dp states you will be easily able to write it so just make sure you just insert a couple of lines dp of index and buy one more line if dp of index and buy is not equal to minus 1 you return dp of index and buy again i have explained these steps in the entire dp playlist so if you're watching this video right from anywhere in between it's not my fault so yeah without wasting any time let's get started and code this so let's quickly quote this up uh you're given the values and the n so i'll just write the function we know it will be an index it'll be a buy and we can definitely carry the same array and uh and yeah perfect so we know if index reaches n uh it's over so you can return zero there is no more profit that you can make once that is over or else there can be a couple of ways you can say okay listen if buy is there or else a buy is not there and you know the profit can be easily made so you can just keep the profit to be uh zero and make sure it's long rather because they want the answer to be in long probability to constraints so profit will be max of couple of guys you know so either you decide to uh sell it off like you're buying so this is the cost that it will cost you and you cannot buy any further right or you can be like okay i'm not buying so i'll move to the next and you still have the liberty to do whatever or if you cannot buy then you can sell so if you can sell then there will be a plus that will that is something which you will get and it'll go across and say now you can buy it's now you can buy and over here or you can say okay listen i'm not going to sell as of now go and the liberty is sell zero like you cannot buy at the end of the day you can return the profit over here you can say return f of zero comma the buy is one values and n is what you return indeed it does run fine so what is the next step that we will do we will try to optimize this by dp so vector of vector n dp n comma vector end to size so to size minus 1 and please make sure you pass it over here versus dp and over here you can write vector of int dp and right over here before returning you can write dp of index and by again very straightforward and right over here you can just check if this guy has been previously visited if not why don't you return that guy which is index and buy just make sure you return it and i think once you've done this should be running super fine okay it will not run because we forgot to pass the parameters over here my bad so just make sure you declare uh the dp to be long otherwise it will give you a wrong answer that's how you can easily solve this problem but now it's time to convert this into a tabulation code so we have done the memoration code and we know the complexity of the memoration code will be uh big o of n crosser 2 the space complexity will be n cross a 2 plus an auxiliary stack space and you know i'm not a big fan of this so you notice that in order to remove the auxiliary stack space we have to apply tabulation what are the steps of tabulation the steps are very straight forward you have to write the base case and then you write all the changing parameters this is i and then there is buy right and then you copy the records that's what you do right so let's write the base case what is the base case was index equal to n so you can say that hey listen you will be creating a dp of n plus 1 this time and we will be starting off with dp of n equal to 0 that's what you will be starting off with right and right after that what is i how did you run the recursion if you remember the recursion it went in from 0 to n so it's the reverse that you will do in tabulation you start from n minus 1 till 0 what about by it will be from zero to one you can go from one to zero as well but it'll be from zero to one so just write this and copy the recurrence and if you do this it will be running fine and after that we will do another space optimization on that so i'll go back to here and we'll make it zero okay and right here we can say uh just make sure it is n plus one so that we can be like dp of n of zero dp of n of 1 is equal to 0 that's for sure because index equal to n by can be anything but it has to be 0. next is let's run the for loops so we know the loops will be running from here till and we know there will be a buy so probably it will be better if you write index because we are going to copy paste the recurrence so let's write index okay by can be from zero till one perfect ready next please make sure you copy paste the recurrence there's no need to apply your brains just copy paste the recurrence because tabulation is bottom up right it's the opposite of recursion so you have copy pasted that and over here just make sure you remove this instead of uh this entire thing it'll be dp of index plus one and it does buy one and this will be db of index plus one and zero so dp of index plus one and it will be zero this will be dpf index plus one and zero dp of index plus one and zero perfect this will be dp of index plus one and one so just write this db of index plus one and one perfect so that's what uh you have written and right over here you have written this and this will be dp of zero one is what you return dp of zero one now try to run this and see if this is running in the tabulation mode it is indeed running let's quickly submit this and see if this is working fine it is indeed working fine now what is the next step we know that whenever we are dependent on the previous like this is the previous row like index plus one is the previous so we are dependent on the previous guy right so if i try to show you in the ipad you'll get a much clearer picture now if you are following the space optimization technique from the first lecture i think this is very easy for you but for anyone who is coming out to you what are we doing we were assigning these guys as 0 and 0 which is the nth index then we went on to n minus 1 at index and we tried to find this and in order to find this what am i using let's go back to the code we are using index plus one like if you are standing at n minus one if you're looking at the code you're using index plus one which means you're just using these couple of guys right and you're filling this easily similarly you are also filling this easily by using these couple of guys that is what you're doing in x plus one and index plus one using these couple of guys to fill this and then you go to the next which is n minus 2 and in order to fill this you're using these couple of guys so do you actually need to store this now no again you'll fill this and then again you'll go to n minus 3 in order to fill this you'll use this and this how to fill this you'll use this in this so there's no need to store this so you just need to store two variables one is this and the another one is this so you can say this as the one variable this is the other variable so i can say uh this as the ahead because it's at the front or you can say whatever you can call it i'll try to call it let's because this is not the buy right you can call it whatever you wish to or you can take uh two variable array as well you can take two variable array as well that's your choice or you can take variables as well so what i'll do is i will be like okay i'll go back to the code what i'll do is i'll try to carry just two variables vector n or rather vector long of the ahead guy because it's the head and i'll be like two comma zero i know one thing for sure the ahead is this is that guy and i know there will be current which i'll compute because the current has to be computed right and uh these are the ahead so let's take it from head let's take it from ahead let's take it from add let's take it from ahead and this will be the current guy and once you've done this just interchange because in the next step if i show you the ipad whenever you go to the next n minus 2 this guy will be the ahead and now you will use these guys so just interchange once you have done this you know this at the end of the day is previous so you just change this off and you know try to run this okay my bad it will be ahead not previous so yeah let's just make sure it is ahead i've been so habituated to use previous and current that uh i wrote it okay that's fine uh submit this it will be running fine okay so this is uh the most optimized stuff that you can do but in the discussion forum you will see that people not using the 2l array and they will be using variables you can also use variables instead of the two sized array that is the similar stuff and if you use uh the studio error that then also it is similar like over here what are you using you're using uh two space over here and two so that's four so you'll see a lot of solutions having they're using four variables to write it does not optimize is it's still the same thing if you're using four variables to solve this the same as using a two and two size array it's four space that you're using right so lead code discussion forum you will see that uh people uh using four different variables to solve this again i will not say that it is wrong you can still use four different variables such as your choice like what are we doing over here if you carefully see you're basically running a loop from n minus 1 till 0 and then there's a by which is like from 0 to 1 so it's like 0 once there is a 0 and once there is a 1. so whenever it's a 0 the else part gets executed whenever it's a one the if part gets executed so you will see in the lead code forum what they will do is they'll omit this since they omit this and since buy is zero and one both will get executed once and once so what they will do is they will first execute the zeroth guy then they will execute the one right and they'll store it so you can also do the same thing so what you can do is you can say this guy to be ahead like this is the not by case so you can say ahead not by and you can say ahead by case and you can say this guy to be car not by and you can say this guy to be cur by okay so let's come back to whenever buy is zero what happens let's go back and check what happens i'm saying profit goes to the car by whenever buy is zero so let's write this curve not buy because by zero means cur not buy what happens on car not bad let's go back i'm saying the value of index plus ahead of one means ahead of buy head of one means ahead of buy so let's write max of values of index plus ahead of buy is what you write and what's the other thing 0 plus ahead of 0 means ahead of not buy add off not buy so if you write this can i say the curve not by because what are you generating car of zero right curve zero and what is curve of zero if you carefully observe cur of zero is curve not by so you have generated that perfect what's the next thing that you'll do cut off not buy is done and this is also done next thing that you will do is you will take care of buy and you will write max because the next thing will be 1 which means this guy will generate which is square of y and for this what's the formula let's see let's go back whenever you add y which is 1 this is 1 right this is 1 so whenever you add this as a formula minus value of index plus add of zero so let's write it minus values of index plus ahead of zero head of zero means not by ahead not by comma zero plus ahead of one means ahead of by and in this way you can easily get the current buy not buy and current buy which means you have filled up this guy and in the next step when you go across you'll be like okay these guys will serve as head not by and they head by in order to compute this and this so you can just stomach this and say okay listen next step ahead of not buy will be cur of not buy so instead of 2d array you'll just do this and ahead of buy will be cur of buy and you actually solve this using this wonderful variables and this is the solution that you always find in a lot of discussion forums but you don't understand so this was the entire intuition behind this possible solution so now what i will do is i'll go back to the code and now i'll try to omit this portion okay and let's try to write it long zero means not buy you know this not bad perfect one means bye you also know this right so bye so this is what you write perfect let's quickly declare this as well long off ahead not by and long off ahead back perfect i've declared both and i've assigned them to be zeros amazing instead of this i'll omit this law let's omit this entire stuff so and i need one other variables which is curve buy and cut not buy for sure okay so i know i'll have to switch so instead of this i'll say okay ahead by will be curved by and ahead not by will be current by for sure that's the first switch that i'll do perfect now let's come over here i know whenever by zero this is executed right so what i'll do is i'll say okay this is definitely going to be executed and the profit goes and stores in carbide which is curved by car not by the else one is cannot buy and whenever it buys its curl by for sure and i can remove this i'll make sure that both of them gets executed so this guy goes this guy also goes so i'm left off with carbine all right i'm left off with turbine i'm left with curd not by perfect this is over because i've assigned them so both of i'm executing both of them without actually running a for loop because i know both of them will execute it so first the curl of not buy was executing you can execute that at first or at end doesn't matter and you can execute the curve back perfect now let's come back uh to changing this slowly ahead of one means ahead of buy head of zero means not buy perfect head of one means buy perfect i think we have done this and one means at a buy amazing isn't it if i run this hopefully it runs yes it does let's submit this wow that is how you generate the variable solutions from a recursion from a tabulation from a space optimization this is how you generate the variable solution just don't mug it up have the intuition and it's 5 41 am in the morning so guys i hope you've understood the entire stuff just in case you did and just in case you did not please take your pen and paper and try to do it and just in case you did understand please give it a like and if you're new to this channel please do consider subscribing to us it is very important for us and now with this i will be wrapping up this video let's meet in the next one till then bye take ever care you're golden
|
Best Time to Buy and Sell Stock II
|
best-time-to-buy-and-sell-stock-ii
|
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day.
On each day, you may decide to buy and/or sell the stock. You can only hold **at most one** share of the stock at any time. However, you can buy it then immediately sell it on the **same day**.
Find and return _the **maximum** profit you can achieve_.
**Example 1:**
**Input:** prices = \[7,1,5,3,6,4\]
**Output:** 7
**Explanation:** Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.
**Example 2:**
**Input:** prices = \[1,2,3,4,5\]
**Output:** 4
**Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Total profit is 4.
**Example 3:**
**Input:** prices = \[7,6,4,3,1\]
**Output:** 0
**Explanation:** There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
**Constraints:**
* `1 <= prices.length <= 3 * 104`
* `0 <= prices[i] <= 104`
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
121,123,188,309,714
|
1,678
|
Hello friends my name is vikas Gupta today I'm going to start a new video on to solving later problem using Java 8. so friends those who are new into javaid and don't know much about like how to use Java stream API this series will help them to understand steam API and also will help them to crack Java code interview questions okay guys so let's get started so guys here you can see that we have given one problem statement okay that is goal parser interpretation okay so guys let's go to Ms word first try to understand the problem first and then we'll go to solve using Java it okay guys so here you can see that we have taken one input okay as uh this one and we have given this string okay command okay so basically uh sometimes you have to understand first if you are getting this inside this string this one then you have to convert this into this only if you are getting this inside this string okay you have to convert this into a small case letter o if you are getting this a l then you have to convert this into normal Al okay so guys in this uh string here you can see that uh first we are given this G we have to written simple G now we are getting this bracket open close then you have to return write this o now you have given this one Al okay so you have to convert this into Al so whatever you get inside this string like if you're getting this G then you have to replace with this one if you are getting this uh bracket open close then you have to replace with o if you are getting this uh bracket Al and bracket close then you have to convert this into Al so we are getting this output as a goal this so this is our output cool okay guys so let's take another example to understand more clearly so guys here you can see that uh we have taken one string okay with the with this name command so as I told earlier if you are getting this G then we have to replace with this one G if you're getting this bracket and open on and close you have to convert this into o if you are getting this bracket open Al and bracket close then you have to convert this into l so uh this will convert into G this coming of four times okay then you have to return o four times okay and this comes bracket to open Al and bracket close convert into Al so yeah so this is our output okay guys so let's go back to lead code once so guys here you can see that this command string command okay we have given some um string like G back it open close and break it open L bracket close okay now is trying to say that the goal parcel will interpret and if you're getting this G then we have to replace with this G if we are getting this open close bracket we have to replace with this string o if we are getting this uh bracket open L close bracket then we have to convert this into Al okay guys so which is uh okay this is J replaced with G back it open close replace with O and bracket open Al and bracket close replace with L so final output is goal okay guys similar for uh second scenario here you can see that so G will replace with G and here you can see that bracket open close Okay comes four times okay so 4 times o now bracket open Al bracket close then Al so this is our output okay now if you see that example three first we have given a bracket open Al and bracket close then we have convert this into Al okay now we are given this G in G here okay now we are given again back it open L close Okay so written as L now this two times coming back it open close on Double O and then G okay guys so this is our problem statement now we will see how we can do it into Java 8. so let's get started okay so what we need to do first uh we have to then uh get some string Builder okay Builder Okay uh SP equal to new a string Builder okay guys so now uh in Java 8 for iterating um some elements okay we have to use into stream okay like in Java 7 we have to use forage for Loop but in javoid we have to use into stream okay into stream uh Dot range okay and we have to start from 0 to command dot length okay guys now what we need to do next for each okay guys I okay now here we have to add some conditions here okay like uh if hope um command dot carrot okay carrot I if it's equal to uh G then what we need to do we can simply uh append or J inside this string Builder okay so s p Dot append don't worry guys I will explain you in details G okay as if okay now if you're getting this uh command dot carrot if you are getting this uh bracket and similar for close one okay command dot get it now we have to check with I plus 1 okay with close one yeah then what we have to do we have to append o okay now next for as if command dot get it I okay we are in this bracket okay and getting this El okay plus one equal to this I plus 2 hitting this equal to l I plus three then what we have to do to append Al okay guys so next what you need to do we just need to uh close it here now we have to return as stimulator we have to written but as we can see our return type is string so we need to convert this string Builder into string okay so SB Dot uh to string okay yeah it's done now okay guys so let's click on run button and try to check if all the test case has been passed or not yeah so guys here you can see that all the test case has been passed now we will go to uh Ms word and we'll try to understand each line of code like how it's working actually okay guys so here you can see that there okay this one and this is our string name command okay now you can see that we have given uh we have to iterate this string okay till the end okay now you uh this is 0 1 2 3 4 5 6 7 8 9 10 11 okay so we have given this string length Okay 12 now we have taken this string Builder Okay uh string Builder okay now in Java A7 what we use we have to use for Loop for iterating any uh string okay but in Java 8 we have to use in the Stream dot range okay and this will start from 0 to this command dot length Okay from 12 okay so it will 0 to 12 okay now in zero index okay it will check now it will start from 0 okay uh this will return uh G 0 index okay yes you can see that this condition satisfy so SB will add uh you can add here SP data G okay yes now for uh first index okay here you can see that it's an Open Bracket uh yeah this satisfy and for uh I plus 1 that is for second index yes it's in close bracket so this also satisfy so this will add this o now for third index it's an Open Bracket yeah this satisfy and fourth index it will uh close bracket yeah this also satisfy so this will append this o into this s b okay now it's a fifth index it's also an open index Open Bracket okay this satisfy and six index is in close bracket yeah this also satisfies so this has else if condition now what we'll do it will uh append this uh o into SB okay again similar for other one also okay now uh in length of index okay we have Open Bracket but in 10th of index we don't have a close bracket it's an A so it will go to uh next as if condition yeah just satisfy okay now next uh I plus 2 index is L yes this is also satisfy now I plus C also close bracket yes this also satisfy okay so this will append this Al into SB okay this one yeah so this is our final output and we have to convert this into a string because our written type is string so we have to use SB dot string okay guys so yeah so let's uh go back to lead code so I hope guys uh you have understand the problem and their solution but still if you have any question any query please comment it out in comment section I will definitely answer your question thank you guys for your time have a nice day
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.