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
645
hey everybody this is Larry this is day 22 of the Le on Discord let me know what you think about today's prom 645 said mismatch uh yeah before I start I want to just say um you know on my Discord and also just here um I talk a lot about grinding and just like working it out and how you know like even when I struggle with something I will try to stick with it as long as possible and sometimes you know it's very easy um I think especially if you only watch like a couple videos and especially this one I don't know if you watching this one cuz this is a easy one but I guess if you're watching then you're watching but I mean a lot of people might not right um but ah and thing is right like there's just if you kind of come here and you watch like the Yeezy PRS and stuff like that or even you know PRS that I've done before which is unfortunate but it is what it is and I do it amazingly fast it looks good but the truth is you know like you maybe now um but in the past I put in a lot of time I probably more time that I would like to admit like I said I've solved like tens of thousands of PR maybe not tens but just like 10 thousand prom say right many hours uh and even now though right and I don't always have the energy for this so sometimes past it I just want to point out that like yesterday for example if you check out my if you check out the weekly contest there was a really I want to say difficult Q for but it's not difficult it's just difficult to implement or like the algorithm is not that difficult to understand but the implementation is difficult at least for me right I took three hours doing it just like straight out grinding it out right so you know so uh just to kind I mean and you know some of it maybe I just need to practice certain things but just to give you a little bit of an example of like even I you know at least I mean at the end of the day you have to figure out what you want right in life in these Gos in lead code or whatever you have to figure out what you want and sometimes you know you have to be you know and sometimes yeah you just have to figure out what you want and what I mean by that is that it's okay like for me to be honest I don't really care about my or like I mean you know it's nice to care about my rating per se but I don't really try to optimize for it I'm not trying to like get a high score or whatever like if it happens it's nice I don't you know um just because that's not what I want in life anymore I'm not young anymore I'm not you know and I'm not saying that to diminish anyone who wants these things but it's just that you know as your age as you get a little bit older as life kind of takes its toe uh you just have different priority priorities and you just figure out um you know things that are important to you evolves over time right or what kind of things that are important to you um but so you know that said I still wanted to grind it out yesterday so you know it still happens but yeah I just want to kind I don't know if this that's motivational but it's just that like it's you know um if you have to be willing to learn and not settle I think is how you get better um and for me I kind of like actually learned a couple of minor tricks I don't even know if that's true I mean there a couple things I did learn but I think to be honest some of it I was also um just like just didn't certain symmetry just didn't occur to me for whatever reason which maybe on another day I would have gotten it but you know you have good days you have bad days you know um but how you handle the bad days determines who you are in life right uh anyway so okay so sorry for a long intro Let me uh but just want to you know um people ask me also a lot about like why I have this Channel and that this is why right like I you know I and even though I didn't finish the Q4 I still finished I think like 100 or 200 for something like that I don't know the ranks are always so weird because now there's like two servers and stuff like that um so you know I still think I'm Prett pretty good so I'm not like trying to like humble back like you know I'm not early in my journey anymore but that you know even I sometimes will take three hours on a problem so it makes you kind of uh giv you a sense of perspective on some of these things and that it's okay to struggle you don't have to like give up and look up the answers in half an hour right or whatever I don't or whatever that people always say for me it's I don't know I mean there are some nuances there and I'm not going to go it because this intro is already a little bit long uh but yeah uh today there is a premium prom so I will definitely check that out but uh but this one is probably easy one so we'll kind of just run through it shall we I am a little bit tired a little bit or like mod TI modly tired but uh cuz I just came back from running uh like 7 eight miles and I think I bad form today to be honest cuz um part of my uh my foot is like a little bit sore but usually it doesn't for that length bit I don't know I think I was just doing squats the other day so I think something is a little bit off but uh but yeah all right sorry for the 5 minute intro but if you're here you're probably here or I hope that you're here you know you can hit the Subscribe button and you're here just to you know hang out and chill because I think this one is probably an easy one anyway right so um and then we can go over it together uh all right let's go 6:45 set together uh all right let's go 6:45 set together uh all right let's go 6:45 set mismatch you have an set of integer s which originally contains all the numbers from 1 to n unfortunately due to some errors one of the S got duplicated another number in the set which result in the repetition of one number and the loss of another number you given an inur away nums okay um I mean yeah this is obviously way easy you can just kind of do like for loops and stuff right but and like look up tables and stuff like that I am curious whether there's like a funky constant well I mean there's no constant time because you still have to look at everything like constant space was the one that I would think about but I don't think so right because I mean the most obvious thing is just like summing everything why does my milk look so disgusting do me I mean it made it do me a body good but this one looks like it's doing me a body silly did I mix anything I don't know I'm trying to also drink more protein that's why I'm drinking milk but um all right yeah I mean I think my first thought sorry I think my first thought is just summing it I mean the other this is a trivial problem right and I don't you know like if you are struggling with this one then you just have to learn how to do um uh sets or whatever right but I am curious is there a slick way of doing it that isn't uh just like putting things in a set hm you know to be honest yeah I don't know cuz if you sum this up that means I just have three I mean there's still things that you can do in a funky way but it's just I don't know that there's anything um at least not I guess there is that like um permutation thing right uh the permutation cycle right um and the way that you would do a permutation cycle is just do a sort of a linear sort so that every number is in its index so then now two things will happen right one is um well one is that one number is cannot get back to its place so that's going to be the extra one and then also that slot is the one that's missing the number I mean that's not that bad actually so it's going to be all one extra space but I don't like in place algorithms just because it's not usually like I still consider it kind of linear space only in the sense that um you know if this was an API if this you have this help function uh your helper function should not manipulate the input data because like let's I put in some data a list where I care about ordering and you're going to return to me like sorted I'll be like yeah what is this API why is my things why did you solve my things you shouldn't solve my things I'm only asking for some unrelated things you know like it you know that's uh it should not change the state of my input so I think that's great eh but that's a curious thing but yeah um yeah we could do that I mean I could do that for fun we'll see so basically the idea here is you know you look at each number right and then is n num sub I or I if not then we want to make this true however we can and that means that nums sub I should go to a slot of num sub I right so maybe we'll just do um current is equal to this right and then num sub current then we by definition we want to swap because this number is not going to be the um num sub current is not going to be current just because current is already in nums of I so then you swap these two right so then you can do maybe like nums of I right um oops the only uh time where this is not true of course is that if there is already a repetition right or something like that so I think there are coup but yeah uh so okay so right if num sub I is not equal to I maybe we can even do it in a w Loop right then now we do a swap thing right and then we keep on going until num sub I is equal to I um unless um I think the only way that the only other condition is if num sub I is equal to num sub current so if num sub I is equal to num sub current we break right because then now we can uh I could just return I guess that means that the extra number is um I have to make sure I get it right soorry I'm a little bit slow today uh so num sub I is going to is so we want to move num sub I to num sub so this is the destination so that means that and if that means that if they're the same that means that the extra number is num well I mean I don't know I struggle this one the extra number is both numbers because both numbers are the same okay which one is the first one first okay so number and then the missing one is I or maybe I + one yeah I missing one is I or maybe I + one yeah I missing one is I or maybe I + one yeah I think it's i+ one um okay actually I think it's i+ one um okay actually I think it's i+ one um okay actually I messed this up a little bit because I think I use zero index things but this is one index thing so that's a little bit awkward but yeah so this is going to be just - going to be just - going to be just - one all right let me I for some reason I had zero index in my head so let me think about this first but I mean this is mostly structurally right but except I use one index or yeah I used the wrong indexing okay so that means that what is I do we examine every line or even the comment right so it's equal to i- i- i- one no oh yeah so I okay so I is from 0 to n minus one so that's index so then this number is going to be one index and so this number is also one index and this number this well I mean both these number are one index so we have to do negative one on both sides I know that they cancel out but I just want to be explicit here and then here we want we do want to return to one index thing so that's fine uh and here this is a zero in I is zero index and everything else is one index so and this case also it cancels out kind of if you want to put it that way and that's pretty much it this should return a thing so we going to do a SE Force um because this should always be true I think oh maybe I messed up it's okay so oh so now what so the S Vex is equal to oh I got the wrong this is the one index one whoops I don't know why I had it like that but okay yeah um am I confident let's give a AIT maybe I have a cly typo somewhere okay I do um why is this wrong so eight all right let's just print out nums after everything right h so it returns early so eight okay let's just print out after every swap I guess so here eight we changed okay and then four we change it to 0 1 2 3 okay that's good and then put to five here and then three oh huh I just return i+ one I three oh huh I just return i+ one I three oh huh I just return i+ one I guess that's not exactly accurate because I is zero oh huh I think I'm just really wrong on this one I so this is the extra number I thought that this because this is the extra number this is fine but actually it is not because um it just means that well it means that this is the extra number but it could be that another number can go here so I was wrong with the early termination so okay so that was well good practice though CU I feel like I don't know wa and then we can break right um H I know that I don't return the right answer yet but I'm just curious um of the states so I'm just going to play around a little bit I guess we have to return some non none things I just wanted to print the states just to make sure that I'm consistent okay so then one and so and then seven actually eventually swaps to one but then we just keep going right so then now sort it so now I guess we have to do one more loop I was trying to think what I can do without one more Loop but that's fine right so if num sub I isus one is notal to I then sub one is equal to um I guess of I oh no the index all right huh what was that t so low all right uh yeah I mean I did play around with it that how did I get it wrong last time I guess last time I was also trying to do it this funky way H what did I get wrong answer from H don't know but anyway yeah um this is going to be like I said infurious all one extra space but I don't know I don't really a fan of it and the other way of doing it is just you know use Lo up table it's not that interesting um but yeah linear time constant space constant extra space uh in place manipulation and that's all I have for this one let me know what you think and I'm going to do the premium problem next so yeah stay tuned hit the Subscribe button uh thanks for watching I'll see you later and take care bye-bye
Set Mismatch
set-mismatch
You have a set of integers `s`, which originally contains all the numbers from `1` to `n`. Unfortunately, due to some error, one of the numbers in `s` got duplicated to another number in the set, which results in **repetition of one** number and **loss of another** number. You are given an integer array `nums` representing the data status of this set after the error. Find the number that occurs twice and the number that is missing and return _them in the form of an array_. **Example 1:** **Input:** nums = \[1,2,2,4\] **Output:** \[2,3\] **Example 2:** **Input:** nums = \[1,1\] **Output:** \[1,2\] **Constraints:** * `2 <= nums.length <= 104` * `1 <= nums[i] <= 104`
null
Array,Hash Table,Bit Manipulation,Sorting
Easy
287
272
hello and welcome back to the cracking thing youtube channel today we're going to be solving lead code problem 272 closest binary search tree value 2. before we get into it you guys know the drill subscribe to the channel it helps me grow all right given the root of a binary search tree a target value and an integer k return the k values in the binary search tree that are closest to the target you may return the answer in any order you are guaranteed to have only one unique set of k values in the binary search tree that are closest to the target so let's look at an example where we have this simple binary search tree and we're given a target of 3.714286 given a target of 3.714286 given a target of 3.714286 why in the world they couldn't just give us a regular target instead of this long ass decimal number i don't know leak code be wild and sometimes anyway and k equals two so we wanna find the two elements that are closest to three point seven whatever uh so you know upon inspection we can see that those two are gonna be the three and the four uh because the distance between that uh this number and three and four uh are the two smallest distances uh if we were to calculate with two five and one those would all be greater than four and three so in this case we would return three four so you know visually inspecting a binary tree and picking out the best answers are quite easy how do we actually put this into code well let's talk about some of the approaches you could take to this problem because there are multiple approaches and we will converge on what should be one of the best answers we read the question prompt and we went over a simple example but we didn't really talk about how we actually want to solve this so let's go through some approaches so we know that we have what we have a binary search tree right and we're looking for the k closest values to a certain target so what we could do in our first approach would be an in-order traversal an in-order traversal an in-order traversal of this tree which we know that an in-order traversal of a binary search in-order traversal of a binary search in-order traversal of a binary search tree will give us all of the values in sorted order and then what we want to do is simply sort the array uh based on distance to the you know value target right so this will give us uh a sorted array now it's already sorted but we have to resort it to essentially get the closest value to um you know to our target so we can sort based on about criteria of you know how far is it so we'll use like absolute value of the current value in the array uh to the target right and we'll get a sorted one and then we can simply return this new sorted list the first k elements of that list and we're good to go unfortunately the in order we can do in log of n time oh sorry in big o of n time but the sort we know is going to take n log n which means that our you know total time complexity is going to be big o of n log n so this works and it's fine it's not a you know a terrible solution but obviously can we improve on this so your second solution is going to be to do the same thing we're going to still do an inorder traversal but this time around instead of sorting we can actually just use a heap here heap um to basically keep track of those k elements and we know that this heap is going to be big o of n log k where k will be the number of elements in the heap obviously each heap check is going to take log n time i log k time and we have to find um you know those n elements so we're going to do this it's going to bring down the time complexity to n log k if k actually equals to n then there's no difference between these two we might as well just do the sort but if k is actually less than n then this is a more optimal solution again this solution is fine and you could do it uh or one solution which i'm going to discuss but we're not actually going to do is going to be the quick select algorithm which uh if you're interviewing at google maybe you want to know because they asked this kind of but uh quick select uh in the average time we'll give you a big o of n solution for this problem but in the worst case can be big o of n squared which is no good because it's actually worse than the other two so quick select if your interviewer is looking for quick select you're in for some pain uh if your interviewer doesn't want quick select then don't write it because most of you probably don't know it i don't waste my time with that kind of nonsense um but there is a another solution uh which is actually going to be a um you know an inorder dfs plus a q here so what we notice um in this you know example is that we have to find the k closest elements and one thing that you can't actually see here because you're not looking at the delete code page but all of the values in the tree are actually greater than or equal to zero which means that we don't have to deal with negative numbers and because we don't have to deal with negative numbers at a certain point in our in order traversal we will hit a point where numbers just keep increasing right and if we start increasing and we're getting further and further away from our target there is absolutely no reason to continue uh processing the tree because we know that in an in-order traversal we're just that in an in-order traversal we're just that in an in-order traversal we're just going to get bigger and bigger values as we continue going so if the values are already too big then there's no point of us continuing and we can actually cut our dfs down to stop there so basically we want to you know approach our target from the left and look for you know the k closest elements and we may need to go a little bit to the right because some of those elements to the right may be closer than the ones that we've done from the left but at some point as the numbers increase in our in-order traversal we increase in our in-order traversal we increase in our in-order traversal we will hit a cap where it no longer makes sense to continue because the numbers are too big and we're just increasing the distance between target and our value right we're not actually getting any closer because the values will increase as we go so basically what we want to do is we want to approach from the left and keep track of um you know the k you know elements that we have and we'll keep them basically in a queue and what we want to do is after we basically pass the target in terms of value so say if the target was three once we start getting values like four or five six in our tree eventually there's going to come a point where there's no point of going any further because values from the left will actually be closer to target and we can actually just pick the best ones out of you know from the right side and then the left side and we can actually cut our um iteration here because like i said with the in order we're just going to be getting larger values and we're not actually going to be finding anything better because the distance is just going to keep increasing since there's no negative values in this array we don't have to worry about any of that so this will actually allow us to basically do it in big o of n time in the worst case we're going to have to do a you know big o of n traversal through the tree because k is actually going to equal to the number of nodes in the tree so we basically just have to parse all of the nodes in the tree which is going to mean it's big o of n which is you know the best solution that we can have here because it matches the average time of quick select but it's actually better than quick select because we don't have this worst time big o of n squared obviously it's better than n log k with the heap solution and it's definitely better than n log n with the sort solution so this is actually the solution we want to go with and it's the most optimal and we don't have to worry about quick select accidentally giving us big o of n squared because that's not good so this is actually your most optimal solution and this is the one that we're going to code up in a second so let's go to the code editor and write this up so you can see how it works in the code editor let's type this up so remember that we're going to be solving this uh this problem using a q to basically keep track of our elements so that way we always have access to the first element that was added to the queue in constant time and we can actually get rid of that element in constant time as well using the q's pop left function so we can't use a regular list because we can't get rid of that element in constant time so we're going to say q is going to be collections dot deck and we're just going to pass in an empty list here now we need to define our in order traversal depth first search function so we're going to say def oops def dfs this is going to take a node and remember if the node exists we want to go as far left as possible so we're going to say if node.left what we want going to say if node.left what we want going to say if node.left what we want to do i'm sorry if node then we want to say we want to call the dfs on the node.left dfs on the node.left dfs on the node.left now remember in an inorder traversal we go left then we process the current node then we go right so we have just you know gone as far left as possible now once that dfs ends then it's time to actually process the current node so now we're going to say if the length of our q is actually less than k so we haven't seen k elements yet we're just going to put in our value so we're going to say q the append node.val node.val node.val there's nothing for us to do here otherwise if our q length is k then we need to start making a decision of whether or not we need to get rid of elements or we can actually just stop our iteration here so there's two cases the first case is when our node.vowel is actually closer when our node.vowel is actually closer when our node.vowel is actually closer than whatever the top of the queue is in which case we're going to get rid of the top of the queue we're going to add node.vowel to our queue and then node.vowel to our queue and then node.vowel to our queue and then continue with our dfs the second case is when actually the distance between our current val and whatever the first value we put into the queue is our is already too big so our no dot val is actually further than that first value therefore we can actually just stop there so we're going to say if the absolute value of whatever q 0 minus target is actually greater than the absolute value of node.val minus target so value of node.val minus target so value of node.val minus target so basically in this statement we're checking is target uh closer to node.l checking is target uh closer to node.l checking is target uh closer to node.l or is it better is it closer to whatever q0 is so if no doubt val is actually a better solution then we just get rid of whatever is at the top of the queue so we're going to say q dot pop left to basically get rid of this q 0 value because no dot val is now a better solution and we're going to say q dot append no davao otherwise in this case what ends up happening is if we hit this else block we know that the length of our q is length k and we know that q of zero uh is basically a better solution than no davao which means that no matter what happens now this node.vowel will just keep this node.vowel will just keep this node.vowel will just keep increasing because it's an in-order increasing because it's an in-order increasing because it's an in-order traversal so the further we go this node.val is just going to get bigger and node.val is just going to get bigger and node.val is just going to get bigger and bigger which means that if this solution didn't work then getting a bigger one is just going to increase this distance so there's no point of continuing so we can simply break there because we will have found our k best solutions going to even bigger value is just going to increase the distance so there's no point of continuing so we can return there if that's true otherwise uh if we basically make it through here so either we hit this oh if we either hit this if statement or we hit this if statement then remember that's an inorder traversal we still need to go to node.right node.right node.right uh which means that we will now complete the kind of dfs alright so the last thing we need to do is actually just call our dfs function on the root itself and at this point we simply just need to return the queue and those will be our k elements let me just run this make sure to make any syntax mistakes and we look good to go so cool so that submits and you can see it's quite quick because it is one of the most optimal solutions so likely we talked about in the diagram the time complexity here is going to be big o of n and the reason it's big o of n is because in the worst case k will actually equal to the number of nodes in the tree which means that we're going to have to process the entire tree to basically get all of those k values into our queue which is our solution so that's why it's going to be big o of n because we have to process everything uh so for the space similarly our q in the worst case could end up storing you know those k elements um plus we also have the actual um recursion in the tree that we need to do with the dfs so in the worst case when k equals n our solution here uh is just going to be big o of 2 n but we know that asymptotically this is the same as big o of n so uh this is going to be a big o of n um time and big o of n space solution all right so that's how you solve this problem not the most complicated one i think once you kind of see uh how this trick works this is um you know something you kind of have to think about the other solutions are a bit more straightforward but this one is a bit more like oh once you kind of realize this trick where you can end the recursion early because you will just be getting greater elements and there's no point of going forward it makes this problem really easy and as you can see the code is quite simple anyway i'm going to stop talking here if you enjoyed this 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 otherwise thank you so much for watching and have a great rest of your day
Closest Binary Search Tree Value II
closest-binary-search-tree-value-ii
Given the `root` of a binary search tree, a `target` value, and an integer `k`, return _the_ `k` _values in the BST that are closest to the_ `target`. You may return the answer in **any order**. You are **guaranteed** to have only one unique set of `k` values in the BST that are closest to the `target`. **Example 1:** **Input:** root = \[4,2,5,1,3\], target = 3.714286, k = 2 **Output:** \[4,3\] **Example 2:** **Input:** root = \[1\], target = 0.000000, k = 1 **Output:** \[1\] **Constraints:** * The number of nodes in the tree is `n`. * `1 <= k <= n <= 104`. * `0 <= Node.val <= 109` * `-109 <= target <= 109` **Follow up:** Assume that the BST is balanced. Could you solve it in less than `O(n)` runtime (where `n = total nodes`)?
Consider implement these two helper functions: getPredecessor(N), which returns the next smaller node to N. getSuccessor(N), which returns the next larger node to N. Try to assume that each node has a parent pointer, it makes the problem much easier. Without parent pointer we just need to keep track of the path from the root to the current node using a stack. You would need two stacks to track the path in finding predecessor and successor node separately.
Two Pointers,Stack,Tree,Depth-First Search,Binary Search Tree,Heap (Priority Queue),Binary Tree
Hard
94,270
1,300
hey yo what's up guys babybear4812 coming at you one more time uh first off forgive me for my uh ridiculous looking ensemble it's freezing today the heat isn't on in the building and um yeah that explains the sexy look but here or no he we got questions to answer and today's question is 1300 so it's one of the newer ones and it's the sum of mutated array closest to target now the question is i think it's a bit unique i haven't really stumbled across many that were like this and it tells us that we're given an integer array r and a target value called target and we need to return an integer value such that when we change all the integers larger than value in the given array to be equal to value then the sum of the array gets as close as possible to the target okay so it's a bit of a mouthful but so we'll kind of walk through what this actually means it says in case of a tie we return the minimum such integer and what i'd argue is the hardest part of this question is uh to notice that the answer is not necessarily a number from uh the array itself and we'll see that in they don't really give a good example of that here but i'll we'll walk through an example and see where that happens so imagine we're giving this uh this input array here and the target is 10. the output we would return is three and again we'll talk about how we're going to get this but the reason we're returning three is because uh when using three the array converts the three 3 which sums to 9 and that's the optimal answer the reason it's sum it becomes 3 is because if the value we're outputting is 3 we're saying take every number in this array that's greater than 3 and bring it down to 3. so four becomes three nine becomes three becomes you stays as it is so we got three uh that would sum up to nine which is as close to ten as we can possibly get in this question if we tried something like four for example we'd have four would stay as it is the nine would become four the three would remain as it is we wouldn't change it so we'd have four three because three is less than four and that would sum to eleven um since we're told here that in the case of thai we return the minimum of the two integers that's why we would return a three in this case instead of four even though eleven and nine are the same absolute distance from ten we're choosing the smaller integer hence three in this problem here uh in the second example we've got two three and five so this one's kind of in increasing order as you notice here this one was not we said that the output is five here and the reason the output would be five is to think about the following well um you know if do i put it or what let's put it this way if we're outputting 5 and we notice that 5 is already the largest number in this array none of these numbers will actually be changed we can actually see here that 2 plus 3 plus 5 already equals 10. so the sum of the array is the target and so when we're outputting five really we're saying don't change anything in this array an equivalence statement could have been return 10 or return 50 or return 100 because remember we said whatever we're returning we're going to take all the values in the array greater than that number and reduce them to that there are no numbers greater than 5 there are no numbers greater than 6 or 10 or 50 or any of the numbers that i mentioned the reason we're returning 5 though is because it is the smallest of all those possibilities um in this series so we're not going to go through the math here on how this one checks out but uh the target is 56 803 and the output notice is 11 361. none of these numbers is 11 361. what we notice though is that if we you know 11 361 is smaller than all these numbers and if we were to that means that by replacing this we're implying that we need to change every single one of these numbers to eleven three thousand uh eleven thousand three hundred sixty summing that up would get us as close to 56 803 as possible um so i hope that at least you know the question uh makes sense now i don't think the answer is obvious and we'll obviously walk through how to get to these numbers um but that's what the question is asking now we look at a few of these examples here so i've copied them over and i think one thing that needs to be addressed right off the bat here is if we're looking for all the numbers that are greater than um than a certain value we have right now the kind of the intuitive first step to take would be to sort this array we're not concerned about the order of these numbers so we're not concerned about if they're uh numbers larger than value that come before or after a certain index we just want all the ones that are larger or smaller than a value if that did matter then this would be a whole lot more complex because maybe then we'd have to think about like what the longest increasing subsequence would be or one of those kind of related problems that i'd argue are harder and would definitely make this a really tough problem but since we don't have to worry about any of that we can go ahead and say let's go ahead and sort this array so maybe instead of thinking about this one um we'll sort it to become three four nine meaning that no matter what we do from here on in our minimum time complexity will be o of n log n okay so that's gonna be something to keep in mind as we go now how do we even begin to think about this question well okay we have it in sorted order um i would then argue the following since it's in sorted order we can almost walk through it increasingly and maybe every step along the way we make some sort of decision or see like what happens if i change all the numbers from here on out so if i change this three or maybe i return and say hey three is my answer everything here is going to be changed right if i change something here then everything after the four is going to be changed if i'm looking at this you know longer example over here if i not change sugar maybe i say 5 is my answer 12 is my answer i know that everything after this will become a12 or everything after this will become a 5 or a 4 or whatever number we end up choosing so if we think about walking through this sequentially really the question we're asking ourselves every single time is what number would i really want right now okay what number would i really want right now and so i would think about the following if we know that we need to get to 10. i know i need to get to 10 and i'm starting i'm sitting pretty here at the beginning of my array and i know i need to get to 10. in an ideal world if i could have my pick of the litter what number would i want this number to be and all the rest of them to be so if i've got three elements here and i want to get the 10 and i want all of these three elements to sum up the 10 in an ideal world i want each of these numbers to be 3.33 i want each of these numbers to be 3.33 i want each of these numbers to be 3.33 i know these aren't integers but if we just think about doing the division really i want to have my target divided by my length and if i could have that number that would be awesome because i could just i could literally divide it and i know that from wherever i'm sitting the length of kind of what's left um if we were to take the target we need to divide it by that length we would get exactly what we want problem is we can't return integers or sorry we can't return decimals here we're working with integers so what i'm going to do is that every step along the way i'm going to say i'm interested in the target that i have and you know divided by the length and now i'm going to round that number well if we round 3.33 we do actually get well if we round 3.33 we do actually get well if we round 3.33 we do actually get 3 and we notice we're already sitting on this three right over here so what we're saying is if i get my ideal answer as close as possible to it i need to change all the numbers from here on out to be three right and it just so happens that this already equals three that number that we want is in the array and so that's how we're gonna get there okay this first example though i think these examples are a bit weak because i don't think they fully kind of illustrate the thought process so if this one didn't paint the picture fully i promise through the next riddle it'll make a bit more sense uh because there's a bit more complexity to it than that let's pretend now that i'm walking through this area this one here is sorted i'm sitting at this too right i'm sitting pretty like i said and the first thing i ask myself is well i want to get to 10 okay i want to get to 10 and i know that from here i've got a total length of three how to me um in an ideal world i want all these numbers to be three point three right so by rounding i'd want them to be three okay if i want all these numbers to be three problem is i can't change this number to three it's gonna be a two right because two is smaller than three i can't change it if we had something like six seven and eight were my three numbers and i knew that from here i wanted all my numbers to be three easy i report or i uh i return three because all of these since they're all increasing or at least they're level they're either level or increasing they would all have to change to a three but that's not what happens here so maybe what i can do is i can track something like um my number needed at any given step of the way okay my number needed in this case would have been three however i'm not sure i can do much with that because you know i can't change this number here so i don't really think this goes the answer i'm kind of i'm walking through the thought process we'll formalize this in a moment but that's kind of where we're thinking so far all right what if i take the next step over now i'm going to start looking at this the second index here well if i'm looking at this number here and i want my sum to be as close to 10 as possible i need to acknowledge the fact that whatever has happened behind me is now invariant i can't go backwards and change things if i change you know this number and maybe i notice 3 is my answer and i want all the numbers greater than 3 to become a 3. this number is going to be unaffected because we originally sorted it everything behind me is fixed i can't do anything about it these numbers before me are already going to be part of the sum that i want this 2 is going to be part of the sum that we're using to get toward the target so what i need to do then as i'm tracking this is to keep track of the sum that i've had of all the numbers so far that are not changing so far i've had a sum of two this sum of two will stay here no matter what whatever i choose to do from here on out all good but we need to make uh take into account the fact that we've already taken two off of our target and our total sum what does that mean for us that means that now i've got two possible numbers i can change now do i want these two numbers that i have left to add up to 10 well not necessarily i need to get them as close as possible to eight the reason i need to get them as possible as close as possible to eight is because i want ten i already have two so i need to get eight from these two numbers what does that mean that means i'm interested in finding my target minus my sum so far right so some so far which again is two for now and now what am i dividing that by well i want eight to be you know split up among whatever is left and so that in essence is equal to the length of what i've got uh this entire array minus where i'm sitting right now i'm sitting at index one so minus index three the length of this minus one gives me two i'm interested in finding the total sum minus whatever i've seen divided by whatever is left and whatever's left is this total of two units so this right over here and of course rounded again like we did before because we need to return integers is going to be the logic behind how we're determining what number we need from here on and if i was to change all my numbers from here and out what number would i want well in this case uh our target is 10 and our sum so far is two that gives us eight my length minus my index so however many units are left that's two would give me four okay that means i want to get four now could i change this number to a four no unfortunately i can't because it's smaller than before so i keep going and again this will become more clear when we go to the next example but i keep going and i acknowledge that okay well so i can't change anything here but i have now seen the three of three's now invariant i'm gonna add this three to my trailing sum and i'm going to have a total of five okay i'm taking my next step over now what number do i need from here on out to make the magic happen well i need my sum so far has been five and my target is ten so i need five more over how many units can i change to become a five potentially if they're all you know uh greater than five well my length is three my index is two so i only have one unit left here five over one is five meaning that the number i need is five oh wait well we are five we're looking at the five meaning perfect we found the number we needed it's equal to the number we're looking at right now awesome we're returning five so once we see it we return five and that's it and that's how we solve this one over here now the i think one of the harder parts in this question is what if we can kind of acknowledge like i think this formula makes sense i think at least for me what i struggled throughout my head around the first time is how do i decide when to stop like when have i found um that number that i needed and it's got some sort of relation to the number i'm looking at here so we saw that the three and the two are somehow related like we weren't too happy about the fact that we needed more than we had at the moment then we had the same issue with the four and three and then finally in this case we said okay well we need a five and i have a five so cool let's return it but you know what if we had this case where the number we want isn't in the array so what we need to think about is what i'll call our exit condition is again we i think we've determined this relationship this one it ain't the hardest thing to figure out i think this one is you know not easy to see the first time you look at this problem but i think it's digestible the part that's left that i really want to formalize is going to be how do we determine our uh relationship between the number we need and the number we have so far when do i say okay i'm done i found my best possible answer and i'm going to return it i've drawn out a bit of an extended or a longer example here which we'll walk through relatively quickly but i hope that uh you know by walking through this example we'll answer that question on when have we found the number we want to exit at so we've kind of determined what we might need to do is we're going to need to keep some sort of sum or some so far and i'll keep a track of also the number we need at any given point and so this total array has got a length of three four five six uh seven so i'll say length equals seven and i'll just i'll keep that up here and i've written this example out on paper just so i can skip doing some of the math and wasting time there um let's say we were to start this example you know from scratch if i had uh my target was 100 and my first number well forget even the first number per second if i could ideally you know pick a number uh from which uh which i could set this entire array to in order to get a hundred that number would be after rounding it would be 15 right 15 times 7 would give us 95 that would be the closest that we can get if all of these numbers hypothetically if this 2 was a 22 and this was a 23 and this was 25 and we kept increasing then i could just realize that well i can change all these numbers to the 15. reason i can change them all to 15 is because they're all bigger than 50. okay so that should tell us something if number needed maybe number needed is less than or i'm also going to say equal to because we saw equals in the previous example uh the number we're looking at or maybe uh afi return num needed and that's going to be the logic this is really the formal logic of what our exit condition is going to be i acknowledge here that if i could set all these to 15 we'd be happy campers that's the best i could do can i change it to 15 can i change all of them to 15 i should say i cannot why can i not do it because we know there's at least one number right here that would not become a 15. i don't know what's going to happen with the rest of these i haven't checked them yet you know maybe this is 30. maybe this would become 15 and maybe all of these would become 15 but we don't know that yet all i can say is whether or not this one for sure can become a 15 it cannot so we could keep going and searching for a more ideal answer we acknowledge that we've seen this number so you keep a trailing sum and that's two and finally move on with our lives next from here on out we notice that we now need to get a target of 98 100 minus this two to get the 98 we need to change we have six units that we can work with 98 over six again rounded here would give us 16. however 16 is larger than this number here i can't change all these numbers to 16. no matter how badly i want i acknowledge that say roger that you add this up as the trailing sum and you keep on going about your way we get to this next unit over from here i need to get now we've got we have had 7 so far i need to now get 93. i need to get 93 from the next five elements 9 3 over 53 over 5 93 over 5 yes rounded would give us 19. can i change all these numbers to 19 i'm sorry guys i really got to take a call my bad i'm really sorry about that guys so i was waiting for this call to come in so i really had to take it when it came in but anyways as i was saying we the number we need from here on in would be a 19. um we can't change this number tonight and we know that for sure so we go on with our lives and we keep on searching tomorrow will be a better day or so we hope i then get to this number over here so far i've had uh my sum so far has been 10 okay so i need to get to 100 minus 10 which is 90. i have four you know four numbers that i need um to get to 90 with the closest i could do there 90 over 4 would be 23 right when we round it if i do 23 um well that's not going to help me because i can't change every single one of these numbers to 23. the search continues we add 12 to the numbers we've seen in our trailing sum we get to 22. now um now from here on in we're pointing at this spot now our target is 100 we've already seen 22 so we need to get to 78 okay we need to get to 78 and we have three numbers to get us there 78 over 3 rounded would give us 26. oh lo and behold we need all these numbers to be 26. this number is a 30. since this number array at i of the index is greater than the number we need we're going to return 26 because each of these numbers can and will become 26. so at this point we're done we stop off we return 26 because the number needed is less than or equal to these uh this array at the index i as we're walking through right so this is really the crux of it we need to a sort and then b keep a sum in this number needed trailing as we go and the second we see that our number needed is less than the array i we're going to return that number that we need and that's all there is to it if we were to hypothetically let's say keep filling the story i just want to show you guys what that would look like um we would get here to 52 and then um and then we'd say you know from here on out uh we would have let's see uh we'd get to we need 24 here uh this would be 93 and then we'd have uh seven and that is such that is the worst line i've ever seen 937 and we need like things 148 would be our sums this wouldn't even make any sense um so really the issue is with these numbers from here and out is like let's say i looked at the seven like sure 7 is smaller than 26 but that means that if we set seven all these numbers will become seven right it's not like just this one would become seven so that's why it's not an option i can't leave the rest these as they are and make the 53 a seven right since these would all become seven i'd have you know 7 times 4 is 28 plus 10 we have so far is 38 and so you can see we almost like we're increasing this number needed and then we decrease down uh you know afterwards and so once we hit this kind of this peak if you will that's where we're going to return it again based on this condition over here uh i think that was a bit of a longer explanation that computer's starting to heat up which means it's really been a while and it's not happy with me um but i wanted to make it as thorough as possible because i found at least the logic to be a bit tough to grapple with that said at least the trade-off is with that said at least the trade-off is with that said at least the trade-off is the code is going to be super short if we got like seven or eight lines and yeah and that's really it so let's um let's have a look at the code we'll figure out how we're going to get it done uh we're given up an actual array and you know the arrays already got it's sorry we've got at least one number in the array they're all legitimate positive numbers so we don't need to do any error checking what we do need to do is take the array and sort it like we said we would uh we then said that we're going to need to get some sort of uh trailing sum going i'll call it trailing some well we'll start it at zero because we haven't even started anywhere yet um we haven't had anything in uh then i'm going to say for i in range and the length right so this is the index we're going to be walking through one by one and we're going to say the following we're going to say that the sum we need so some needed is going to be equal to we had our formula so we said we're going to need uh the target minus the trailing sum so whatever we've had so far divided by the length so the length of the array minus the index right so that's what we had up here so length of the array minus the index because that's going to tell us how many numbers we have left as we as are sequentially kind of getting shorter and shorter how many numbers do we have left that we can change the trailing sum will tell us that we have an invariant sum that we've already taken into account and as we're kind of shortening it's more fixed we only have a smaller amount we can play with and to get this number like we said we're going to round it um so we get actual integers once we do this once we check our sum needed we decided or we kind of deduced logically that if the number we need is smaller than the number we're looking at then we're going to return smaller than or equal to excuse me the number we're looking at we're going to return the number needed so if some needed is less than array at i less than or equal to saying less than or equal to we're going to return some needed otherwise if we didn't return it so imagine our first step here we said we needed you know we needed 15. uh we can't do x it's greater than two so then we said okay we're gonna have to take this two as an invariant and we're gonna add it into our trailing sum so uh trailing sum plus sequels array of you're recording this now that final part of the video i lost the audio for some reason so i'm just jumping back in real quick to finish this explanation off um after we've done this actually this is all we're ever going to do for our for loop if we don't at any point actually return this sum that means we've gotten to the end of the array so imagine here or you know our earthquake was a thousand instead of 100 for example uh if that was the case then no matter you know where we got to the number we need to fill up this gap to 1000 would be way more than any number we have here in the array meaning that all we could do is return this final element um if that number we needed was again greater it was 100 or 200 or something along those lines well that's not the minimum possible answer we can return by returning the final answer in the array we're stating that i can't change any of these numbers because this is the biggest number there and so that's why our final statement here will be if none of this works we're going to return the final number in the array and i'm going to run this uh super quickly and press submit now just to prove to you that it can be done so you can see it's good runtime good memory usage and the complexity because i know a lot of you told me to start including that in the video the role we're doing here is we're doing a sort which would be n log n time complexity this walkthrough here of the array is linear and within this array the only variables we're keeping track would be the trailing sum i guess technically the index and the sum needed all of which are our constant memory so be of n log n time o one space super efficient um and yeah i hope you guys enjoyed i hope you learned something uh this was uh again it was a bit of tough one for me to grapple with so if you were struggling with it i hope this eases the pain at least a bit as always let me know if you have any feedback down below questions comments concerns like comments subscribe share i always trip over that part all that fun stuff and as always i'll see you guys in the next video peace
Sum of Mutated Array Closest to Target
critical-connections-in-a-network
Given an integer array `arr` and a target value `target`, return the integer `value` such that when we change all the integers larger than `value` in the given array to be equal to `value`, the sum of the array gets as close as possible (in absolute difference) to `target`. In case of a tie, return the minimum such integer. Notice that the answer is not neccesarilly a number from `arr`. **Example 1:** **Input:** arr = \[4,9,3\], target = 10 **Output:** 3 **Explanation:** When using 3 arr converts to \[3, 3, 3\] which sums 9 and that's the optimal answer. **Example 2:** **Input:** arr = \[2,3,5\], target = 10 **Output:** 5 **Example 3:** **Input:** arr = \[60864,25176,27249,21296,20204\], target = 56803 **Output:** 11361 **Constraints:** * `1 <= arr.length <= 104` * `1 <= arr[i], target <= 105`
Use Tarjan's algorithm.
Depth-First Search,Graph,Biconnected Component
Hard
null
968
hey everybody this is larry this is may 16th the 16th day of the may leco daily challenge hit the like button hit the subscribe button join me in discord let me know what you think about this prom this kind uh just this farm i guess and today and whatever as i am you know have this relock style um just to give an update uh during the two weekly contests i finished uh 44th and 47 i think so i don't know it's a minor victory but you know it could have been cleaned up but it was a fun contest hope everyone did them or enjoyed them and let me know what you think on the discords or whatever it is so anyway today's problem is binary tree cameras and uh i am solving this live so it's a little bit slow uh or whatever fast forward skip ahead do whatever you need to do watch it on you know 5x or something out or maybe that's too fast i don't know if you could understand let me know if you can understand on 5x but all right so we start for a binary tree you install a camera on the note of the tree you should now have this pairing itself an immediate child okay so this is basically i um my okay well okay i was gonna just guess at what the problem was asking but i've been doing this really bad thing lately where i keep on miss one line of uh problem statement and then it just it became a different form it even happened on the contest today uh earlier whatever anyway so okay um but we need to calculate the number of cameras monitored to or note of the tree so okay so we can think so i think we can do this recursively um it is i was gonna say we can move first but um let's see i mean it's essentially the idea is that okay well let's simplify the problem in order to kind of see if we can get a concept going and the idea is that okay for these three problems um where you have to look up and down and this isn't already the case but this is the way that i'm looking at it now um first of all start with linked lists right um let's say you have a linked list what does this mean well this just becomes a problem of uh okay maybe the dynamic programming where we're okay for every root node we have to either have a camera which satisfied you know both its children or um or if it doesn't then one of his child has to or both i guess so okay but how do i phrase that so okay so let's actually let's think about this and i don't know if this is quite right to be honest um and usually for dynamic programming i'm not gonna lie um i do usually use lru cache and i almost typed it already uh or cache in the new python three eight or three nine um so that's but all right but let's just write cache as you go to i'm gonna use a default dictionary of an int a little bit different than i do usually but yeah let's go cover this root so let's say we have a node right and then we should have some parameters what are those parameters so we have the node and can it be proof or yeah um the node and whether we need to do it right need it maybe it's um because then i think those are all the scenarios that you need um so yeah if no needed is in cash we return cash of no needed otherwise at the very end let's just actually set this to the key so that i don't have to keep on typing it um okay so what are our scenarios right if this is needed then well then we have a couple of scenario so that means that this node is gonna have one um so okay so presses together let's just do count is equal to zero well maybe not that um okay so if we needed to set this then this count is going to be one and then now we can um return cover of node.left uh this is false because now we don't need the next one to be true and someone like that right um oops so this plus one i guess um and also just to kind of make it easier if node is none return zero but yeah so basically this is saying if we needed to use a node then we don't need it for the children notes right and then otherwise oh actually well i mean this is true but we should cache it i forgot that i'm not using lsu cache to be honest um okay and then now if we don't need it what happens right well that means that wait let me think about this for a second hmm is that good enough uh okay if we don't need it then it means that yeah okay if we don't need it then um then we need one of his child to be true right so yeah so so either we do this is one of the possible um okay press is equal to some infinity value um let's say you know s is equal to min of that's right if this is not needed oops uh let's this is awkward a problem i think i don't know but yeah and then now if this is not needed then what can we do right if this is not needed that means that this is already covered then we can choose not to cover it um yeah and what is that option well that option means that huh this is awkward so i'm trying to think about how to say you don't need it but you need to chill them to need it uh let's see what am i thinking because you don't want the root to always have to need so if uh maybe a just a parent note okay let's say the parent true force value um and then now we only needed this but yeah the parent is true it just means that you know the parent has already has a note right if this was needed then yeah otherwise uh if parent so if the parent is true then this doesn't have to be true and also neither of us neither of the children has to be true right so but this is not force and because we don't need it just doesn't do anything so yeah um otherwise if the parent is forced that means that this is needed this is a really awkward way of putting it my needed thing is a little bit awkward i think the reason why is because um i'm just having an awkward case with the parent i think i'm just trying to generalize the parent or the root sorry i think if i don't generalize the root then we're okay so i think we just need to uh yeah maybe we just need the parent i think the parent is more of a thing is that true man i'm just having an awkward time with this one to be honest uh okay so this is parent what happens well if the parent is true then this one doesn't need to be true and then we can go to okay i think maybe what i had was good but this is very awkward to understand to be honest so yeah uh okay so if the parent is forced and this wasn't needed then either we needed next on one of the children or both you could so yeah so answer is equal to cover of note left either left so you need it at left and the parent is false plus cover note of right we don't need it and this is true the parents are still false um or the other case is just the right is uh needed and of course these cases overlap so i think this should be exhaustive this is very awkward i'm not confident about this to be honest but uh but now at the way and we just do cover root uh we don't need it and the parent is forced okay let's give it a spin but yeah sometimes in dynamic programming uh maybe that's what i wanted to highlight is that it's just about going through all the cases and really think it through about what are the states in every possible way and this may be wrong and this is wrong it turns out um why is this zero tell me why oh because this could be um so this has to be true on the oh this has to be not none for us if no dot left is not none if no dot right is not none um if this is a leaf what happens if this is a leaf and this is not needed then this could just be zero so we will i think we're okay there where are we is the default zero hmm yeah maybe that is a better uh return case and that's why i uh yeah again this has to be cached okay whatever press is equal to zero maybe let's see okay so that looks good but i am not confident about it to be honest uh and if you're not confident about it at home that you know that's perfectly normal for that reason um but i am just going to give it a spin because well let's at least try the mt case do we have at least one node okay fine i think one node might be wrong actually because yeah um because it's saying that the first one is not needed okay wait um oh it's actually this is the base case is wrong this should be true wait is that needed uh i don't know the base case or the starting case because okay this is a hard part or awkward problem for me i feel like there's a easier way to do this too to be honest but uh but i'm struggling with this part am i yeah no i am a little bit awkward so the tricky case that i'm thinking of is that if you have six notes um you know like six straight out in the length this you only need two um we could actually test that case real quick let me look at this pop-up oh i'm doing let me look at this pop-up oh i'm doing let me look at this pop-up oh i'm doing it nope maybe i don't know how the format goes i'm just guessing but apparently i was wrong so there's six this should give three or two sorry okay so that's good so i think maybe just the one case is wrong maybe because basically it is not needed why do i say it's not needed because we need it then we always use the node but if there's only one node that's is that the only case where that's not true though let's say we have three well i guess that's just the same as this first k so that's oh one about four i'm really awkward on this one i'm trying to figure out how to do the handle the kick off case usually that's easier okay so this is wrong probably for the same reason that this is so okay so now i'm so i was right to be not confident about this one um why is that so basically if this is uh i think this one is just a really awkward case if the if we need it well the parent is definitely false but i need it is checking whether it's covered if i think i just i think this is just a bad case i think if um yeah so if no dot left is none and no doubt right is none then let's have to some cases um so if needed if we need it then this actually is really bad that means that something messed up so actually but if parent if the parent is good then we don't return to zero otherwise we return one um none objects yeah i think what i sometimes i make this mistake where i use none as the test as the base case but i maybe i shouldn't have because that complicates things as well uh yeah okay let's what happens if none is not a base case sometimes it does simplify a lot of things but sometimes it in this case does not um yeah maybe it's still okay this looks better i'm a little bit more confident about it i think i just i had this case which is same as here but um but i needed something on this side as well i think uh which is why i was giving uh a bad answer maybe all right let's give this a minute let's forget a test case i'm still not that confident to be honest um yeah okay actually i should have tested this one though now i feel a little bad so this one is just like three notes and i get two instead of one how did i that's like such an obvious case but this one is not how do i get that one right and not this one but yeah in this case as you can see it is just a lot of case analysis and okay so like that is very odd because you think recursively that um they have the same properties but maybe not because you know okay so in this case we go to the so this could be two so if this was not needed um yeah parenthesis force uh yeah powerless force um oh that's right wait what uh oh yeah that's right actually no i knew this one oh i was thinking about this one but i was being a little bit dumb um because basically wha what there's another case where that if the pet how'd that for uh sloppy yeah um but yeah basically right now we're saying that okay we don't want to put a note here but you also want to end to the case where you do want to put a note here which is probably why some of the things so for example even if the parent has a note we can still put a note here right so that's basically the idea here so yeah so it's not needed but you know we can have a plus one uh and yeah and that will maybe give us a better answer but you know this one as well so yeah okay so this looks a little bit better so that i was actually missing a really big um case and i think that's why this hack thing is a little bit awkward do i still need it now that i have that because i think yeah i was a little bit sloppy okay so that looks good under these cases let's give it a submit i just totally forgot an edge case yeah okay so i was actually pretty close to be honest it's um yeah so it was accepted uh to be honest yeah like i said it is way um i was way close i just i was thinking about it while i was doing it but then i just forgot about it when i after because i was i spent too much time on these two cases and when i needed them then i just forgot about this base case so yeah um okay how do i want to say this so as you can tell sometimes dynamic programming is very exhaustive okay get it no okay i mean you probably got it just wasn't funny but anyway that aside um now you do go for all the tests all the uh order possibilities and go for the cases and after that you know it happens um so yeah so let's define these real quick so node is just a node uh needed is um you need this note to have a camera and parent is parent uh a camera node or whatever so that's basically it and of course for each so talking about complexity uh how many inputs are there for node right node it's going to be n needed it's going to be two inputs paren there are only two inputs because they're both only true or force right so that means that in total they're all of four times n or just of n uh number of possible inputs and yeah and for each one of these each core we do all of one work right because everything is just recursion and all one uh we do a set amount of them so there's no for loops or anything so yeah so each input does all of one work so total is o of n time and of n space uh of n space because again the four times n number of inputs so you need that to store it in the cache um this is tiring hope this makes sense um i mean i don't think i did any so i think this is a cool or a decent way of doing dynamic programming um or the video is a decent not explanation but like a discovery of dynamic programming of okay you know literally you just go over every possibility and like i said sometimes it's exhaustive right like i don't think i have any crazy math insights i don't have crazy like you know whatever um it's just about doing enough prompts and i'm thinking about every possibility um the only thing i would say is that you know you do enough of these problems you do get to solve them faster because of common patterns or whatever um and in that way you do go faster and sometimes if you see me do other dynamic programming problems because i am practiced and familiar with them uh you'll just see me like go straight into typing it and that's why um but you know sometimes you just have to be dilution and be careful and yeah and i was not careful as you can you saw as well because i missed this really big case that was very obvious but i just kind of sometimes on videos when i'm talking i just get distracted and forget so it is what it is but yeah um let me know what you think with this problem uh hit the like button to subscribe and join me on discord uh have a great week this is sunday or wherever it is yeah just have a great week hope you all do well and stay good stay healthy and i will see you later bye
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
208
hey everybody this is Larry this is day 17 of the liko data and hit the like button to the Subscribe button drop me on Discord let me know what you think about today's form 208 Implement try a prefix tree oh guys I mean there are a couple of ways you can do this but this is uh one of those textbook things I don't know that I'm gonna spend too much time explaining this one um I wonder if I did in the past but today I am very tired it is squat day even though it is Delo but I am just tired so um yeah and I've actually you know this does come up as a bit though so I do recommend people learn how to do this in a good way um because uh for legal problems they are definitely more than a few of these that will come up and you know if you have some that's already implemented or have a good idea of how to implement it well that's going to be good uh because that is basically the idea okay so yeah so um yeah the way that I always write it and you know is that I have a node and each node basically has a lookup table of the edges so maybe you could even call it edges and yeah and there are a couple of conventions you can do you can maybe do a Boolean thing of like s n meaning that is still worth the ends of this thing so it starts at first maybe but you but there's also another convention where you can use to serve that edges of like a dollar sign um uh assuming that dollar sign is not part of the alphabet um then to kind of Mark that it's true but you know that's up to you but today I'm going to just use a Boolean value um yeah or hasn't maybe I don't know yeah so then now self-doubt good is you're going to try self-doubt good is you're going to try self-doubt good is you're going to try and know right if I also need some helpers um but yeah maybe I'm a little bit lazy today we'll see but yeah so then now uh Kern is gonna stop that will foresee in word um if c not in current edges then current that edges of C is you're going to try node and then Kern is going to turn that edges of c and then at the very end current is n is equal to true uh search is going to be about the same idea we probably could reuse this maybe but it's not quite as you it's not even though the idea is very much the same it's not it's you it's very common that there's not quite the same right because you don't want to create edges for no reason because then it deteriorate your performance at some point so if we want to return Force right so that's basically the idea uh the difference uh yeah and then return current is n right um and it starts with is actually exactly the same except for that now it's just returned true because it doesn't matter whether a word ended there where this assumes that the word will end there so yeah uh this spell seeing the word oh this is prefix okay fine yeah looks good let's give it some it hopefully I didn't miss a case and I didn't 1081 day streak um yeah how long did I take for this one yeah like a couple minutes but you know uh you should be able to do this one way quickly because it does come up not just because twice will come up which is true but try will come up as part of a harder problem so that you have to be able to get this really quickly and then use this to solve something harder so that's why I definitely recommend y'all to kind of you know practice and get familiar with the ideas about this as well and as much as you can yeah uh this is the top the note class and then let me and this is the rest of it I suppose um yeah so each of these is going to be linear in the size of the word uh the size of the input which is O of L maybe you could say for the number of uh letters in the word and yeah and you can really do faster than that because excuse me because that's the size of the input uh so yeah that's all I have with this one let me know what you think let me know if you have any questions let me know if you want anything and try reviewed especially if we're going to get more tribe problems um you know in the coming week or the coming days weather in this week so yeah anyway that's all I have for today let me know what you think stay good stay healthy to good mental health I'll see you later and take care bye
Implement Trie (Prefix Tree)
implement-trie-prefix-tree
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker. Implement the Trie class: * `Trie()` Initializes the trie object. * `void insert(String word)` Inserts the string `word` into the trie. * `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise. * `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise. **Example 1:** **Input** \[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\] \[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\] **Output** \[null, null, true, false, true, null, true\] **Explanation** Trie trie = new Trie(); trie.insert( "apple "); trie.search( "apple "); // return True trie.search( "app "); // return False trie.startsWith( "app "); // return True trie.insert( "app "); trie.search( "app "); // return True **Constraints:** * `1 <= word.length, prefix.length <= 2000` * `word` and `prefix` consist only of lowercase English letters. * At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`.
null
Hash Table,String,Design,Trie
Medium
211,642,648,676,1433,1949
406
hey what's up guys come here and so this time let's take a look at another leet called problem number 406 cue reconstruction by height okay you're given a random list of people standing in a queue and each person is described by a pair of integers H and K where H is the height of the person and the K is a number of people in front of this person who have a height greater than or equal to H right and I agree them to reconstruct the queue so what does this problem mean right okay let's take a look right so what is the front right so for example you're given this like this array here right each element of the array represent a person at people and the first one is the height and the second one is the number of people in front of him right which is like a greater or which is higher which visit which is like higher than him right what does it mean okay what does Franta means right front you know this is front this is end so it means I'm the basically on the left side not on the right side for example here seven means one seven zero means on the left side there is no other people which is taller than him right and the five zero also means that there's no on the final lap side left to the two this five zero there's no more people which is taller than him right how about the four as you can see if four here right let's see take an example for here I mean after the reconstruction here right so 4 means on the left of 4 there like there are like 4 people which is taller than the him right which is true because 4 and for the tightest height is 4 but on the left side see there are like 1 2 3 4 there are 4 people which is taller than him right how about 7 same here right 7 and see seven here there is only one element right which is on the left which is equal taller than him which is 7 0 itself right so yeah I mean the implementation for this code is fairly easy but the thought the idea is not that easy I'll try to explain let's try to I will try to go through this thing the problem one by one you know let's take the one example a very simple example let's say there are only two elements in this array let's say there's only 7 0 and 7 1 right let's break the problem into a the very small problem first right let's say there's only one height in the in this input array so what's how can we rearrange this array right if there's only one height what do we just simply sort by the second element right let's say there's a 7 to here right and then we just simply sort by the second element right and then because that in the in this case the 7 0 will be our first output then the seven one and then the seven two right because they are there in the same height and we just simply stored by the second element of this of these people right okay so that's that how about now let's try to add another person with a different height let's say we have a height six right six one yeah let's say there's a six one here so then what does this six one means right six one means there is one person which is taller than him on the left side right then here the key observation here is that you know when we process the six here the second element here will be the index basically if you know if you watch this closely this one will be the index that we'll be inserting into the current answer here right because it tells us okay we need two more people we're sorry we need one people in this array which is taller than I am and that's why the learning process brought us to a second concept here how can we make sure all the elements in the array will be taller than the my current height right then when we do the soybeans we said we sort by the second element but then we have to sort by this first item in the first basically we're in the sort we need to put the highest right highest person's at the beginning and then we just loop through from that highest person to the lowest person right if we sort the people in this sequence then when we process a lower height right we can sure we can be sure all the other elements we put we already put in the answer array they must be there must be a higher than the current height right then we can make sure our this current this index will be the position our current heart needs to be in because everything is greater than I am so this is satisfied this that the definition of this K here right because put it which means we need case number on my left with basically it right because after my greater than AIIMS high a taller than I am so I just need to insert the current right the current element into this array at this position which is here right okay let's see if those are the informations let's see there's another one right let's see on the height of six we have two elements right let's say we have a another six it has to be six three right think about this right is it possible we have a six one and then we have a six two here no right why because the since we have seven one right and then when we have the sick after we insert in six one there will be like three elements in this array right so the next one has to be six three so basically I'm just explaining right so basically we're assuming right since there to improve the gave us is a correct if the part is the permutation of the output so the next available one of the six has to be six three right so let's assume you know we have two elements I'm after height six here right height equals six and then like I said once we insert this one to the array then the second one right and we process the second one we know this index will also be the index that we will be inserting too because there are like three elements in this array right and then we just need to insert this element at the position three of this element we do it one by one since words keep inserting the admin in into our answer into our output and then once we process all the heights here then we know we have the we have reconstruct the array here so you know when we if we really see this well if we really ask this question in turn in the interval in the interview it's not that obvious I don't think and everyone can come up with this kind of observation really quickly and easily especially if it is actually we need to first start from high the highest height to lowest heart and then second one will be oh this the second element will be our index to insert right so I think if you really if you will really ask this question during interview you know try to communicate with it with your interviewer and yeah don't just spend like half an hour standing there and trying to solve this problem by yourself you know just try to talk to an interviewer and know ask them what you have thought and most likely if the interviewer the most interview there they work to they're kind of they will give you some hint one way or the other right and then you can just use that hint to help you further cat get a photo I mean further down to help you to get close to the real solution here right which is this kind of thing all right sorry about all those kind of nonsense talk let's get down to the coding here right all right okay so like I said let's we first need to sort all this adamant here right like we said we need to first sort by the height and then the index right just do a sort right the key let's use a lambda function here so what do we sort right so first we said we need to sort the adament from top down right but then we also put in the second one we need work we want to sort second one from smallest to the biggest right but on the first one it has to be a highest to lowest so what we do is we just use a small trick here right we first stored the negative number after the first one right and then the second one will be stored in under the positive one right so after this one we're sure we're sorting this the highest one on the beginning and then also for the same height we sort from the index or index from smallest to the biggest ascending order right and then we just do up a loop here right - a loop here first let's define right - a loop here first let's define right - a loop here first let's define an answer output here right so we do what we do the height you which is simply to insert right since we already sorted everything we just need to insert the position so what's the position right the position will be p1 right the p1 and the value will be P right think that's the yeah that's the definition of the insert here basically we specified that the position we want to insert and then what's the value of the after what value we want to insert so the position will always be the basically the index here right on second one and then in the end we simply return the answer see only a few lines of code but the South behind those code are kind of not easy to get at the beginning yeah so sorry yeah for people for P in people yeah some titles here yeah see so cool so again to base to idea 2002 hints here right yeah let's take a look what is Hugh says yeah anyway so first one yeah I don't know maybe I should stop here basically if we need to sort from the highest to lowest so that when we do the insert we know that all the elements in the answer will be either taller or the same height as I am I scored one right so that we can safely use it index right to do the insert and in the end which threatens answer here cool I think that's it for this problem thank you so much for watching the video guys and I hope you enjoy it and okay see you guys soon bye
Queue Reconstruction by Height
queue-reconstruction-by-height
You are given an array of people, `people`, which are the attributes of some people in a queue (not necessarily in order). Each `people[i] = [hi, ki]` represents the `ith` person of height `hi` with **exactly** `ki` other people in front who have a height greater than or equal to `hi`. Reconstruct and return _the queue that is represented by the input array_ `people`. The returned queue should be formatted as an array `queue`, where `queue[j] = [hj, kj]` is the attributes of the `jth` person in the queue (`queue[0]` is the person at the front of the queue). **Example 1:** **Input:** people = \[\[7,0\],\[4,4\],\[7,1\],\[5,0\],\[6,1\],\[5,2\]\] **Output:** \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\] **Explanation:** Person 0 has height 5 with no other people taller or the same height in front. Person 1 has height 7 with no other people taller or the same height in front. Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1. Person 3 has height 6 with one person taller or the same height in front, which is person 1. Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3. Person 5 has height 7 with one person taller or the same height in front, which is person 1. Hence \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\] is the reconstructed queue. **Example 2:** **Input:** people = \[\[6,0\],\[5,0\],\[4,0\],\[3,2\],\[2,2\],\[1,4\]\] **Output:** \[\[4,0\],\[5,0\],\[2,2\],\[3,2\],\[1,4\],\[6,0\]\] **Constraints:** * `1 <= people.length <= 2000` * `0 <= hi <= 106` * `0 <= ki < people.length` * It is guaranteed that the queue can be reconstructed.
What can you say about the position of the shortest person? If the position of the shortest person is i, how many people would be in front of the shortest person? Once you fix the position of the shortest person, what can you say about the position of the second shortest person?
Array,Greedy,Binary Indexed Tree,Segment Tree,Sorting
Medium
315
406
hello everyone welcome to learn workflow in this quick video we will look into the another liquid problem that is the q reconstruction by height so this is a medium level question and we will understand how we can solve this question what exactly the question is asking us to do before going deep into the video subscribe to this channel if you haven't already now let's understand what exactly the question is saying you are given an array of people so that's the people that we have been given here and we can see that it's a 2d array we have okay and which are the attributes of some people in a cube so these are like attributes of people in the queue and not necessarily in the order okay so it says that they are not in the particular order okay and then it explains that for each people of i is actually another array that is h i and k i okay and that represents that eighth person of height h i with exactly k i uh other people in front of the height who is greater than or equal to hf okay so it basically means if someone like uh if something like it says a person of height uh six has uh say one person uh before him so that will be an uh array in the about the one d array out of this should be area okay so if that is so that means there must be one person whose high like one person whose height is greater than or equal to six and who is standing before them so that means basically means say that's an person like this okay uh sorry this uh drawing but there's a person like this who is like uh say sixth grade and there's another person like this who is like uh six feet okay and if that is so that means we can understand that there must be one person whose height is greater than or equal to sixty standing uh in front of them like uh other people in front okay whose height is greater than or equal to six so that means uh that doesn't mean that they are the only two person so it may happen like there are another person who is like shorter than them is standing in between them or maybe other another person shorter over here is also there okay so that may happen but it basically means if this person is trying to look this person can see another person's figure which is greater than equal to his height okay so that's the kind of uh question we have over here let's uh try to understand further what it says like we reconstruct and return the queue that is represented by the input array people okay so we need to reconstruct this uh queue and return that so what basically we need to do the return queue should be formatted as an array uh where qr e uh where q of j is h i k j in the attribute of the jth person of the queue okay so uh basically that means that we need to reconstruct this array okay reconstruct in the sense what i look here uh this there is a uh there is a point over here that is these are not necessarily in order so this is the point we have over here so that is not in order particularly that means if we have uh like an and smaller person can have can be say there is a person called uh four and zero so that means there's no other person greater than equal to of height four before them so that's zero and out of this people's array that we are given over here it may happen that after all these people this uh four zero is standing over here okay and it may happen like that so we need to reconstruct it in the manner that this person which says that he has a height of four and no other person greater than equal to his height is standing before him so we need to take out this person and place it at like uh at the initial position because uh the other person's like this person has a height greater than four we can understand by the diagram right so that's the kind of uh reconstruction we need to do over here like let's take an example and let me uh make you understand it more further so we have given a pupil see here 7 zero seven zero means there's a person of height seven and no other person is greater than or equal to seven is standing before him okay and uh look at this place that is uh he is of height seven and one person is standing before him so if that is the condition look up this particular two lines if we see this then for sure we can understand this somehow the seven zero will stand uh let me erase this off and this person's seven zero is standing here and there is another person seven okay this guy is standing here so that means when the when this seven one person over here okay when this person everyone looks up front he can find one person who says it's greater than equal to seven zero okay like this uh like his current his whole night okay and then we find this four that basically means there are uh four this person has a height of four and there are four person standing before him whose height is greater than or equal to four next we see five zero if five zero is there so this person has a height of five and no other person is standing before it and it also shows that this person has a height of seven uh and no other person is standing before him right so if so no other person standing before him on seven is basically means no other person have a height greater than or equal to seven that's what we are being uh told over here right and then other person in front who has height is greater than or equal to h so five zero kenny place house we can place five zero in this manner that this person is in front okay and this person is like five zero okay fine so this person is standing in front and he cannot see any other person greater than or equal to before him and then seven zero comes in seven zero is a person who is like uh looking in front and finding that no other person is greater than equal to uh his height over in the in front of him okay next and then it comes six one so six one is basically like um again the same thing he has a height of six and he finds that there is one person greater than or equal to his height before him okay so we can uh by convention we can understand the sixth one will be somewhere like after seven zero it can be it should be six one right so six one is something like say we placed it here and this person can see that there's only one person whose height is greater than or equal to his height okay that means seven zero and this is six one fine then we find 5 2 is basically is saying that this person have a height of 5 and there are 2 percent greater than or equal to 5 so 2 percent will be 5 0 uh another hour one person whose height is equal to 5 and then another person is seven zero whose height is greater than five so that means that if there are two percent like this so it cannot be after six one it should be here over here right so that's how the person should look into uh who is standing with before him and then we miss we didn't put one person that is this four so this four will be like four is like his height is four and he is seeing four persons are there whose height is better than equal to four okay so that means this person will be standing somewhere over here so i think this can be understood easily like how this particular is working yeah so uh this can be understood how this we should uh look into this then look at the final output is five first is five zero we came across five zero over here and then we have seven zero we have over here and then we have five two we are coming across over here and then it is six one yes and then we got four yes and then we got seven one and there's our seven one so seven one is looking for only seven zero in the beginning so that's the basic idea behind this question okay so that's how we are trying to understand this question and uh that's what the question is trying to say us exactly okay now uh i hope this can this is understandable what exactly we need to do in this question okay so yes this guy this question is a bit confusing because like throughout the question it didn't clearly say what to do it just mentioned reconstruct or return the queue but the hint was there it is not necessarily in order so you need to reconstruct when it says use queue means always there's a uh like first in first out type stuff is there and where to reconstruct this by height so the question says this clearly and then the hint was here that it is like not necessarily in the particular order okay so that is the hint we have over here okay now uh to do this kind of question what exactly comes in mind is something we need to do sorting right more or less we have a simple task that we need to do sorting now how can we do that the basic idea look we can do like sort this array of papers uh based on our two criteria basically first step would be for us like we need to sort this kind of elements those elements that are the bigger values over here okay that the maximum height whatever we have like we need to first do that we got the tallest group of people and sort them in order like first pick up this seven like i have the highest number people who have over here so first pick them up and then sort them based on like uh best on simple stuff like uh what they are how many people are standing before them so we just need to pick up the seven people and just we need to figure out that seven zero will be in the beginning and seven uh one uh will be at the second place okay so that's the initial sorting we should do and then we should do something like uh we should go ahead with uh this uh four and four not will need to find foreign second tallest group the second tourist group is like six one okay so in the second tallest group we will find that will be six one so that the initial sorting will go ahead on this uh pupils and then the third tallest group that is five zero and five two so that's the five zero and five two uh because why we are exactly doing this uh i'll just show you in a moment and the fourth college group we have over here is like four okay so that's the question we have over here and after like sorting that array we should end up with something like this how we can do that we will simply arrays dots or we cannot but we need to uh put in some uh comparator over here to help us with this uh with this particular kind of sorting we are looking forward to how exactly we are doing something like if uh say if our uh what do we say if our zeroth position i mean this uh seven and seven are like equal anyway we find that these are equal then what we'll go ahead with though we will check based on like if two numbers are there whose uh zeroth position is are equal that is their height are required so we'll go ahead to check the positions or given in the array like positions like how many people are before them so based on that we were sorted and if those are not equal we will choose a descending order okay so we'll simply choose a descending order for this particular purpose and that's the question it's all about so first you bought that and now look how you will do that uh take a list uh list for us like at ls and then just place them in it like place them where wherever the position is this marking okay so it will place it like seven uh at the zeroth position we placed it initially and then if i had seven one so we just placed it at the seven and the first position okay then we find uh like these are two elements we are inserted into our list then we find six and one being given here uh let me just uh make up some space uh for this other elements to join in so i'll tell you how is it going exactly so if we inserted seven at the zeroth position then we will insert seven at the first position okay so that's how our list looks in the beginning our list okay next we come across six one uh then what we will do we will insert in the first position six so we inserted like a six one somewhere like six one so that's the first question and in list you know it's a kind of a dynamic array so uh we can insert into a position and the other elements will shift accordingly okay then you find five zero at the zeroth position insert five okay so that's the idea and then we will insert five at the first position okay so the first position uh five one what is five one five two yeah so five two was there so you know this is the zeroth position this is the first position and there we have a five two i'm sorry i wrote down one over here it should be two so then we inserted five at the second position like best on the array now look we got uh four over here so four is like zero one uh two then three and then there should be four place that is currently pointing to our seven one now we'll insert in the fourth question something like four uh is it what our answer is like is it what we are trying to find out see after we just sorted our array particularly then we find that uh using a list like arrow list we can do this kind of insertions and that's like helps us with pretty much everything okay so this is the basic idea we have over here and that's how we'll solve this question so this question uh may not be like super uh super easy question i mean super easy question what it means is the main understanding is this uh hint that these are not necessarily an odd and how you should sort this array you should sort this best one initially will check if uh the both the elements are equal like both are the heights are equal or greater okay so if their heights are uh equal then you should uh like you should have a consideration based on this uh like your uh how many people are standing before them okay and if the heights are not equal that means uh not a greater than unless then how you should do that you should go ahead and check their uh values in the descending order so the my days like if the heights and earlier seven and six are there then you will go ahead and do it in descending order so main ideas to sort this in descending order and then you can see like we find out the final answer over here that's the idea so we'll just go ahead and write some code and figure out what exactly we need to do over here okay like how exactly our code should look like and uh that's how we'll go over here okay the first thing is yeah so here it is exactly you can see it's like an 11 millisecond solution we have over here and uh to be exact if you look clearly then you find that this arrestor sort here what we are doing we are sorting this people and we are sorting based on this comparator we have over here so if we just look carefully about this comparator it just does what we just check if the zeroth positions are equal okay if they are equal uh then we basically used our ternary operator over here that if they are equal then we should do this if true then this if false then we should do this so what if the two values or the two numbers at the front like this if we find seven and uh seven over here then that basically means what we'll do will uh just sort it ascending order based on their uh k position like this uh zero and one like whatever be the value they have at this uh height and next to height and uh for one its position will just uh to like sort them ascending order and in the next case if their both of their heights are not equal then you should sort this in the descending order and descending order in the sense uh in the descending order based on the height so that's how we did and then we used a linked list for that purpose as i was telling we should place the element at these exact positions so link it to be the best case for us and so used a link list and then we took the each of the single array within our people's array okay uh each of the arrows we took and what we exactly did we did like at the ith position or like a of one whatever with the height uh position being marked at this particular places so we took we placed our uh like this is like uh when he at least got add and this is like position comma add what add this e this particular small arrow we have to add that so this gives us the position at which version we want to add this and at last we just written like list or two array and what do we just uh constructed it as a new list of peoples.length okay it as a new list of peoples.length okay it as a new list of peoples.length okay so that's what we did and we returned our final answer and then you can see like this is working pretty fine and it's working good for us actually so that's a basic understanding of this question i can i hope i can make you understand how we should solve this question and how we should go ahead uh finding a solution to this so uh thank you all for watching this video uh hope to see you soon in my next video as well so before that if you haven't subscribed this channel already make sure you just subscribe to the channel and also like the video and uh comment down if you have any problems or questions related to the particular questions okay thank you all
Queue Reconstruction by Height
queue-reconstruction-by-height
You are given an array of people, `people`, which are the attributes of some people in a queue (not necessarily in order). Each `people[i] = [hi, ki]` represents the `ith` person of height `hi` with **exactly** `ki` other people in front who have a height greater than or equal to `hi`. Reconstruct and return _the queue that is represented by the input array_ `people`. The returned queue should be formatted as an array `queue`, where `queue[j] = [hj, kj]` is the attributes of the `jth` person in the queue (`queue[0]` is the person at the front of the queue). **Example 1:** **Input:** people = \[\[7,0\],\[4,4\],\[7,1\],\[5,0\],\[6,1\],\[5,2\]\] **Output:** \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\] **Explanation:** Person 0 has height 5 with no other people taller or the same height in front. Person 1 has height 7 with no other people taller or the same height in front. Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1. Person 3 has height 6 with one person taller or the same height in front, which is person 1. Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3. Person 5 has height 7 with one person taller or the same height in front, which is person 1. Hence \[\[5,0\],\[7,0\],\[5,2\],\[6,1\],\[4,4\],\[7,1\]\] is the reconstructed queue. **Example 2:** **Input:** people = \[\[6,0\],\[5,0\],\[4,0\],\[3,2\],\[2,2\],\[1,4\]\] **Output:** \[\[4,0\],\[5,0\],\[2,2\],\[3,2\],\[1,4\],\[6,0\]\] **Constraints:** * `1 <= people.length <= 2000` * `0 <= hi <= 106` * `0 <= ki < people.length` * It is guaranteed that the queue can be reconstructed.
What can you say about the position of the shortest person? If the position of the shortest person is i, how many people would be in front of the shortest person? Once you fix the position of the shortest person, what can you say about the position of the second shortest person?
Array,Greedy,Binary Indexed Tree,Segment Tree,Sorting
Medium
315
6
aha Roger land or sea yeah I'm like Halle which are the exact conversion sit out here Janaki this is ashwin on one Gary both scream who is a number title total homme the home this is the dreams of the function sure can be digital ta y pa I too late doc didn't puncture in camp idea now I'm kind of energy from the tour I'm Josh it is between future a b c d e f g h i on the joshua roll number should for his home teacher compatible ink extreme builder dari is a string builder three kids with low number cool so here so two builders in e our son from to the array the whole malaysia you go a little juice if you doona to the food no but have fun without showing the wager you also send out e te go sure I of the fungi to computer legal to the stringbuilder again now who eat from p.r stringbuilder again now who eat from p.r stringbuilder again now who eat from p.r some see sense auntie the whole unit at lv pusher siphoned off sanjay partnership so r 4 is 0 x ji na ho h shazia h I so you should be careful the puncture aho say holy water bodies to the stringbuilder we're going to go to paint roller AET charge on PF h ja AE I 2000 p we home Chetan Chauhan de Santa hello light usage on time on how to the foreign contacts without on his chamber copy and holy Lord Hari that in the screen the Holman gently let me go student builder Tory now teaches us to do the rating huge iguana so it wasn't really too torial you go home the student builder of Jack our home to Hatcher turns to green the t's example I shouldn't be found Katie the index to share moments to dream builder the index so you can be the 14 1 so sure seems to be builded the Liang er Sam from doe found in July now how I may find little mood I data tortola student index lon chaney in Tom commuted intelligence index to sell euro number tomorrow I shall advance to roll mental stood near himeno to Evander team haja for Middleton sure they are the fortunate one should some java jones hola weasel as a ton damper ro TR kaiser so who is the sheer illusion email to the index rose in a year to year pimiento one long widow nurses-home to the number of rows widow nurses-home to the number of rows widow nurses-home to the number of rows grk sure you drizzled all e so don't yet Konami oh maybe 400 show me the table characters and I'm dietetics green dome home so hold on underbar soilders to dream builder who at all each year going to go now hold it n da gua they're hoping solitaire holy bore our methodology of majority on our daily tally was another nativity any attune the Ovation you LeAnn cute idea
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
59
hello and welcome to another leak code solution video this is problem number 59 spiral Matrix 2 for this problem we're given a positive integer n generate an N byn Matrix filled with elements from 1 to n^2 in spiral order for example one to n^2 in spiral order for example one to n^2 in spiral order for example one we're given the problem visually and our input is three so our output would be 1 2 3 894 765 and this is because we will be creating a 3X3 Matrix because our input value is three and when you take this Matrix and break it row by row that's how we get our output of 1 2 3 8 94 765 for example two our input is 1 so this would be a 1x one Matrix so our output would just be one let's go through an example for our example our n will be equal to 4 and for our solution we're going to start off by creating a 4x4 Matrix and setting every value equal to zero and we're also going to want to keep track of four values our top our bottom our left and our right our Top Value will point at the top row of our Matrix our bottom value will point at the bottom row of our Matrix our left value will point at the First Column of our Matrix and our right value will point to the last column in our Matrix so I've also laid this problem out visually so our n equals 4 so we have a 4x4 Matrix and our Top Value is pointing at the top row bottom at the bottom row left leftmost column right rightmost column and these will be used to keep track of what our next row or column will be entering values into so the first thing we're going to do is Traverse our top row from our left point to our right point and once we've done this we'll then increment our Top Value so it's pointing at the next row so once we've traversed our top row we have 1 2 3 4 and as we Traverse through our Matrix we'll keep track of our values by having a counter to determine what our next value will be in the next position so we've traversed our top row and we have 1 2 3 4 and now we want to increment our Top Value so it's pointing at the next row so now our top value is equal to one once we do our first traversal of the top row we then want to move on to traversing from our Top Value to our bottom value along the rightmost column and once we've done that we then want to decrement our right value by one so we've gone down our rightmost column and we have 5 six 7 down so we'll want to decrement our right value now the third thing we want to do is Traverse our bottom row from our right column to our left column and once we've done this we then want to decrement our bottom value so now our bottom row is 10 987 and we decrement our bottom value and our fourth and final step will be to Traverse the first column from our bottom value to our Top Value and once we've done this we want to increment our left value by one so now we've completed our four-step process of going around our four-step process of going around our four-step process of going around our perimeter of our Matrix so we'll just want to continue going through those four steps of going across the top row then the rightmost column down then the bottom row from right to left and then from our bottom to top values on our leftmost column and we'll do this until the value of our counter that we're putting into our Matrix is equal to our n² so in this case with n = 4 to our n² so in this case with n = 4 to our n² so in this case with n = 4 we'll continue to do this until our value that we're putting into our Matrix is equal to 16 so we'll do our first step again which is going across the row our top values pointing to from our left column to our right column and now we'll increment our Top Value and now we'll do our second step of going down our rightmost column from our Top Value to our bottom value and since our top and bottom are both pointing at our row two we'll just be entering into this one cell and now we'll decrement our right value and next we'll go across our bottom row from our right value to our left value and our right and left are the same now so it's just one cell again and we can stop there because the value we just entered is equal to n^ S so we just entered is equal to n^ S so we just entered is equal to n^ S so we would just output this Matrix as 1 2 3 4 12 13 14 5 11 16 15 6 and 10 9 87 let's jump into the code the first thing we're going to want to do is Define our Matrix and set each value in our Matrix equal to zero and we'll want our Matrix to be n byn next we're going to want to Define our number counter and we'll set it equal to one to start now we'll Define our top bottom left and right values our top and our left values will both be starting off as zero and our bottom and right values will both be starting off as n minus one now we'll Loop while our number counter is less than or equal to n^2 counter is less than or equal to n^2 counter is less than or equal to n^2 and within our loop we're going to do our four steps our first step being traversing from left to right along the top row and after we're traversing that top row we just need to make sure we're incrementing our Top Value by one so that we're pointing at the next row now we'll do our second step which is traversing from our top row to our bottom row on the rightmost column and once we Traverse along the right column we need to decrement our right value by one so that we're pointing at the next column now we'll do our third check which we'll be traversing from our right column to our left column along the bottom row and once we've done this check we'll have to decrement our bottom value as well so that we're pointing at the next row up and now we'll do our final Traverse which is traversing from our bottom row to our top row along the leftmost column and when we finish this Traverse we just need to increment our left by one so that we're pointing at the next column in our Matrix and that's it for our four traverses so at this point we can just return our Matrix I had one small syntax error accidentally spelled Matrix wrong on our first Traverse so just moving the r should fix it uh let's run this again all test case pass so let's submit our solution was accepted so that's it for this problem if you like this video and want to see more content like it make sure to check out my channel thanks for watching
Spiral Matrix II
spiral-matrix-ii
Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order. **Example 1:** **Input:** n = 3 **Output:** \[\[1,2,3\],\[8,9,4\],\[7,6,5\]\] **Example 2:** **Input:** n = 1 **Output:** \[\[1\]\] **Constraints:** * `1 <= n <= 20`
null
Array,Matrix,Simulation
Medium
54,921
745
okay 7:45 prefix and suffix search given okay 7:45 prefix and suffix search given okay 7:45 prefix and suffix search given many words word sub I has great I designer class word filter that supports one function word filter that it will return the world with a Kevin prefix and suffix with maximum weight if no word exists we turn negative once ah and I turn too much I think Erica so you have some examples what it's okay and this is I guess sometimes I don't know because this is the index 0 hmm and a weird way of phrasing this I see you just one don't but this weight is just basically what you're asking is just you want the last word with the prefix and a suffix that match okay let's look at constraints words have words has lengths of up to 15 K now for each test case up to what's that thing so you could do 15 K queries so they probably wanted to click to some pre-processing click to some pre-processing click to some pre-processing which supply has its own up to 10 characters that's not that prefix suffix have names also have to tag out this we're sub I and people select or against us a bone case that is only okay thing about this I mean so where you are I guess I should I take you late my random thoughts up in general whenever I see can't these kind of strength problems I think of prefect 3 or suffix tree well I guess I think of both and then kind of think about a little bit and yeah yeah so a prefix-free also is known as a yeah so a prefix-free also is known as a yeah so a prefix-free also is known as a try I think that should be so flesh and I'm trying to think why that would not be a case and the bulk of the world work will be done in the processing I'm trying also clean you think about the language I would like they make me fly fun should be okay this is pretty basic problem or basic in terms of I don't like that no tricky no one's it just tells you stuff okay and I think what I want to do now this just kind of built a try off all the prefixes and what would that cost well each word could kind of have up to 10 characters or your tribe will only be 10 level steep yeah and you have 15,000 10 level steep yeah and you have 15,000 10 level steep yeah and you have 15,000 words so you know you're gonna have only about was it 150 thousand nodes times two you had one for the suffix and then you can't just walk to try to kind of and then we turned a later step yeah mr. Fisher yeah that should be okay and each of them just contains the maximum weight at that given level and you just go for all of all the words yeah I'm thinking let me know vide inexplainable my most are implementing and hopefully down show what I mean but Gregg and I would say that was an interview out kind maybe draw out some of these diagrams but this is actually like literally there is a thing called quick-fix tree so like I don't called quick-fix tree so like I don't called quick-fix tree so like I don't know if this and that new ones that I have to explain other than that you know you're just kind of okay right just like tired prior to define the new data structure I know how to do this in we're gonna find fun but I don't think I've done something similar in the code pipeline so our so hopefully we'll see we don't even care that we just have a dictionary this point in this might be actually be the first time I implement a try from scratch in Python so what's out I goes and see how much I remember about the nuances of tries better I said this compound for us while swimming yeah what too soon so we tunable but also it seems like this is niko is slightly faster which I'm happy about okay miss barkow let's stop that keep the weight this should be a quick story oh thank you but Alex desk okay I guess that's all the preprocessor thing that I think about a car simply so let's just play around with how do I wanna version Isis just this tag Wow and so this is only for the prefix we have to create this the exact same one for self fix so maybe we maybe well to process it yes actually maybe we have to store that a bit more maybe in this case we have to store all the weight since I've just pressed weight and then what do a set in a section yeah okay yeah about do this after I get the prefix so that I could kind of use convince myself that this works first this morning right mmm-hmm just sort of like 30 in terms of mmm-hmm just sort of like 30 in terms of mmm-hmm just sort of like 30 in terms of um okay well maybe I should just do it okay we add a bit more test cases test the second one shakshuka me what negative one but I just go into this baby did I get the right answers that I don't even do anything about a suffix oh that's wrong again sorry friends LICO is being slow today you're just tuned in so spending a bit of time waiting for testing to go through okay I mean this is definitely winter dance but let me confirm you buy it I know what I say and then well let's try one where nine sentiment one okay so the output is what I expect it to be I mean it's incorrect but it's what I expected to me because we didn't worry about subjects that's good and it means we understand my page having all the white track as I said just calling the way that's not good enough because now you have to you know kind of take the best of the suffix and prefix so now we have to this should be a set yeah um I think that I think I'm trying to think about it's also well that was said and how much less efficient it is it well because this should be well it makes the space storage the space complexity about ten times bigger because each count so in stealth so we have a hundred fifty thousand no it's planes up you took one of them connect only one and now each of them can contain well a big number of ends but because each word can only have ten characters the total number of characters was like so it only appeared 150 thousand times should be okay just we have to think about in terms of yes you set so now we should give us the wire and circuit well we only have one word so actually there still be the wrong answer just not uh because it doesn't need to be turned because if we turn to set instead of whatever now I added more voice I could just see if gimme yep okay that is actually what I expected to okay for me what we'd like to do is a so given the opportunity just test myself iteratively I given though the answers we wrong just so that you know you don't want to get so far deviating from the correct thing that you have to like figure out way to debug wait like now I have almost like a weird version of TDD where I you know like I know that what I have is currently what I expect it to be and then we could make the next steps and what we have now is that we only have to suffix but not only to prefix 1 antiseptics how do any their prior two ways to think about how to cut the suffix version you could probably I mean so yeah so the one way it's kind of just like added on top of this thing and another way is to create a separate set of tree nodes which I think that's why I do just to kind of make it less confusing now do we wait time just after and let's see stop chatter that works okay still the same answer - like sisters here did we put minus 1 I wish that works I love suffix cuz I actually just want make sure that is actually a white order I just print this out so justice hmm it's that way I should point out so many tries this case it's cover no inter cases I think oh that's fine that happens when you copy and paste what so what okay you worse if they're not extremely nice ring but I just here as a source of parts of our confusions that off by oneness Joker so this does return stuff actually should return the right answer but my figure now we have to get the biggest one with us okay okay we got worried about I said I don't think actually I try I test this and now for suffix okay that's good to have a bat like that seem along because I would know I don't add anything on okay they're actually glad that I've tested this I've actually been meaning to because we don't run this function we don't set it at all so now it should be wait for me there okay so that's why I need to test before well I would like to tell something that doesn't return zero so quite giving the issue because I look uh I just made anything how it goes now tiny'mon expedient okay I guess I should time the receipt okay I think I was just mostly lady okay that's not so bad I think what ends up happening is that huh yeah so this set in this section is too expensive to do a per query so we just have to kind of which record well we have to do it as part of the pre-processing dance how'd I want to do this with all the pre-processing pre-processing pre-processing just thinking about how to do this in a quick way without kind of rewriting a lot of code and I don't mind the situation or to just rush the notes together and we could also be hey let's precache this yeah I mean I think what I'm gonna do is just a variation of the memorization maybe now I feel okay I'm just gonna pre-processing typing again and I just do it recursively yeah so the weight of a word is know me it's very used to miss actually because I think yeah but yeah the weight of the word is forwards in the I entry update away that's the weight I so it's just a sentence but it's really using this for whatever reason also welcome back now - whatever reason also welcome back now - whatever reason also welcome back now - but yeah but that's how I kind of you kind of look at wait I have it the pre-processing that's why this is kind pre-processing that's why this is kind pre-processing that's why this is kind of just the index of the word away and that's why we're treating there's the way in January it is in Python maybe a little harder to read then maybe other languages in this particular instance the enumerate returns the index and actual item in the thing and in this case it's just all false happens to be their way yeah just walk the prefix okay and now we want to do this week something for these two prefix so you only have to do it for one difference because if it doesn't maybe not mmm that's got to do this in a queen away wait doesn't know what am i - I don't wait doesn't know what am i - I don't wait doesn't know what am i - I don't think that why I'm doing this wait so I'm like behind this like this okay yeah what I'm doing what didn't make sense now that I think about it because these things are now in the same room hmm why is this time very shy can it and see why this is time to really fun of entries but then the second is pretty big hmm okay I'm ticket click one minute break to use the restroom I've been drinking too much iced tea be right back and meanwhile still kind of I'm back ok so I think what I have to do now is figure out a way to handle I think this is just to cost a per intersection because the way that they the worst case is essentially this set intersection is the entire you know the entire world list which could be very long I couldn't turn off what actually is just a second and then doing that this set in this section for curry which is possibly of n it's too expensive so we had to kind of reduce this a bit which we have to think about okay so this oh yes it's just I guess this is what I expected so now that pre calculate this so what I'm thinking right now is trying to think of a way that we don't need an entire list of grades way because why cuz maybe it's not strict I don't know well health what goes but if the prefix set is 15,000 entries and if the prefix set is 15,000 entries and if the prefix set is 15,000 entries and then they just ask the same thing many times they're it's not great I'm wondering also if there's one thing I might consider is just memorizing some part of this but I don't know that's in the spirit of things in the sense that's kind of like catering your code to specific inputs versus like a general solution which is why I hesitate to do something like that specifically but might and that's I could prove that it is I just convinced myself that it is true and it more general sense because for example if we're 15,000 words you do for example if we're 15,000 words you do for example if we're 15,000 words you do something less room some balanced ice creams I think I would say one of my original assumption is that yeah I think there's something I can do Ivan one of my religion assumption which I don't know why in this swimming data is that what cannot be duplicated and if that's the case each no I don't know if that helps enough because some idea was that because we moved to placate words because it just ticked but like you could just take the last couple of entries and that should kind of good enough proxy but then in that case you can actually just have something similar disk but except for you know they're 15 giving the 10 like you could have a prefix that or have just a better anyway and I'll still return pretty much roughly everything so I don't think that solves it it's still a them can still mess them all the possible rates and then do a second mr. it's definitely faster than naive just more I guess there's a degenerate case in a sense that it's just is better than I you covered and you could construct an equally bad case anyway because the naive album do this in of n times per to F query but instead we got it down to all of I mean in theories the number of characters into in the prefix and suffix for the sender's section is making this off and maybe we don't need to send in this section there maybe we could count backwards no because yeah we okay I think what I want to do instead of having a set this actually have a sheep and then we walk we do a because here we're looking for the max in the set intersection which you can do in a faster time but maybe still worst case of and because it didn't know if the center section is nothing then it still goes from both entire list whom I still have to think a little bit better than that yeah but you could still talk very gentleman yeah did every some optimizations I can make where I'm just trying to think if like that's sufficient for I think yeah maybe also don't need to say I think one thing we can notice that may be said is just a little too slow because we took them in order this should accept this point now you have two arrays and you want stuff in the potty well yeah you don't even need a heap Slurpee Chris oh he thing because it's already sorted because we add them in order okay so that now we can do something like this is the case that's definitely some kind of optimization and always sufficient not that's much faster is sufficient I guess I mean it mixed her set in the section not whole and good I got think it's your wrong answer which is nice group okay it's more something truth like to add too many wait order something we go away store Connecticut oops that is the way like a penis how do I capture start I get the same thing okay ladies it's consistent this baby dance listen baby no but then we turn to zero which is I guess true what is it that's not a copper self extension oh wait come back into the ball okay how cool it is it's warm time that cream store correct a qu but maybe that I have a typo some what is this okay so the away is right there not a smart return the point instead of the actual engine okay yeah but it's silly mistake and also dad they've worked for next time I get six times like that great but I had another test case oh no I guess the other test cases from the time the only one in that the one that oh yeah okay so that looks good listen yesterday hopefully okay cool um-hmm what can I hopefully okay cool um-hmm what can I hopefully okay cool um-hmm what can I say about this uh yeah I met I think I know boy when you've been here with me wow it's doing this farm I think I enjoyed this farm it's coming somewhere is that maybe I yeah I mean it tells you the number of curries it can do so maybe I should have done the math on that I think I was just I was a little fixated in the pre-processing part in which we kind of pre-processing part in which we kind of pre-processing part in which we kind of scoped out the space complexity but we did not well I think some of it was dead like I excuse me I personally I changed the code to stop holding the weight in no I changed it to hold a set and making that change was a non-trivial and making that change was a non-trivial and making that change was a non-trivial change that I did not analyze their complexity for and I just didn't even think about it that much which I probably should be more careful about I think what I said is using a set is sufficient in the sense that is correct but it is not sufficient in the sense that it's once fast enough obvious as we kind of talked about we had to do a set intersection which is all wolf and just to just get the max intersection and so you only need to and having this two pointed to think a approach allow us to kind of get it to the right way because most of the time it's not insider yeah most of the time it will match regularly so even though still oh of N and this complexity is still the same it returns way earlier do I it's kind of sketch in a sense that I feel like I can construct a time limit example for how I did it so I don't know if there's a better expectation than kind of the way I did it because the worst case and therefore how what I've done was that you know this gets returned negative one and YouTube just goes through a half throw away so then you have like so it still goes for the entire thing it's like yeah it's like if prefix matches everything and suffix matches nothing or like one item or something like that then it's gonna go for the entire away so it'd still be slow and it's possibly is still time out before this input set of input cases it seems okay y'all have any questions but yes I didn't we I think there's still a little bit uh like I'm not I don't think I have a lot of query clarity or confidence in to distinguish and generic solution to this problem I'll have to do some research later as an interviewer how about every thing about this I mean I think initially I did underestimate this to just be essentially brain implementation of the prefix tree or the try and a parent is set in this section in there kind of with that really so I guess I kind of dig it I think I don't know if I would expect this kind of prompt about it in the real but if it is then you know I need to be prepared for it I think this is in terms its difficulty probably on the right I mean I would have to play around calibration but I think that's probably on a like reasonable side of the difficulty okay cool
Prefix and Suffix Search
find-smallest-letter-greater-than-target
Design a special dictionary that searches the words in it by a prefix and a suffix. Implement the `WordFilter` class: * `WordFilter(string[] words)` Initializes the object with the `words` in the dictionary. * `f(string pref, string suff)` Returns _the index of the word in the dictionary,_ which has the prefix `pref` and the suffix `suff`. If there is more than one valid index, return **the largest** of them. If there is no such word in the dictionary, return `-1`. **Example 1:** **Input** \[ "WordFilter ", "f "\] \[\[\[ "apple "\]\], \[ "a ", "e "\]\] **Output** \[null, 0\] **Explanation** WordFilter wordFilter = new WordFilter(\[ "apple "\]); wordFilter.f( "a ", "e "); // return 0, because the word at index 0 has prefix = "a " and suffix = "e ". **Constraints:** * `1 <= words.length <= 104` * `1 <= words[i].length <= 7` * `1 <= pref.length, suff.length <= 7` * `words[i]`, `pref` and `suff` consist of lowercase English letters only. * At most `104` calls will be made to the function `f`.
Try to find whether each of 26 next letters are in the given string array.
Array,Binary Search
Easy
2269
147
hello everyone welcome to kodus camp we are at 15th day of december lead code challenge and the problem we are going to cover in this video is insertion sort list so we are given head ahead of a linked list and we have to return a sorted linked list it is as simple as that but they have given the procedure to sort the linked list that is we have to use the insertion sort technique or algorithm to sort the linked list and return the results so there are other simpler ways to sort a linked list but here they are specific to the algorithm so we have to implement it and also they have given what is insertion sort in three points which is nothing but if you are picking an element you have to place it exactly where it belongs so in this list if you see uh it two belongs next to two so you directly have to shift the two in its correct position and then pick the next element and wherever it belongs you have to shift it exactly to that position so every time if you pick an element you have to put it in the exact position it belongs to and you won't change its position again so that is simply a insertion sort so let's see how are we going to approach this so usually for any linked list problem we have used pointers either it can be two pointers or three pointers to get the problem done and we are again going to use the pointers technique but i won't restrict this algorithm with three pointers it may go for many pointers so come along with me we'll learn step by step to start the algorithm let me introduce two pointers head initially so i am going to insert a dummy node before the head of the linked list so this is the head i am going to introduce a dummy node so that finally this will help us to return our results head so this is going to be a dummy node and we are going to attach it's next to our head so to start with i'm going to introduce a pointer called sorted tail so this sorter tail is basically going to point at the end of sorted linked list so these are all the elements that are unsorted and we consider the head as the sorted one and from unsorted list we are going to pick every element and place it before or between the dummy and the sorted tail because sort of tail indicates the end of the sorted list so we pick each and every element and put it somewhere between the dummy and sorted tail and this goes on until the sorted tail meets the null value so now the algorithm divides into two parts because based on the sorted tail we are going to put the values in its correct position so there are two conditions the values in the unsorted list can be less than the sorted tail value or greater than the sorted tail value so first let us see greater than value case so if the values are greater than the sorted tail so in that case the sorted tail extend itself extend to the next position to point that is the sorted tail that is the tail of the sorted list because the value is already higher so it doesn't really have to uh put the element in between instead it can change its pointer to the next one to point that it has extended its sorted list or the sorted tail has moved to the higher one the same goes with the next node also so this also higher than the sorted tail so now we don't have to really put this somewhere between dummy and sort of tail instead we can move the pointer so this goes this way if the value is less than the tail note then there is a different case so we'll see that later let's move the sorted tail till the values are higher than the sorted tail so let's start our case by having us sorted tail in short st in place of head and we compare the value at sorted tail with the value at sorted tail dot next that is x t dot next so when you compare the value is actually higher so you don't have to remove this node and put it somewhere between dummy and head instead you can just pass on your sorter tail to the next node so that the list extends so now the sorted tail moves here so now again we are going to compare the next sorry tail dot next with the current value so here the value is 3 and the value is 5 which is already higher so we are going to move it again to position 5 and from here we are again going to check the value which is 7 which is again higher than what is there in the current sorted tail so then the sorry tail extends to extend the sorted list so now the position of certain tail is going to be at the point at the node seven so now comes our second case which is the values in the unsorted list are actually less than the value at the sorter tail so far from head to sorted tail our list is already sorted so we did not perform any operation so the next value when you compare seven and four the value is actually lesser than what is there in the sorted chain so in that case you have to take away this node completely and search for its position and place it in its correct position because we cannot simply place it somewhere in between but we have to put it in its correct position so in that case we first have to make a connection from the sorted tail and the next node because we'd be removing the connection between seven to four and four to six so that we can take this node and connect it somewhere else so in that case we have to first establish a connection from sorted tail dot next is equal to sorry tail dot next so that now 7 has been connected to 6 and we are left with the node 4. so as i said before we are dealing with a different set of pointers or more pointers than usual for this algorithm so before making a connection between 7 to 6 we are going to keep a pointer here and name it a stem because uh we want to keep track of this node so because once you make the connection from 7 to 6 the connection between seven to four will be terminated and the connection between four to six will be disconnected so in that case we need to keep track of this node so we are assigning the pointer temp so this is something you have to deal with programmatically so let me not confuse you right now with the pointers so now our task is to place the this node in its exact position so here comes the important part of the program so we have to search for the position which suits 4. so to do that we are going to introduce another pointer because we simply have to iterate and find its position so that is called previous or pre or whatever you want to say however you want to name it so this pointer will i trade between head and the sorted tail to find the position of four so this compares the value at pre and temp every time and figure out the position of four so now it compares one and four which is actually less than 4 so the previous pointer moves here this compares again 3 and 4 3 is also less than 4 so 4 needs to be placed somewhere after 3 so this now again checks pre dot next is less than or greater than 4 so pre dot next is actually greater than 4 so which means 4 has to come somewhere between previous and previous dot next so position of 4 is in between 3 and 5 so what are we going to do we are going to connect previous dot next to temp and temp dot next to previous dot next hope i'm making sense we are just taking this node away and make a connection from three to four and four to five instead of having a connection node between 3 and 5 we are removing this and connecting the node in between and that's it now the node actually becomes 1 3 4 5 7 and we already made a connection from 7 to 6 so 6 and null so in this case our sorted tail is already at position 7 so we have placed the node for this task is actually done so our task is now to as usual iterate assorted tail to the next node and check whether we have to move i trade the node next or place the node between it so now we came back to the previous step that we have to compare the value at the sorted tail and the value at sort of tail dot next now the value is actually less than what is there in the sorted tail so now is it is our job to make a connection from 7 to the next value to 6. so before that we have to set have to we have to set a temporary pointer at 6 because we need to place this node somewhere between head and sorter tail and make a connection between 7 to null so as we have reached null the sorted tail has reached null the algorithm is not going to continue anymore because we have sorted the list already so in this case we have to place 6 in the correct position that is the only job we have so again let's introduce previous from the head and previous is going to check and compare and finds a position and previous moves to 3 is less than 6 and 4 is less than 6 and 5 is less than 6 now finally previous dot next is 7 so 7 is greater than 6. so we found the position so we have to make a connection between previous dot next to temp and temp dot next to previous dot next so also here store the previous dot next we do use another pointer temporary temporarily to store it and then reuse it for the connection so i don't want to bombard you with all the pointers right away you will understand it once you see the program there so yes this is it your algorithm has sorted already with in single execution or the single run of the linked list so hope i made some sense explaining this so let's go to the code now so here's the code for this problem i didn't type it because uh i thought it might confuse you so let's start this is a base condition to check if the head itself is null then we are simply returning the head and then as i said we are going to have a dummy node and that is gonna point at the before the head so that we can easily identify the head to return it that is what i did towards the end we simply returning the dummy dot next so which is our head of the linked list so yes that is all done in between we have our code so as i said uh i am declaring the sorted tail to point at the head of a linked list and this is gonna simply point at the tail or end of sorted list so every time the sorted list grows either by placing a node in between or placing uh moving the sorted tail pointer towards next so as i said here we have covered two cases so to start with the while loop as i said we are going to iterate the while loop till it reaches the null so every time we are going to have the sorted tail as the pointer and check its next value and if it is not equal to null we are going to proceed our iteration so as i have said there are two cases the first case is what if the sorted tail value is less than the value in the sorted tail dot next dot value so in that case we are simply going to move the pointer towards the next node because we don't have to really do any sorting as the value has already been sorted so we are simply iterating it till we face a value which is less than the sorted tail so yes this is a simpler case and here comes the heart of the program and here what we have what we are doing is as i said if we find a value which is less than the value at the sorted tail then we have to place it somewhere in between to do that we are first assigning a temp pointer to the sorted tail dot next because that is the note we are going to place to maintain it to not lose track of it we are assigning a temporary pointer after that we are establishing the connection from shortytale.tail2.tail.next.next so hope you understand this point and then we are assigning a pre pointer this pointer will iterate from head to sort a tail to find temps position yes so we are going to every time compare pre dot next dot value that is why we are assigning dummy as the head because we have to include the head value also so we are assigning the pre to dummy and we are checking pre dot next dot pal is less than 10 dot val if it is less than 10 dot well then the temp node will somewhere will be placed after that so we are going to iterate and move the pointer pre till we find the position of temp so once we find the position of temp this while loop terminates and then temp dot next is equal to pre dot next and three dot next is equal to 10 so they just gave the connection from temp dot next to play dot next first and then the previous connection so that we don't need an extra pointer so yes once all the saturations are done the node will be sort the list will be sorted already so we are going to return dummy.next as our output so hope i made dummy.next as our output so hope i made dummy.next as our output so hope i made it clear so let's give it a try yes so let's submit yes the solution has been accepted and it runs in five milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in my comments thank you
Insertion Sort List
insertion-sort-list
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. 3. It repeats until no input elements remain. The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Constraints:** * The number of nodes in the list is in the range `[1, 5000]`. * `-5000 <= Node.val <= 5000`
null
Linked List,Sorting
Medium
148,850
80
Rice welcome and welcome back to my channel so in today's video we will solve the fourth problem of top interview 150 remove duplicates from sorted it added to you so this problem is similar to the previous two problems i.e. remove previous two problems i.e. remove previous two problems i.e. remove elements remove duplicates from sorted. Just slightly you have been changed in the problem statement, so let us see what has been given to us in the problem statement, here we have been given an array with the name Namas which is in increasing order and what we have to do is something from this array. If you want to remove duplicate elements, then you have to keep in mind that if the copse frequency of any element is ≥ copse frequency of any element is ≥ copse frequency of any element is ≥ then in that condition what you have to do is to keep two elements, the rest is to remove whatever is duplicate, okay like this. How many total elements will you get? What do you have to do? You have to return the count of elements. One count each should be in the first element. So, what do we do? Let's understand this through an example, what is the problem? So look here in the problem we have given 13 times, this is you have given times, this is one time, now this is three times but we have to take only till you times, so we will take two, okay we will remove one then We will keep both of these and if we keep this then the elements of the first i.e. here you have five, elements of the first i.e. here you have five, elements of the first i.e. here you have five, you will return this five and in Ara replace it with dog with this element, after removing the wickets, now in the second example, you see here zero two times. It is 14 times, you are one time, you are three, you are times, you are zero, you are one time, you are four times, you are two, you have to remove two, you have to keep this, and you have to keep this three, and you are also one time. Now while solving this problem, we have to keep in mind that we do not have to add any extra space, that is, your space complexity should be one, so now let us see how we will solve it. See, if one of your two elements, your zero becomes zero. There are two elements which are similar, there will be no difference, but how is this third element, you have to take care of it means how to see, it is in increasing order, none of the elements on the right side will be smaller, it can either be similar, it can be equal. Either it can be greater. If any value here is greater, if you are three or one and four is five, then we will not have to replace there. If similar is happening then we have to keep in mind that here Let us replace it with such elements that what should be greater is okay, what is greater than its value, we will check its value, if it is greater then it is correct, go ahead comfortably, let's move ahead, okay what do we do now? Now let's take another example and through this we understand how we will solve this problem, you three, now we take one jai, zero and i, here we take zero, okay, now look at the first two elements, you need to see. What is the first element, how is it duplicate, is it similar, means is it similar or is it different, only then it will work, it is similar, still let's go because we will not have to look at the first two elements, so let's look at it, let's make I bigger further, let's also make I bigger further. Now look here, it cannot be smaller, this has been said because it is in the amazing order, so if it is greater then it is correct, either it will be similar or it will be gutter only, if it was similar then there would be a problem, but what is this, if it is greater. We will proceed in this condition, okay, we will make S three, we will also make I three. In this condition also, the value on J-2 i.e. the also, the value on J-2 i.e. the also, the value on J-2 i.e. the value on One Index is zero, this is one, will it be necessary to replace it here? Because i3 pe value and k0 pe value zero one pe value what is there in it this is one and this is zero which is greater then it is correct because in this condition we wanted the same and did not want similar because if mine was similar then three consecutive elements. If it becomes right, then we will see, we will also take it forward, take it to four and take I also, four minus two, value i.e. take it to four and take I also, four minus two, value i.e. four minus two, i.e. four minus two, i.e. four minus two, i.e. 2, two, value is one and its value is also one, now it has become similar. It is a problem, then you can replace it. You can replace it with this one which is greater than this because you have seen it here, now you will go here, if you go here, then you will get a similar one. On the right side, you will either get a greater one or you will get a similar one to replace it. Is there any benefit from it? If not then we will have to replace. If there are any greater elements then in this condition we will leave K as it is. Let us leave G brother as it is. Now we will increase it. I is fine. I have taken I to five. Similar again. Now we got what is different, we got different, now what will we do, we will replace this here with this, we will take it to five, now we will see what is the value of this 5. What is the value of this five, what is its value, it is greater than this, the value of i6, so here also what we will do is replace it, okay, that means whatever was there, you have replaced it here, okay, if it is greater, then in this condition. Also, what will we do here, we will replace it with three, we do not want to keep it smaller, look, this is your here, it is okay and this is one, it should be in increasing order, it should not be in decreasing order, so the value here is goter. What we will do is we will replace it and we will also increase K further and take it from six. Okay, what we have to do in this also is we will have to replace it, we will replace it, so here zero, one, two, three, so all these conditions. To follow, we have to keep the condition in such a way that we follow all the things. Okay, so what will we do in this condition. Look, I have shown you the code, it is simple, you just need to understand that ours is in increasing order. What is important? Okay, if the mines are yours then keep replacing them with Namsai in the condition that you are handling all this. Okay, so what have we done here &lt; what have we done here &lt; what have we done here &lt; 2. Look, the first two elements will be there for you. You will not need to check if the duplicate is similar. We do not have any ad for the evening to see us, but after that from the third element, we will start watching, so till the time it seems, you will be on K Plus. Will you keep replacing kya with nas ai? Okay, after that now if the value of your namsahi is greater than k - 2 then what should you do with the value of naam jab, is greater than k - 2 then what should you do with the value of naam jab, is greater than k - 2 then what should you do with the value of naam jab, replace it with jas ai and this is what you will do here finally by turning. Dog here, if you replace it, then you will move K forward, or increment K here, after replacing, it will be seven, so seven, you return it here, Dog, so in this condition, if we did not add any extra space to it, then it will be one and our time. What will be the capacity? Okay, so I hope you have understood. If you liked the video, then please like, share and subscribe.
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **same**. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements. Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`. Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. **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,1,2,2,3\] **Output:** 5, nums = \[1,1,2,2,3,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 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,1,2,3,3\] **Output:** 7, nums = \[0,0,1,1,2,3,3,\_,\_\] **Explanation:** Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order.
null
Array,Two Pointers
Medium
26
231
Hello Everyone Also Observed Every Time Without Meaning Suggestion subscribe Video plz subscribe Channel Please subscribe our The Power of Two List Ko 231 So Let's Talk Warden Ne Basically Prostate Consideration 65th Id Number Two subscribe to the Page if you liked The Video then subscribe to The Amazing Subscribe 98 Intermediate Resist Servi It's Not Power and 251 Final Thursday Subscribe To Jo Vo Time Do LG President 1658 And Disinterested Understanding What Is The President 10 subscribe this Video Please subscribe and subscribe the Channel Please subscribe and subscribe the Video then subscribe to the but if this port number is given to was twelfth verse of it is 000 liquid what will you find the number of but subscribe to subscribe for Live Video 12345 subscribe to again will do the same thing will Strike 5 minutes one count number of width number 21 subscribe to the Page if you liked The Video then subscribe to subscribe our play list take another number adventure fest in one from 106 - 1st 106 - 1st 106 - 1st id m id 1051 subscribe Video subscribe and subscribe this Video Subscribe Number Form - - - 100 Number Laughing Tourist On A Silicone Fit Station Superintendent Play List Number Of Barfi Listen 0 Video Ko 1000 2009 Hai Idhar Girl Gets Fund From Diya Decoration The Video then subscribe to the Page Play List According to Buddheshwar Employment Bill Video then subscribe to the Page if you liked The Video then subscribe to the That accepted yes Vasundhara Pranon and they are doing the same time meeting subscribe The Channel Please subscribe and subscribe the Channel subscribe for Live Video subscribe this Video not true lines hai to left side high hai akshar third open loop control the message of Video subscribe and subscribe the
Power of Two
power-of-two
Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_. An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`. **Example 1:** **Input:** n = 1 **Output:** true **Explanation:** 20 = 1 **Example 2:** **Input:** n = 16 **Output:** true **Explanation:** 24 = 16 **Example 3:** **Input:** n = 3 **Output:** false **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
191,326,342
350
Hello guys welcome to banana seeds were being made then suggestion is definitely problem is isko and intersection of two boys so let's get started problem suppose given to a research including verses chapter-2 isko m with me two tight speakers logic code Will be simply food items in set and set as unique values ​​rule to values ​​for example what we do it values ​​rule to values ​​for example what we do it values ​​rule to values ​​for example what we do it is the meaning of the word from to quote is that unique elements battery batting doesn't unique and U Want To Talk You Want To Return Them Along With Accountable For Example In To 9 News Sid Solving Problems Will Do Something For The Untold Story The Element With Water Element Is Erring 1212 That Is Cute Students Appearing To Times Superstar Storing element second and gentle account element along with account with water stored in up and will see how ef loot status clearly not working rates will need to accounts C3 staring one time next china the ladies verses in the inco form a text past four forces all Suffering One Time Subha Have Studied S All Elements In 15 Number To Use To All The Problem To The Incredible Stupid Elements Name Of Bar Increasing Account Big Economy To Decrease Updates Situ Rights Way Do I Reduce Account 1.5 Reduce Account 1.5 Reduce Account 1.5 This Account This One Little Positive It Means I Bed First Mantu Appeared In Everywhere Also Request Artist Positive Tyanthur Samay Answer Consists Of To Go Through Them Flash Lights On Phone Go To The Next Element Mix Element In These Into Fragments Account Me Weakness Okay Sunna Still Accounted for Preventing Industrial Accidents and Another Account Dr To Take Minimum 102 10 2018 Chiro Benchmark Traveling And Agreements There Father With Your Intellect Which Can Be Created This Will Make - World End Will Not Created This Will Make - World End Will Not Created This Will Make - World End Will Not Edit Officer And Witty Then Account For Which One Can Still Positive Sunil Edit Liquid Subscribe Must Subscribe * * * * Subscribe * * * * Subscribe * * * * Half Limit Corresponds To Rate Countries Super Example Tower Soon One Time Viewers Building Number Two Workers And Three Times For Three Hours At One Time Fall This Point Element Alone With Account Se Vitamin C Element Urine Prevents Account Surya Building Come App Download Vibration Weaver The Forest And Share Trading Due To This Performance Rally In Delhi For Elements Present President Will Not Be Riching Android In the best modern times, between for the element fit will find management and now established after and elements which saw in this will see how to change the condition where it's great Dan Zero Ne Bigg Boss Want To Be Greater Than Love You Want Big Returns You Show It A Second Difficult Twitter Account This Account Positive Element And Decrement Subscribe To That Patent Of Swine Flu Organization See It's Working For Education Only Patient And Listening
Intersection of Two Arrays II
intersection-of-two-arrays-ii
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**. **Example 1:** **Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\] **Output:** \[2,2\] **Example 2:** **Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\] **Output:** \[4,9\] **Explanation:** \[9,4\] is also accepted. **Constraints:** * `1 <= nums1.length, nums2.length <= 1000` * `0 <= nums1[i], nums2[i] <= 1000` **Follow up:** * What if the given array is already sorted? How would you optimize your algorithm? * What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better? * What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
null
Array,Hash Table,Two Pointers,Binary Search,Sorting
Easy
349,1044,1392,2282
5
hello everyone and welcome to python programming practice in this episode we're going to be covering leak code number five called longest palindromic substring this is classified as a medium difficulty problem so it might take some doing to get the answer i'll start by reading through the description and the examples given a string s return the longest palindromic substring in s it's not a very detailed description there but let's parse out what that means basically a palindrome is a string of characters that's the same forwards and backwards so if you reverse it's the same thing so the longest palindromic substring of a bigger string s would mean all the different substrings within s what's the longest one of those that is also a palindrome so that's also the same forwards and backwards let's look at a couple examples to see what that means so example one this input string is this b a d and then the output is b a b that's the longest substring within s that's the same forward and backwards we can see that s itself if you reverse it that's not the same because the first and last things are different and i guess both of the four length possibilities are also out because that if you reverse it that can't be right because there's the different thing at the beginning in the end and this one there's something different at the beginning in the end so the longest thing that we have is length three this b a b if you reverse that it is actually the same thing so that is the output of the first example two c b d i guess in this case the output is bb because that's the same forward and backward even though it's just one letter repeated it still counts as a palindrome and that's the longest one there i guess if the input is just a single letter that's an easy one it's just we return the single letter back a one letter string is a palindrome i suppose because you reverse it and it's still the same thing and then if we had just ac as the input we could just return a because the longest palindrome there is just a single letter so we're also given a couple constraints here the length is going to be between 1 and 1000 so the length of the input string and the string is only going to consist of digits and english letters that are lowercase and or uppercase now it's not making a distinction between whether lowercase and uppercase should be considered different or not so i guess technically we would consider an uppercase a to be different than a lowercase a so we'll just kind of treat those as if they're different letters so let's pull over to the code editor now and start thinking about a solution i think to start with this problem i'm actually going to define a helper function right away that lets us check whether something is a palindrome we're probably going to want to be checking whether various substrings or palindromes a bunch of times so we can write a helper function to allow us to do that i'm going to go ahead and write this in a pretty short way here def check palin we're going to take an input string s just like we're given and then we're just going to return whether s is equal to the reversed version of s and we can do that with this kind of slicing operation trick so all this is going to do is take some input string and see if it's the same as the reverse version of itself if it is that's a palindrome this will return true if not it will return false so this helper function should come in useful later on when we're checking whether sub strings or palindromes but to think about solving the greater problem let's pull over to the white board really quick and see how we might think about it so i've written down a string here that does have a palindrome in it but the whole string isn't a palindrome and how would we go about finding what the longest palindrome is well one way we could go about this that could work is simply check all of the possible sub strings and whether they are palindromes or not and then return the longest one and if we check the longest substrings first and then we can just return whatever we find as a palindrome because the shorter ones are coming later and we're only interested in the longest ones so how that might look like with this string here well first we'd check the longest substring if it's a palindrome well the longest substring is the whole string itself so we'd look at that we'd pass it to that check palindrome function we wrote and see if it's a palindrome or not it isn't so in that case we'd have to begin checking shorter substrings so then we'd check perhaps this one length four and that's not a palindrome then we check this one the other one that's length four that's not a palindrome and then we just continue drilling down into smaller and smaller substrings so next we'd check this length three one that's not a palindrome we check this length three one that actually is a palindrome so at that point we could immediately return this substring because if we are checking in longest order first as soon as we see a palindrome we know it's the right answer and we can return so this might not be a super efficient solution to the problem because if the string doesn't have any palindromes in it until the single letter version of a palindrome we could end up having to basically check every single substring until we get to that point so the code could be pretty slow but this should be a way to do it even though it's kind of a brute force solution so back in the code editor now we are going to do this solution we'll call it check all sub strings so what we want to do is loop through all of the possible lengths for sub strings but start with the longest ones so for length for the possible length of sub strings in range well the longest sub strings are going to be the whole length of the string so len s and we want to start with the longest one so we're starting with len s and then we're going to go down to the shortest ones so all the way down to zero and to go backwards we say minus one so basically here we're just iterating through all the different possible lengths of sub substrings starting from the longest ones and then for each one of those possible lengths and now for each one of those possible lengths we also have to loop through every possible starting position of a substring with that length and then check each one so for the first one that's the whole string well there's only one starting index position for that it's just index zero but in the next case when it's one shorter than that we have to check two sub strings and then three sub strings etc so basically for start index so for some starting index in range zero the first one is always going to start at zero but then we need to check a number of substrings that grows one with each iteration so to do that we're going to set this range to go to the length of our string plus one but then we are going to subtract off the length of the current substring we're checking so basically as the length of the stub strings were checking shrinks then the number of starting indices we're checking for that for loop grows so as we get deeper we're basically checking shorter and shorter substrings but we're checking more of them so now all we really have to do is inside this for loop we have to check whether the substring we're looking at is a palindrome or not and if it is we'll just return it so if we called this function checkpalin and now we just have to be careful about what our substring is going to be so we're starting from this start index that we have here and we're just going to go up until the start index plus the length of the substring that we're looking at we called that length so if this is true that means we found a palindrome and we should just return it so let's take out that substring that is a palindrome if that is true we will return it and we actually don't need to include any extra return statement after this because eventually if there isn't a palindrome longer than length one well eventually we'll get to length one substrings with this loop and then the first one of those we see it will just be found to be a palindrome and it will return so we don't need anything outside of the for loop eventually this will return with whatever the palindrome is even if it's something that's length one so close this final brace here and then hit submit on this one now if we didn't make any errors that this should be a working submission but it might be pretty slow so medium problems sometimes require faster speed than we might get with this it's taking a while to judge let me pull over and see what the result is so this was a submission that worked so logically it does solve the problem but it wasn't that fast we see the run time was a bit over seven seconds so it was only faster than about 18 of other python 3 submissions so it was fast enough actually to pass the greater which means it wasn't like the slowest thing imaginable but it still wasn't very good because most of the other submissions were faster so let's pull back to the whiteboard and think about how we might be able to find a solution that's going to be a bit faster than the one we had so basically what we want to do is avoid checking every single substring and perhaps avoid a double for loop where within each of the loops we're doing a palindrome check because that could be something on the order of like n cube type operations we would want to find something that maybe we're only looping through once and then we can do some checks on that so one insight that's important to have about how palindromes work that can help us solve this is that a palindrome has a given center and then everything within the palindrome around the center also has to be a palindrome so one way we can think about solving this is we can check all of the different possible centers for a palindrome and then see whether there is actually a palindrome starting there if there is we can extend it in both directions until we find the biggest palindrome for that center and we can just continue doing that for every single possible palindrome center that there is in the string so let's give an example of what that might look like so one potential center is just the first character and that's not a very interesting one because we can check the first thing well obviously a single letter is a palindrome but then if we wanted to extend the palindrome from that center we'd have to extend it one this way and one this way to check a three-length and one this way to check a three-length and one this way to check a three-length palindrome but for this case we just stepped off the front of the string so we can't even check that so for this zeroth index we can really only check a one-length palindrome because as soon as one-length palindrome because as soon as one-length palindrome because as soon as we try to make it wider or extend it's just steps off the front but what if we started instead with b as our center so the next thing well we could check that and we know that a single length string is a palindrome for sure so we don't even really have to make that check we can immediately extend one to each side and check whether that's a palindrome and in this case it isn't so since it isn't we don't need to check anything bigger than that because if the center isn't a palindrome well anything extended off from that wouldn't be either in this case we'd also be stepping off the front if we extended again and then we could check the next one so the next center would be c and we could check is that a palindrome oh yes it is so we'd find that we at least have a palindrome of length three now after checking that we could extend it again and then we check this one well that's not a palindrome so we'd store in our back pocket we found this one of length three and then we could continue doing these checks for every single position and after doing that we can just track whatever the biggest one is and then after doing our loop we'll know what the biggest one was and return it in this case we just returned the three length one that we found here bcb now there are a couple other things we should be thinking about if we're going to try to use this solution there's actually kind of two different centers a palindrome can have it can either be an odd length palindrome in which case there's just a single letter at the center but we can also have palindromes that are even length where there's two letters at the center so for instance we can have centers that are kind of between each of the letters where the center is actually a two letter pair and we'd also have to account for that possibility so we'd have to check like a substring starting with this and extending off one each side there and check a four length one a six length one etc so we'd kind of need to do two different checks one for centers that are for odd length palindromes and one for even length ones another important thing to consider is that since we're only looking for palindromes that are the longest that can save us some work when we are checking new palindromes with a new center for instance if we found this palindrome that's length three well at that point all we care about are palindromes that are bigger than length three so when we're checking a new center say we moved on from that one to this one well we don't even need to check this three length substring now because three isn't bigger than what we already saw so we can go ahead and immediately start from this center but check something that's at least one bigger than that so we'd step out to five and we can just keep growing like that so we're basically going to have to keep track of some kind of step variable that can tell us how big of a substring we can take at the current center every time and by doing that we can just save ourselves some work by only looking at substrings that are going to be bigger than the one we already saw so let's go ahead and drop back to the code editor here and see how we might be able to code this up now let's just make some space we'll probably want to use our check palin function again in this solution so we'll just keep that at the top but we'll have a second solution here called perhaps grow from center so we're going to need to start by just initializing some variables that's going to keep track of things for us so we needed to keep track of our current biggest uh substring that's a palindrome so to start off with we can just set that to s0 because we know the first letter itself is going to be a palindrome it's just a single letter so we'll start off with that as our first scene one length palindrome and then we can go up from there and we're also going to keep track of that step so how far we should step out from the center when we're checking our next palindrome basically that's going to be something like half the length of the biggest one we've seen so far so let's say step is going to be equal to the length of the biggest one we've seen so far and then we'll just do floor divide two so when we are starting off with we're basically not going to have a step because one floor divide two is zero so in that case we'll just not have a step but then as our biggest palindromic substring grows this step will grow and allow us to only look at bigger and bigger substrings so now we have to implement the logic of looping through all of the centers and growing substrings out from each center until it's not a palindrome anymore and we're going to kind of do two different passes on this for each of the different center possibilities so we'll start with the single letter centers that are for when there's going to be an odd length string so we'll say handle single letter centers first and for that we're going to say for center in range one comma len s minus one so basically we're going to consider every single index position from index one to len minus one to be a potential center the reason we're not checking index zero well we already initialized index zero here so and we know that's at the very beginning of the string so we can't extend it at all it just jumps off the front so we don't need to look at that and then the same thing goes for the last index like we don't need to grow anything from that center because it can only be of length one anyway so we're going to just exclude those and now we're going to define the bounds of what the substring is going to be so that's we're going to define that as a two length list and the bounds are going to be our center index minus one plus that step length that we defined and right now the step length is zero and then the upper bound is just going to be the other side of that so instead of minus one plus a step i'm going to say plus one plus a step so basically that's just extending the bounds out by one in both directions from wherever the center is because we know we don't need to check anything that's only of length one we already found something of length one right away so this is for the first pass basically checking something of length a substring of length three but then as we increment the bounds it'll grow it to length 5 length 7 etc if we keep finding substrings so basically as long as we can extend our substring one in both directions and that's not putting us off the front or off the end of the string then we want to keep doing this loop and we'll continue doing it until we find something that's not a palindrome so while our bounds zero so all the first or lower bound is greater than minus one so something that actually exists and the upper bound which is bounds one is less than our length of our whole string we don't want to go off the end of the string so while that is true we just want to check whether the substring we're trying to look at based on those bounds is a palindrome so let's use our uh check palin from function here if check palin of our string s within those bounds so we're going from bound zero at the bottom end up to bounds one but we actually have to do bounds plus bounds one plus one because it's non-inclusive the way non-inclusive the way non-inclusive the way uh python slicing works so we have to do plus one here so if that's true we just need to update our biggest palindrome scene so far with what we're looking at because that means we just grew to a bigger palindrome and it's bigger than anything we've seen so far so we'll say biggest is going to equal that substring and now also when we save a new biggest substring we're going to increase the step size based on the size of that new substring so we'll just say the step size is also going to be updated again we just we can just recopy this code it's going to update it again based on the length of that new bigger substring so now all we have to do after confirming the next biggest palindromic substring is increase the bounds for the next iteration of the loop so we're going to say bound zero is going to be extended one in the minus direction and bounds one is going to be extended up one so plus equals one so basically this is saying is if we actually have a palindrome with these bounds we're going to store it and then make it wider and then the next iteration of the while loop will go and it will check that wider widened by one possibility and it will just keep widening and widening until it either hits a point where the substring is going off the front or the end of the string or we find something that isn't a palindrome so the else case here is just that well if check palindrome is false it wasn't a palindrome so we want to stop checking this particular center so we'll just break out of the loop in that case so after running through this whole logic here we will have found the longest palindromic substring for centers where they are in going to be a single letter so an odd length of the total substring so basically all we have to do is do the same thing here but for handle the case where centers have two letters so the other type of center so we'll handle double letter centers and a lot of the logic here is probably going to be similar but the ranges and for the indices are going to be a bit different so for center in range so we can actually start at the length of the step that we've already recorded so basically if we already found a substring that's kind of long we don't need to start at the very beginning because we're going to at least need to allow for sub strings that are at least longer than that so we can start at the step here and we will go to the length of the whole substring minus the step minus one so basically we could be going from zero to len s minus one but since we know that we have a sub string that requires us to have something of a certain length that's why we're starting at step and then going to len s minus step minus one it's just potentially saving a little bit of work by doing that and now we have to set the bounds these are going to be similar to the bounds we set for the odd numbered case but a little bit different so in the odd numbered case we basically started with a certain center and wanted to move both of the bounds the lower bound down by one and the upper bound up by one because we wanted to start with substrings of at least length three because we already had the single letter case of length one but in this even numbered case though we have to start with sub strings that are of length two so we don't want something that's three wide we want to start with account for things that can only be two wide so basically to do that we're going to instead of doing center minus one n step we're just going to take away the one here so we're not going to decrease the on the front side by one and we'll keep this the same because we want to extend it up to length two but now that we have the centers set up and the bounds correct for the even numbered version it's just slightly different than what we had to do for the single letter centers all of the other logic is the same we still want to check if the bounds are jumping off the front or the end of the string so that's the same we still need to check if they're palindromes within the specified bounds and we still need to do all these updates and all the bound incrementation so essentially all of this code is going to be exactly the same within this uh double letter version so let's paste that in there and so now we have one pass essentially that's handling the single letter center case we have another pass handling the double letter center case double and after these two passes complete whatever is left in biggest should be our biggest palindromic substring so we just have to return it at that point so let's say return biggest and now as long as there aren't any uh errors somewhere in the code here uh this should be a working solution so i'm going to go ahead and click submit on this one so let's pull over and check our result here so that time the code was a heck of a lot faster we got only 128 milliseconds and it was faster than about 97 and a half percent of other python 3 submissions so although it might not have been the prettiest code and we could probably figure out a way to avoid doing as much replication of the same logic as we did for the odd and even numbered cases it was fairly efficient so i hope this provided some insight on how you could think about approaching a problem like this and about how doing a few things to avoid making additional checks you don't have to make can save a lot of computation time so thanks for watching and keep coding you
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
229
Hua Hai Hello Hi Friends Welcome To My Channel Today We Are Going To Solve List Code Problem Number To 9 Majority Element 200 The Problem Statements And Settled In The Draw Size In Find All Elements And Happier Mode On In Three Times Solve We Have Been Given Address Of individuals and also have been given additional should of Vinod link they are divided by three hundred have two of return list of all elements that appear for more than by three times for example in other side from 3230 last elements who have to find out elements which Appear Three Divided By Rush One Means More Than One Time Some More Than One Tennis Minister Appear Two Times He Raw One Pinch One By One Is 101 That If You Those Times And In This Example One Ko Me To Go To Total Elements And Divided By Three Us point 6 and all elements that you want to visit more gun point to point 60 output in one form to do 202 aam atth to ayush yadav map where are you no like karo I am posted in treating all the numbers of the year and hui ya His chairing was the frequency of each of the elements in the year 1 year 100 Cafe Effects of First Time Digest 0.1 in frequency and benefits of 0.1 in frequency and benefits of 0.1 in frequency and benefits of wearing appeared in more than 105 injected into the frequency and after that is already calculator fresh value based on the total elements After a divided by 30 chest unit rate through the map and I will be who arm whole get all the elements which appear for more than sight and asked how to the result of that Sophia Rai tried all these test cases and for all test how to pass Which candidate is Samriddhi Solution 210 Solution is not accepted and thanks for watching the video Effigy Videos Helpful Tube Please Consider Subscribe In To My Channel And Giving Me Atmaswarap Thank You
Majority Element II
majority-element-ii
Given an integer array of size `n`, find all elements that appear more than `⌊ n/3 ⌋` times. **Example 1:** **Input:** nums = \[3,2,3\] **Output:** \[3\] **Example 2:** **Input:** nums = \[1\] **Output:** \[1\] **Example 3:** **Input:** nums = \[1,2\] **Output:** \[1,2\] **Constraints:** * `1 <= nums.length <= 5 * 104` * `-109 <= nums[i] <= 109` **Follow up:** Could you solve the problem in linear time and in `O(1)` space?
How many majority elements could it possibly have? Do you have a better hint? Suggest it!
Array,Hash Table,Sorting,Counting
Medium
169,1102
8
hi guys welcome to the channel before we dive into the question if you are new to the channel please consider subscribing the question says the function first discard as many as white space characters as necessary until the first known white space character is found then starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible and interpret them as a numerical value the string can contain additional characters after those that form the integral number which are ignored and have no effect on the behavior of this function if the first sequence of non whitespace characters in string is not a valid integral number or if no such sequence exists because either STR is empty or it contain only whitespace characters no conversion is performed and if no valid conversion could be performed we should return a zero in the note it is mentioned only white space or you can say space is considered to be the white space character and assume we are dealing with an environment which could only store integer within the 32-bit signed integer range within the 32-bit signed integer range within the 32-bit signed integer range which is - to the power 31 2 to the which is - to the power 31 2 to the which is - to the power 31 2 to the power 31 minus 1 if the numerical value is out of the range then we need to written maximum or minimum of this range so I have taken all the example given in the question if you see the example number 1 we were simply going with the string with a numerical value and we will simply written it as 42 but if we see the example number 2 first of all we have some space and it was clearly mentioned in the question that we need to discard the whitespace so we will discard it then we will take care of the sign we will use a sign as it is and we will use a numerical value as it is so it will become minus 42 if you come to example number 3 we will see for the white space we don't have it then we will see whether it have a sign or not it don't have any sign then we will see whether the first sequence is a numerical value or not yes it is then we will simply convert it here and we will see whether after that we have a word or no numerical value or not so no numerical value we will not use all of this and we will simply written for 190 and if you come to example number four you don't have any white face you don't have any sign and the very first sequence is unknown numerical inner known by space we will simply written zero and if you come to example number five if you see this number it is clearly out of range so we will simply return - to the power 31 will simply return - to the power 31 will simply return - to the power 31 let's see how will you gonna a pair of all the edge cases so for the wide space we can use a function it will take care of the wide spaces after that for sign we can simply write if string 0 equal to minus or in the same way we can check for plus so in this way we can take care of minus and plus sign then we need to that whether the first sequence is note American note white space or not for that we can use is numeric so this will tell us whether the given element is a numeric or not and in the same way we can check for the element after our numerical value and for simply this we can write whether string exists or not and for out of range first of all we will convert the string to the integer and then we will check whether it is out of the range or not so converting a string into an integer is the main gist of the problem so let's see how we can convert a string into an integer before that lets see suppose we are given with the number 4 5 6 so we can also represent this number like 4 into 10 this will be equal to 40 then we will add the next number into it 4 plus 5 now it will become 45 then again we will multiply 10 this will become 4 50 then again we will add the next number for 50 plus 6 it will become 4 56 let us take one more example 123 so we can write it 1 in then it will become 10 then we will let the next number it will become 12 then again 12 into 10 it will become 120 now we will let the next number to them 123 let's see one more example 7 8 9 first we'll multiply sign with 10 it will become 70 then we will let the next number it will become 78 again we will multiply then it will become 780 and we will add next number it will become 789 so now let's see suppose you are given with a string 1 and if I say hardy well what will give us the SK value of 1 that is 49 and SK value of 0 is 48 and or do you take a string I was string 1 and if I take body of 1 + - / do 0 it will give me 49 - 48 of 1 + - / do 0 it will give me 49 - 48 of 1 + - / do 0 it will give me 49 - 48 1 let's take another example string 2 if I take audio - - body of 0 this will be I take audio - - body of 0 this will be I take audio - - body of 0 this will be 50 - 48 will be equal to 2 let's sync 50 - 48 will be equal to 2 let's sync 50 - 48 will be equal to 2 let's sync string 10 over do 10 - body of 0 will string 10 over do 10 - body of 0 will string 10 over do 10 - body of 0 will give us 58 - 48 give us 58 - 48 give us 58 - 48 so from this pattern we are getting one thing that if I use over do any number in string - Ord of 0 will give us an in string - Ord of 0 will give us an in string - Ord of 0 will give us an integer form of that particular string and using this pattern and using this representation I can convert a long string of numeric value into integer I hope you are clear with the concept if not let's see the code I'm pretty sure after seeing the code you will be employer with the question so let's write the code let's first of all take care of our edge cases so first of all we will remove the white space and for that we will use strip and it note STR we will simply return 0 and we will take our variable negative which will be false initially and we will take up out this will be 0 initially if first we are at index 0 is equal to minus then our negative will be le STR at index 0 is equal to plus or negative will be equal to if STR it index 0 is not no married then we will simply written 0 and we will convert our string at index 0 into integer using body now we'll take a for loop for I in range from 1 to length of STR because we have already converted our string at index 0 into integer if string it next slide this numeric then our out will be equal to out into ten-plus over d string at index out into ten-plus over d string at index out into ten-plus over d string at index I minus overdose ring zero and if note negative and our out is greater than equal to then we will simply return and this negative and our out is greater than equal to which means it is less than this number then we will simply return else we will simply break them if wrote negative we will simply written them out else we will return minus a so this was the code if you will copy this code and paste it on the lip code it will going to definitely work you can find the code in the description below if you have any question please let me know I will try my level best to help you thank you so much for watching the video please don't forget to subscribe
String to Integer (atoi)
string-to-integer-atoi
Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi` function). The algorithm for `myAtoi(string s)` is as follows: 1. Read in and ignore any leading whitespace. 2. Check if the next character (if not already at the end of the string) is `'-'` or `'+'`. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. 3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. 4. Convert these digits into an integer (i.e. `"123 " -> 123`, `"0032 " -> 32`). If no digits were read, then the integer is `0`. Change the sign as necessary (from step 2). 5. If the integer is out of the 32-bit signed integer range `[-231, 231 - 1]`, then clamp the integer so that it remains in the range. Specifically, integers less than `-231` should be clamped to `-231`, and integers greater than `231 - 1` should be clamped to `231 - 1`. 6. Return the integer as the final result. **Note:** * Only the space character `' '` is considered a whitespace character. * **Do not ignore** any characters other than the leading whitespace or the rest of the string after the digits. **Example 1:** **Input:** s = "42 " **Output:** 42 **Explanation:** The underlined characters are what is read in, the caret is the current reader position. Step 1: "42 " (no characters read because there is no leading whitespace) ^ Step 2: "42 " (no characters read because there is neither a '-' nor '+') ^ Step 3: "42 " ( "42 " is read in) ^ The parsed integer is 42. Since 42 is in the range \[-231, 231 - 1\], the final result is 42. **Example 2:** **Input:** s = " -42 " **Output:** -42 **Explanation:** Step 1: " \-42 " (leading whitespace is read and ignored) ^ Step 2: " \-42 " ('-' is read, so the result should be negative) ^ Step 3: " -42 " ( "42 " is read in) ^ The parsed integer is -42. Since -42 is in the range \[-231, 231 - 1\], the final result is -42. **Example 3:** **Input:** s = "4193 with words " **Output:** 4193 **Explanation:** Step 1: "4193 with words " (no characters read because there is no leading whitespace) ^ Step 2: "4193 with words " (no characters read because there is neither a '-' nor '+') ^ Step 3: "4193 with words " ( "4193 " is read in; reading stops because the next character is a non-digit) ^ The parsed integer is 4193. Since 4193 is in the range \[-231, 231 - 1\], the final result is 4193. **Constraints:** * `0 <= s.length <= 200` * `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`.
null
String
Medium
7,65,2168
77
Hello everyone, so today we are going to solve late code 77 problem name combination, so this problem is given under medium category in late code, okay and my request to you is that before solving this problem, you should follow the simple steps of recension plus back tracking. There are problems, either by revising them a little or by practicing a little, you come in this problem, if you do not know the request, if you do not know back tracking well, then do not jump directly into this problem, if you have difficulty in understanding the concept of this problem. It is possible, okay, so let's start this problem, so what is the problem, so I understand you, I want to understand, then think that N = 5 and k equal to 5 means all the numbers within 12345 are integers. First we have to see what is the number of equal tu so k numbers chosen from d range one tu n then what we have to do is to print the total of these five numbers that we have, the possible combination times in which the numbers are divided by two. Two numbers are basically the possible combinations from this set number would be 3 4 could be 3 5 could be the combinations Basically I can return the answer in any order so it is not that the order is my specific I am one Do not look at one comma 3 after comma 2 1.2, you not look at one comma 3 after comma 2 1.2, you not look at one comma 3 after comma 2 1.2, you can also give comma three, okay and one more thing along with this, let me tell you, this problem is also that if you have printed 1 2 then now you Why can't we print com one because this question has been asked that we can find the combination from one comma 2, so first tell me this problem, there can be two ways to solve this problem, before we can solve it by logic also. We can solve this problem and what else can happen is that we can solve the problem by back tracking also. If you have solved Iniquin's problem then you will find this problem very easy, then you can revise these problems once. Okay. So I reduce it first, I first discuss the solution of back tracking, after that you get the requested solution and easily understand that what solution do we have in it, what do I have, then I set the solution so that the problem becomes a little easier. Yes, it is for me, so I first set the rule that which is my vector, means inside the G factor, I two here, equal to you, means the number of numbers, I will store inside this G vector, so the numbers are my numbers in this vector, cool. B distinct means numbers should not be repeated meaning chemical tu hai toh 1 will not come 2 will not come 3 will not come ok I have the second one I will store it in the factor in the order of increasing numbers meaning the factor I will have is one comma 3 It is possible but not 3 1, first three is A, one is A, after one three will come, this order will come for me, I always want increasing like 1 2 3 4, it will think that this is a vector, meaning when equal to four, then here it is like this for me. Okay, no, the max size of the vector should be yours. The problem is, so I am considering it again so that we have a little eye on it. After that, second, this is very important for me. Increasing order. This is very important for me. Why is this? It is important that when we do this code, it will be very clear to you because why did we take it this way? Okay, maybe by now you are completely done with it. Now, when we do backtracking, before that we check one thing that whatever will be the backtracking. This will be a recursive code, otherwise it will have to be my base condition for the requesting code. What is my base condition? What is my condition? The factor that is going to come to me is a vector, that is, inside which I will store it in numbers. If the size of the vector is The cake is equal to I mean, what can be my base condition that when my vector becomes full, then I can just say that if I have one of the iterated types of Sochi which is count I am trying to figure out how many are still remaining inside my vector, meaning, how many can be the number of remaining numbers, so how many are there, think about what I mean by remaining, that is the size of my factor, but till now there are two numbers in my vector. If the number is stored then what is the remaining till now, so what I am saying is that if I have such a disease, if I have a counter that R is equal to three, then how come I am equal, you are equal, it will become zero. We can also say that my factor is full, basically I am talking about saving but we can do this code in two ways, so I will show you both the ways as I am explaining it, basically here we are. We will not even do that, we can do that, thinking that when this is my equal, you are equal, you will become zero, the camera is happening, it means we are selecting someone, my factor has become full, then what will I do, I will give this answer b and sir dot. I will do it in push back, that means I will store it inside the answer vector, which is my vector. Okay, I hope you will understand the base condition. I am writing the base condition clearly. I can write two types of base conditions and according to them, I There will be a little change on the code, first the base condition which is mine is answer dot push back also returns OK otherwise here we return answer dot push back also in two ways, we can write it for the country and if of these two ways then which is We will also write the code, we will have to make some changes in it, but both are separated, so before that I say that my n = 4 and k is before that I say that my n = 4 and k is before that I say that my n = 4 and k is equal to tu, what does it mean that my vector is a factor of tu length of D vector is this, okay, what do I have, one, you three, four, so what happens to each trick, each tree has a level, tree, each tree has a level, this is a Level is also like this, there are many levels, so in the same way, what I am saying is that we are denoting each level of this level, how this will be the vector, this will be the first meaning number, this will be the second number, so this is From the number, this will be the first number, this will be the second number, meaning when I have one in the first, then what can I put in the second, how to do this, the three rules I had made, remember again the three rules, what I said, what is my first rule? Can I keep one here? Think, can I keep one here again? Can I keep one in seconds? If there is regeneration, what happens in it, then what will we see? We will also give you a friend from here, this is my back tracking method. Meaning, I will make a change on my variable, after that change, I will do the rest of the calculation, below that I will only do the cost, here any more recursive calls will be thought that this is equal to three, equal to four, equal to five, such that All the research below will be done, when your [ __ ] ends, research below will be done, when your [ __ ] ends, research below will be done, when your [ __ ] ends, then what will I do? I will give you the pulse from here. Clear I hope you understand this far, this is my back tracking state, three is four, so can I keep three. It's an obvious thing, I can keep three, can I go down any more level after three, otherwise there will be 3 cm bed, four will be reduced, does one have any other option, is there any way to survive, otherwise we So we can speak, that's why what do we do in this also, we bacteria, at this moment we will erase the one from inside the vector, the data one in the first position, basically whatever is in the first position, we will rub it from here, clear, then we go to A. Tu pe first koi first level tu meaning, we put tu inside the vector, when I put tu inside the factor, can I give one after tu, can I give one, not one because my second one, what does he say that cool be in. Increasing order Must be in increasing order If I do here then if I do one then it will not reduce because it is going against my rule then one will not be confirmed here Can it be free here There is no problem here, the problem may be from there itself, we cannot go down further after number four and there is no other option, so we will end from here, okay, don't get confused by this, it is not a 00 or anything. Basically the root is what is it doing these days that my bus has not started till now or the factor between me and mine is an empty factor ok so first second is done increasing order cannot go because increasing order will not happen again see If I am putting one in three then it will be in increasing order, it will not happen, you are putting it, this will not happen, I can put three after three, I cannot put three after three, no because these should be unique numbers, so what option do I have that I can put four. If I can go then I put four here, see below after four and if I can't go then I will go sitting in force, when I force 3 there will be no other option because my maximum numbers are 1234 so I What will I do, it will be tracked from 3, that means when it is butter from three, then it is my end and when it comes to my fourth, you can see that four has no other option because there is no other number after four and my So the size will always be two, this will not happen, okay, second thing I asked you, how do we know this question of back tracking, so this is back tracking, see, there are two things to identify back tracking, now we will take care to identify if there is a problem. I am asking something like this, which is a possible combination. Okay, if I am asking something of the possible combination type and inside it you can see some rules that there is a rule that numbers in a vector must be distinct, bill can be stored in this. Well, I have my own but the maximum size of the vector will be the same and should not be different from that, it should be different in every set, anyone can come in the order now, so if someone is giving such a condition, then you should always remember that the possible combination. Plus, if there is such a condition, then in this case, back tracking is very important, which is a possible combination. Even if you get such a story, remember that this boyfriend will definitely be there is no doubt in it. Okay, so let us now see the back tracking. How do we write the code that if I have any level A then you are seeing that first what do I do, first I am my factor, before that I am making one putt, after that I for one. I am left, you will be three, what will happen to three, meaning when I think of my cake, you will be three, then you can be here, then you can be three, if you can be here, then instead of three, there will be four. It is possible that after one you will come, after you here, 34 will come, or after one, three will come, after three, four will come here, it will happen like this, it will be like this, but when here, after one, when you come here, then here Three will also come, then four can be a in the first, so these are the cases which means you can see that there will be a loop here because in the first step, I have to pat one also, in the second place there is a there is a there is a in the solutions. So if I want this completely, then for sure the look will be done here. The result will be seen. After the look is done, what is happening is that we are putting one by one, which means that after putting in the first position in this vector of mine, here I am. It will be done, then I will go here, I mean, whatever is missing inside them will be done here. Okay, so that's why I said, you will see it completely, what is this exact word of yours, ditto, complete code right here. And I want to give you a concept, so see, first I gave one here, okay then one's [ __ ] is finished gave one here, okay then one's [ __ ] is finished gave one here, okay then one's [ __ ] is finished like one you came one three came one four came one's [ __ ] is finished then what did we came one's [ __ ] is finished then what did we came one's [ __ ] is finished then what did we do one If it is 2 3 4 from here then it has already gone to the ground. Okay then I will put it. What did I say that I cannot give forest here, I cannot see the forest because the forest was reduced and whose [ __ ] is already finished. and whose [ __ ] is already finished. and whose [ __ ] is already finished. Basically, I can say that I have already finished, okay, so far, perhaps we will write the construct time, inside that, what am I taking first, I will take the number that I will store inside my factor. And offense, this is my variable which is what I will return from the function in ultimate. Okay then what will we take which I am taking important. Okay current variable, you can say, let's give it a name, I will name it P. This became easier for me, so I am keeping it here in two parts so that you can see that I told you earlier that you want two types of tracking, but we can write it with two types if its size is right, after that you will state the forint oil. I'm going to process what I'm going to process P I'm going to process back track first argument what's mine second argument is mine from and third argument is mine in fourth argument what's mine look now what's going to happen right now no I'm here But always by me tu means tu or whatever number is more than tu, that is why what will I do, if my current value is i, then I will clear i + 1 here, that's all the I will clear i + 1 here, that's all the I will clear i + 1 here, that's all the code, this is the complete run. After this, what should I do after this, just back means the change I did, the back means the change I did, the back means the change I did, the number I called, like I, you, after that, no further value can be added, then return it, then after that, which back track? Hey, what did you say in without step, first I thought that earlier I had one foot here, so now you are one foot, so it is okay, your [ __ ] is finished, now you are one foot, so it is okay, your [ __ ] is finished, now you are one foot, so it is okay, your [ __ ] is finished, so when I am returning from you, I removed 2 from here. So this is my step, this is the complete code, see the end of the code, this code is so short, there is nothing more than this, it is ok, this is one method, you can also do the second type like this, if IF's equal then equal you. If it is zero then what will we do? How many numbers are left to be stored? Remaining numbers are the B fields. Okay, so what will we do for that? Okay, one more thing, i plus one, why i plus one, because we have to go to the next number, just give me the code. Now we come to the recursive code, the second solution we want to see is how to solve the request problem, I can give you a small they are without size - off k mines you I they are without size - off k mines you I they are without size - off k mines you I can write this index like this This is the only concept you have to give, so you see what is happening that I will do this, the entire code will be exactly similar to the previous one, I will just remove the line about bag and remove the line about bag and remove the line about bag and keep it in this only. Come on, I am writing this code properly and giving it to you, so come on, I have written it in such a way that what should he say, this is our answer vector of vector in and time will come, equal tu zero hum What will we do? Okay, then we will do this, what will happen to me, K will become -2, so what will happen to me, K will become -2, so what will happen to me, K will become -2, so what will happen while doing this is that when I have this value, then this will be the first index of a vector, when this is - 1, then this one will be the second index of the vector. when this is - 1, then this one will be the second index of the vector. when this is - 1, then this one will be the second index of the vector. Meaning, where it will be stored in the second element, okay, then call it I plus one, okay, this is your code, this is also the correct code To code this, you must have understood whether you are digesting it well or not. It's happening okay Victor Interview After that we are creating our own function there first we will start the video Second vector of vector off in and okay what will we do first step without Pushkar first we will index that First of all we will push this after that we are doing this function tomorrow to file up in the next index and P plus one sorry [ appreciation] will change push back also return okay what else to say Okay so it is subject it is accepted and you can also see it bits 92.3 means if bits 92.3 means if bits 92.3 means if it performed better than the first one then you must have understood both these codes well then practice it two-three times. You are practice it two-three times. You are practice it two-three times. You are seeing that how you can do this back tracking or request, how both are linked, how you can do it, you will understand very well and the better you can draw the status tree, the more quickly you can code. Can design ok so that's all we get for today
Combinations
combinations
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`. You may return the answer in **any order**. **Example 1:** **Input:** n = 4, k = 2 **Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\] **Explanation:** There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination. **Example 2:** **Input:** n = 1, k = 1 **Output:** \[\[1\]\] **Explanation:** There is 1 choose 1 = 1 total combination. **Constraints:** * `1 <= n <= 20` * `1 <= k <= n`
null
Backtracking
Medium
39,46
450
hey everybody this is larry this is the last day of the august lego day challenge yay congratulations everybody uh yeah let me know what you think uh hit the like button the subscriber and join the discord and let's look at today's problem hopefully it's a fun one delete known as bst uh given a root no and a key delete the node of the given key return to root node reference updated okay um yeah because you have to search it uh that's fine my friend keep on peeping um okay so i mean they're a cup so this seems pretty straightforward uh conceptually in that it is you know the search part is easy um you just have to search and then it was found deleted right uh and this is a very textbook problem so in theory you know how to handle this and if not you can read up a book uh for me i actually don't remember exactly how to delete it i mean i know how to delete it but i don't remember i know all the rules uh so let's say so i think for me it's just uh about going for the cases so let's say we delete three right in this case we did it three uh do we promote the left or the right in this case it doesn't really matter um but let's say four has yeah maybe another example is okay uh you know we delete five right do we promote the six what if six has something small guys yeah someone like that right so yeah so i think it's just figuring out uh how to update it and i think i actually don't remember how uh the textbook version of how to fix it is to be honest um the way that i would do it maybe is just the way that i think i would do it just as a naive uh thing would which is also would be of h where h is the height of the tree is just replace whatever key that you found with uh with the node that is the smallest number that's bigger than it or something like that right would that be good enough um because the smallest number that is uh maybe not because then you if you have a linked list situation that wouldn't work right so actually uh i would say i probably don't remember exactly how to promote it because for example in this case if we remove five how do you want to promote it i mean i guess you could look at this and be like okay let's promote the six and then seven right but what if you have like just a full tree of you know let's see if i could if this shows up yep uh let's say you have a tree of something like um let's say this is six this is seven this is five this is eight so that like now you have a full tree here let's say you remove six oops let's say you remove six uh how do you know you can't just promote the seven because then the five would be weird right um i guess you could promote the five let's promote the seven and then just recursively uh just recursively take a random one and promote it is that weird does it have to be anything now because you can't do it that way because if you promote the seven then you can't promote the five because the five has to be to the left right so that's a well maybe i just don't know how to solve this one to be honest um just because i don't remember the specific algorithm so yeah so in this case how do you remove the sex uh it is in a non-cheesy way right uh it is in a non-cheesy way right uh it is in a non-cheesy way right because we could probably do some crazy things um i mean in variant here we could replace the six also this is just wrong but uh so actually we want five oops sorry friends uh but yeah if you remove this five then can you put the 7 here but then the 6 has to be on the left so that doesn't make any sense um i actually really don't remember i'm trying to think right now uh sorry for wasting your time so you know if you're new to the show uh this channel i usually do this problem live uh many times i already know the answer or i could solve it right quickly so i'm able to explain it as i code but this one i am a little bit stumped just because even though it is a very elementary um you know computer science algorithm class e uh problem it's just that like this number comes up so i guess i don't really remember how to do it and i have a couple of strategies that i would try to think about how to do but i don't have uh or like i'm not convinced that it'll be it'll work all the time right for example maybe one strategist okay replace the five of the four and then okay but then now we have something like one two three four oops like you have a linked list uh that's not a linked list but um like you have something like that uh what happens if you remove the two right well you're not gonna be you know so that's a little bit i mean you put up the three but i'm not sure that you know so there's definitely a couple of things here and i really don't know what the answer is uh to be honest um and i think so maybe this is a good example for me to go over what i would do when i see a problem that i don't know and i um you know try to figure out how to learn about this the first thing i would do is i would just look up the solution well not the solution but like the um the algorithm right and what i mean by that is um and when i talk about uh looking up the algorithm i don't mean the code i just mean like someone explain it to in words right so um okay so apparently there are multiple cases wow so this is not uh so i don't feel as bad okay so i did get it to here uh and this is me just reading this so read it with me uh and if you know if you're watching this video i hope that you know you get something out of this because um i imagine if you can actually find this problem anyway because this is a textbook problem so you can find in your textbook but for me i'm just trying to demonstrate how i would learn a new problem uh okay so down here search for node remove okay so we know that uh remove is in detail uh elegant for lookup okay the three cases okay so i uh no do we have no children that's easy okay that's true node to remove has one child if there's only one child then that's also trivial okay that makes sense uh and then now the two children part okay wow so i guess i did have it's just that i didn't think about doing them in two cases or in three cases in this case so okay so basically i did actually have it i just wasn't able to i think what i was trying to do was trying to have one case to fit them more but it turns out that uh just look at watching this uh reading this uh there's just three cases and we just have to handle it and i already know these three cases because we kind of talked about it on a stream uh on this cast and i think that so there's some code here which i'm not looking um so the thing that i would do when i look at um and this is true for competitive as well is when i uh when i look at the editorial i read the uh editorial but i really read the code because now that i have the idea i will force myself to implement as best i can so that i get practice implementing it even if i don't know it right or you don't algorithm because then now i can implement it in my own words and then afterwards conceptually depending how you know messy it is i might look upon other code to see how other people might implement it uh for me i have about at this point to be honest about 20 years of programming and implementation so i could probably generally implement anything um that's reasonable anyway uh but you know that doesn't mean that i can't learn it's just that uh usually that's not the part that tricks oh i could get something done but it might not be as clean as possible so okay so now we just have to go through our things uh and find the node right so okay so let's have a find function uh no um node key if node is none then probably messed up somewhere but otherwise um if no dot was at value is equal to key return node if no dot value is greater than key then we return uh find node.left then we return uh find node.left then we return uh find node.left uh l is returned fine no that way right so those are the three cases we get the note uh we can probably play around with this uh just you know let's just print the uh find a root of key so that we can kind of see this one let's see if this finds the five but one time ever so we do have oh i forgot to pass along the key so i guess i didn't know i just didn't remember to put them together that way so it is able to find the four and the five uh in the ready of h kind of way so now we have the note so oops notice you go to this and then now we can think about three cases right if note that's a little bit messy well now i'm just thinking about like okay now we found a node but in order to remove it we have to um we have to remove the node so oh you need kind of like need the point of reference but i guess not really that's what i was thinking about right uh so now if node.left is none uh so now if node.left is none uh so now if node.left is none and no oh that right is none so this has basically this is a leave then and register node is equal to none but that doesn't change the reference to this right so that's what i'm thinking of it so i need to parent to this so okay so how do i fix this so if no it's none just for not none doesn't really matter uh if code is go to key uh let's just do let's just pass into parent um yeah let's just find the password passing the parent so that we can return the note and the parent uh this and node but no actually this is good it's just that we put into finger on the thing um and this is just not as apparent uh though we might have to change the root reference as a result if we have to remove the root we will play around with it but if this is a leave then uh in this case this returns no uh parent dot oh this is a little bit messy as well because you have to click you have to choose which um you have to show which you have to return which way it went um how do people do this man i just talked about how good i am in implementation and then i just can't remember how to do it um yeah actually i guess we could just check uh manually if parent.love is huge uh manually if parent.love is huge uh manually if parent.love is huge this is actually not great but uh no parent.left equals none no parent.left equals none no parent.left equals none uh if parent.right is equal to node uh if parent.right is equal to node uh if parent.right is equal to node parent.right is either none right uh yeah and if parent is none the parent is none then root is equal to none because that means that the program is the root um the root variable not just the root node itself uh okay and then now we check else if no dot left is not none that means that uh well okay let's just do both uh both children it's not none and no doubt right is not none uh and this is again through like what you saw me with the googling for maybe i'm 20 30 seconds that's all i needed to know how to uh implement this right so my memory may be a little bit fuzzy but that's basically what i'm doing um okay but also because i already kind of had an idea of what to do right so okay so that means that we have bob chow get the biggest num bird that is smaller than and this num this target or key um do i want to write another function or is it just annoying uh okay yeah fine less than i guess well what do we want to go left and then we want to go as right as we can right yeah so we so actually we could just do a while loop i think uh current is equal to node.left is equal to node.left is equal to node.left while current and that right is not none uh current is equal to current.right uh current is equal to current.right uh current is equal to current.right uh and then yeah and then now current should be the smallest value so now uh no dot value is equal to current that value um but then right now we have to get the parent again so right parent is you go to the note because then now we're removing this number right so we have to point remove references to this node so basically that right and then now we do the same thing of uh this thing so now maybe we can put abstract at parent reference say paranode also i think i use bad casing for it because i think i use the other i generally use the other one but uh i mean this is current we want to remove current okay and then now if only one child right it's not none uh then uh no as i then parent dot left so if there's only one child uh then we set the parent to whatever it is okay so if parent dot left is equal to okay if parent is none then root is you go to node.left then root is you go to node.left then root is you go to node.left um i have found that i think i just need some else just to be sure maybe it doesn't but uh if you go to node then parent.left is you go to node then parent.left is you go to node then parent.left is you go to node.left else parent dot node.left else parent dot node.left else parent dot right is gonna know that right ah this is going to be messy to kind of um is this white no this is not that left still but yeah maybe i could uh i don't know this is a mess i don't know that i expect this to be correct to be honest uh but um but you know it's uh it's a learning experience uh let's see if it is at least right for these uh so this is okay for the second case but not the first case um and we moved to five and five is we what does this tree look like again oh yeah we moved to five and we put the four here but then now the i feel like well i mean it's okay except for that i'm now missing oh no this is okay if we have the same amount of numbers it's just a different tree right because there could be multiple trees um okay let's do you know one element uh two element and there are a lot more cases obviously um oh that's good i don't know which one it's airing i know but conceptually that's good none type as tourist doesn't even find this at all that's odd let me double check that this is the one that i'm airing on now that's well my answer is wrong um i thought this should take care of it for me uh why is the parent not none that's actually let me print this out real quick yeah so this is none so then yeah so this should call here which oh this is uh this is okay i got it's just that i silly python uh my understanding of python platform is fine it's just that i didn't do it correctly uh okay so then now uh that means one of these other ones are incorrect or at least uh it gives me an error a line 34 so why is this none it doesn't find two that doesn't seem right is my tree set up incorrectly it might be oh yes that's my bad okay you give it bad input it will give you bad input uh bad output i guess uh garbage in garbage out okay let's see okay so this looks good um it's just that i misunderstood the thing uh i think there are probably a couple of edge cases that i would test um i think the big one being the leaf so let's do that uh actually i already test that so okay let's just submit it and then uh i'm not 100 confident right now but uh yeah i would that's why i'm testing this oh did i miss oh because if it's not found okay i didn't i thought that for some reason that i thought that has to be in there so that's fine that's easy uh because if node is not it's none oops then we turn root because then we don't do anything after that um yeah let's just put it in the thing as well i for some reason i thought that there was uh you know i know that's sometimes you just misinterpret things let's submit it again oh well there's a visualize button that's kind of cool but i definitely have an issue here let's see what does this look like so we moved three i put the two and the four but why does the so it should go to left is not none and then it should do root is equal to node oh hmm there's two child so it should go here and then it set the root wait what yeah i will say one thing that is that when you do practice enough you have a reasonable like errors uncertainty of how confident you are about your code and that's why i was saying i'm not confident about this at all but with this three it should move uh get the two and then set the route to two okay i think i well i mean i know for certain that's a thing hmm i think i'm confronting a few things though uh i think i'm missing an extra case because basically what i did is i go all the way to the right and then i remove that node which is by definition a leaf but i don't take care of the case where um it's only the left and there's no right nodes right so okay so i have to do if current.right is none i have to do if current.right is none i have to do if current.right is none uh then we just set root dot root is equal to current notice you could know that left uh note that left is equal to um i'm sorry note that right because there's no right is none wait am i doing this right uh no roo is you go to current.left wait is it no it's just current which is no doubt left okay uh but then this node doesn't have this is no dot left that right so that means this is root.right is equal to um root.right is equal to um root.right is equal to um okay i need to fix something right here um old root right is equal to root dot right and then root right as you go to over right so that we don't get rid of it um okay and then now we can do an else which is this other thing this is the most wrong answer i've gotten for uh these in a while which maybe is interesting uh but yeah this is should be good enough uh yeah ace with these answers oh that's tough um also say that's one issue that's sometimes hard is that like you can't really because we have different algorithms right so you can't gauge from these uh but clearly uh you should at least have the same number of nodes so just as well and this is a lot of wrong answers but you know so i removed julie what do i get i guess i made a mistake in assuming that this is whoops uh what i should say is it should be parent i don't know if this is right actually i mean it's kind of right but it's i don't know it's enough right let's kind of take a look real quick yeah i don't think i actually well there's just a lot of extra links okay so if we remove node or we will move uh yeah we want to remove node right why did i do this way actually oh because we want to remove the thing here so actually we don't use the pairing at all um so we are both child we got love okay we need to parent to the node uh which i guess we have so that's okay i don't know why um so then the parent to the node and we remove the node uh okay so if we have both child then to note that left that right is not is none then we do this thing um we want to set so we have a node we go left and that red is none then we want to move node.left to node so that means that node.left to node so that means that node.left to node so that means that parent if pound is none root dot wood is equal to we do this old thing i think which we did would as you go to um node.left um node.left um node.left and then root that right is equal to over right and then basically just have to go through this section again uh turn that left is you go to node then parent.left is equal to node.left node.left node.left the phone.write you want to know the phone.write you want to know the phone.write you want to know parent.right as you go to note.love i think uh now i'm getting a little bit confused because i've already at this point spend half an hour on this problem so it's easier to be confused that way uh current is you go to node.love current is you go to node.love current is you go to node.love okay so this is still wrong because it removes an extra four for some reason what is this input again um we want to remove three so we put the two here which is fine but then oh yeah okay so we now need node.left um compound.left that right is you go to node.right yeah so that looks better is it good enough let's try again i have a lot of wrong answers for this forum already so why not another one oh man uh and this is just going to be a little bit a lot more annoying to fix uh yeah okay i don't even know where 22 oh it's this one's 22 so i don't know hmm that's just a lot of pointering uh and a lot of keeping track of parents and stuff i think that's my issue here uh but it's still another so the thing i would do with these things is try to figure out um something that makes it easier to visualize and that may be a smaller number right in this case we went from here this would be good if you don't show the data is too large to this display thing because then i at least i think it just sticks to 21 to 22. uh that's what i try to do so i don't know why this is wrong i mean let's take a look on at this thing the struggle is real sometimes uh i mean everyone looks okay so what is the 20 is here hmm so i think i'm for some reason no i mean i think i just this looks can i can't tell what these numbers are so it's a little bit sad um that's the problem these forms but it just is i probably just have a silly mistake somewhere all right is it this part in this logic maybe the problem is that i don't even know like if i had print something out like i don't even know if that's the right answer um yeah because this node.left has yeah because this node.left has yeah because this node.left has no right so this is basically okay does that still give me the same answer it should really but oops i feel like i'm not learning anything of this one that's the main issue to be honest uh so yeah it gives me the same answer so that means it's still going to be the wrong answer um why is this wrong and also i just need a visualization i don't actually even know why this is as well like if actually if this is okay except for the data too large to be the spray thing if i just remove that then that would actually be great like that i could actually see like enough of it like the only thing that's not showing is the data is too large to be displayed um it seems like their algorithm just takes the larger number uh the same thing except for going to the other way so but it seems like i don't know why that i got rid of i think the thing that i don't understand wide maybe is that i get rid of 20. so there might be some issue with that um maybe 20 is one of these numbers it's hard to tell because they don't show you so i do get rid of an extra number for some reason next to 16 and 18. where is 6918 i guess it just doesn't yeah sure because it's maybe i'm just i don't know so basically this is the input i need a separate tree visualizer but i could get rid of an extra cell or an extra thing uh and the number i'm trying to get rid of is just 22. right and 22 is 22 here i replace their 21 they replace their 23. uh it's hard to tell what how to express this maybe i shouldn't brag about how good i am and probably uh in implementation right before that but i just want to know what the parent of the 20 is so yeah maybe i'll just write something to debug it a little bit quicker um okay so now we can maybe figure out from this uh this recursive structure uh thanks for i don't know if you're still here but if you are i don't know why uh thanks for kind of joining me on this but uh yeah so this is the so 20 is the left of 21 okay so when we remove 22 somehow we just lost the left of the 20. okay oh hmm is this right maybe like maybe this part is wrong pound is not under cut i still have the 20 here no yeah still not here um this logic is a little bit long because we want to remove node right so no doubt right parent.left we move up the left uh parent.left we move up the left uh parent.left we move up the left uh and then is it just this did i mess it up now the parent points to the notes we want to remove the note right so the parent node used to point at this and it now points at that and then now this thing which is the new i love uh that right goes to the old note.right note.right note.right yeah unless i don't know i don't think this changes though that's why i don't know let's just do it try it for a second and i end up spending way too much time on this but i thought it would be easy but i was well all right so the 20 is still gone so that's not it but where did the 21 go i mean we moved to or we hmm all right let's also print the root before and after uh this visualization seems to be very better than whatever the alternative so um okay but yeah uh if you enjoyed this debugging let me know hit leave some comments i know that this is uh pretty not a video that people would run into but huh so 2120 and then after that 21 the left is 19. huh so i go left and i go i keep on going away oh this case is tricky that i thought so basically maybe another visualization is something like hmm that's a subtle mystery um i mean it's not that solo i just maybe didn't think it for uh but the 21 has 20 because 21 is the largest number that's more than 22. but then now we so the thing that changed is actually i was wrong it's not in this code uh it was in this code but because of that i removed the original node all right wow that's a lot of edge cases okay fine um in this case now parent dot let's see but now we want to replace that so then that means that now we shift one so that means that this and the parent that right as you go to current.left something like that not just two well we have to set it to um i don't know this is right let's see 21 19 but is there a 20 okay 20 is still there okay this is right though no that's only one way to find out i mean maybe not maybe they're multiple ways but i am a little bit tired and lazy so let's find out this way okay cool uh so this was a 40 something minutes video i think um the short answer is this is silly uh i don't know let me think so this is ofh uh time uh and maybe space because i did it recursively you could do it in a way such that's not recursive and then it'll be uh constant space maybe um but what lessons can i learn from this um one is this is why i avoid these kind of three things and you leave things like this to the library but and a lot of you know balanced binary search trees this isn't even balanced but um i think it's just thinking through all the different cases and this just had so many cases uh maybe on a second pass i could clean up the code a little bit this is about 80 lines of code um i think if i could do it again maybe i would i don't know have better things to handle the parents i think that would be a little bit cleaner but overall just a really annoying problem really messy prom uh let me know what you think again it just took 45 minutes this is my longest prom uh for this month i think uh maybe i looked at it and i was like oh this is going to be easy but then quickly i was both right conceptually but also just wrong and a lot of implementation wise uh let me know how long did you take this off this farm and let me know and i'll see you guys next month bye
Delete Node in a BST
delete-node-in-a-bst
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return _the **root node reference** (possibly updated) of the BST_. Basically, the deletion can be divided into two stages: 1. Search for a node to remove. 2. If the node is found, delete the node. **Example 1:** **Input:** root = \[5,3,6,2,4,null,7\], key = 3 **Output:** \[5,4,6,2,null,null,7\] **Explanation:** Given key to delete is 3. So we find the node with value 3 and delete it. One valid answer is \[5,4,6,2,null,null,7\], shown in the above BST. Please notice that another valid answer is \[5,2,6,null,4,null,7\] and it's also accepted. **Example 2:** **Input:** root = \[5,3,6,2,4,null,7\], key = 0 **Output:** \[5,3,6,2,4,null,7\] **Explanation:** The tree does not contain a node with value = 0. **Example 3:** **Input:** root = \[\], key = 0 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * Each node has a **unique** value. * `root` is a valid binary search tree. * `-105 <= key <= 105` **Follow up:** Could you solve it with time complexity `O(height of tree)`?
null
Tree,Binary Search Tree,Binary Tree
Medium
791
1,738
hi everyone it's albert today let's solve the weekly contest median question find k's largest x or coordinate value and before we start don't forget to subscribe to my channel i'll be constantly solving good and classic clinical questions with clear explanation animation and visualization now let's look at a question the question statement so we're given a 2d matrix of size m times n and it's consisting of non-negative and it's consisting of non-negative and it's consisting of non-negative integers and we're also given an integer k and here we define the value of coordinate a b of the matrix is the xor of all matrix i j where i is bigger than 0 and smaller than a and j is larger than 0 and smaller than b and we are asked to find the k largest value of all coordinates of matrix and in the four given example they all have the same input matrix which is 5 2 1 6 first largest coordinate value is seven and second largest is five third is four and fourth largest is zero and a data constraint for this question the size of the input matrix will only go up to 1000 and to solve this question the first thing we have to know is a key characteristics of the xor operator which is a x or b x or a will be equal to b and with this characteristics we can use dynamic program to solve this question and a dp transition equation is dprc row n column which is the coordinate value of the matrix would be equal to dp r minus 1c xor dpr c minus 1 xor dp r minus 1 c minus 1 and then finally xor the cell value of the matrix rc so we can generate the xor coordinate value matrix and then we append each sales value to a rest array and finally we will sort the rest array and get the k largest value and the time complexity of this approach will be big of m times n times log m times n because we need to sort the rest array at the end and since the data size of the matrix will only go up to 1000 so this approach will work just fine now let's look at the code is pretty short and concise so basically we just iterate through every row and column in matrix and then implement the dp transition equation and here we can just modify the input matrix directly and then append the dp value to the rest array and at the end we'll sort the rest array and then return the kth largest value now let's see the code in action okay and here is the input matrix 5216 and they are the same for all examples and then we will start to calculate the coordinate value for each cell based on the dp transition equation here so the first cell 5 will still remains 5 and then we will append 5 to the rest array the second cell the coordinate value will be 5 x or 2 which is 7 and we will append 7 to the rest array the third cell the coordinate value would be five x or one which is four and then again append four to rest and the last cell it will be six x or four x or seven and then x or five which is zero and then append zero to rest and at the end we will sort rest and then the first largest value in rest is seven which is the output for example one and the second third and fourth largest value in rest is 4 0 which are the output for other examples and this will conclude the algorithm finally let's review so the key intuition to solve this question is the key characteristics of the x or operator which is a x or b x or a will become b and based on this we can generate the dp transition equation here so we can generate the xor coordinate value matrix and then we append each sales value to a rest array and at the end we can sort the rest array and get the k largest value and the time complexity of this approach is big o of m n log mn because the size of the res array is m times n and we have to perform sorting on it and the space complexity will be big of m times n and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one
Find Kth Largest XOR Coordinate Value
maximal-network-rank
You are given a 2D `matrix` of size `m x n`, consisting of non-negative integers. You are also given an integer `k`. The **value** of coordinate `(a, b)` of the matrix is the XOR of all `matrix[i][j]` where `0 <= i <= a < m` and `0 <= j <= b < n` **(0-indexed)**. Find the `kth` largest value **(1-indexed)** of all the coordinates of `matrix`. **Example 1:** **Input:** matrix = \[\[5,2\],\[1,6\]\], k = 1 **Output:** 7 **Explanation:** The value of coordinate (0,1) is 5 XOR 2 = 7, which is the largest value. **Example 2:** **Input:** matrix = \[\[5,2\],\[1,6\]\], k = 2 **Output:** 5 **Explanation:** The value of coordinate (0,0) is 5 = 5, which is the 2nd largest value. **Example 3:** **Input:** matrix = \[\[5,2\],\[1,6\]\], k = 3 **Output:** 4 **Explanation:** The value of coordinate (1,0) is 5 XOR 1 = 4, which is the 3rd largest value. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 1000` * `0 <= matrix[i][j] <= 106` * `1 <= k <= m * n`
Try every pair of different cities and calculate its network rank. The network rank of two vertices is almost the sum of their degrees. How can you efficiently check if there is a road connecting two different cities?
Graph
Medium
null
1,790
Hello friends welcome to my channel let's have a look at problem 1790 check if one string swap can make strings equal this problem is essentially the same as problem 859 the body strength problems problem so here we'll first read through the problem statement to digest the problem requirement and then we compare with problem 859 and share the procedure and the code first let's look at the problem statement so we are given two strings as one and S2 of equal length so notice that in this problem it's assumed that S1 and S2 have the same length so this is the difference from a problem 859 so a string swap is an operation where we choose two indices in a string so not necessarily different right so and then uh slap the characters at this indices so if the indices are the same so it corresponds to nothing actually so very good we are required to return true if it's possible to make both strings equal by performing at most by string swap are exactly one of the strings so otherwise we return false so this uh our exact events of the strings actually carry got one of the two strings fixed and as the goal or reference so here are three examples so in example one so we can switch B and click right in X-Men or in S2 right so we return in X-Men or in S2 right so we return in X-Men or in S2 right so we return true so similarly in example two so we can check the different characters corresponding to the indices so we turn false so in the third example so the two strings are identical so in this case based on the requirements of the problem or assumptions we need to return true so before we do the analysis let's also look at the constraints so first S1 and S2 have length in between 1 and 100 so this 100 defines the problem size so which is a small number so the second constraint tells us again the two strings have the same length the third one is about the characters in the two strings so which are lowercase English letters so with that side we are ready to do the analysis so um com let's first compare with problem 859 so in this problem here so first it's given that the two strings share the same lengths the secondly it's allowed to not performing any snap right so we can perform one last step in the Euro since or we can just do not perform no slabs so as such we just need to slightly adjust the procedure in problem 859 in such a sense our problem 859 is slightly complex than this problem so the procedure is the following so first we find the indices where S1 and S2 are and have different characters and then we call this number can't so actually in between we can do early stopping right by checking if count is great than two right so in second step if count is greater than 2 or count equals one so we just need to return false and the if conch equals zero so in this problem we just need to return true directly so this is the difference of this problem in 159 so if cons equals two so then we just need to check slap so we assume the two indices are ing so we need to return if this condition as when I equals s2d and S1 J equals s2i so this is the checks Maps so with that said we are ready to do the coding um first let's initialize a cont variable that is zero right so and also I'm going to record the two different indices if there are so we get a x is a set because we are paying attention to the indices and also we want to compare the two characters in the same position of S1 and S2 so we are going to use enumerate function and the zip function so for I character lab character 2 in and enumerate a zip S1 S2 red so if character one does not equal to character 2 so in this case we are going to increment the count by one and then we add this uh index to the set aux so let's do our an early stopping so if conch is greater than two so in this case we just need to return false directly in and then after we exit this follow if nothing has returned so we check the three cases because uh in this after this for Loop there are three possibilities count equals zero or equals one or equals two so let's see if count equals zero right so we just need to return true in this problem and then if um count equals one so we just return false and the other case actually which can use a house or just read like this making it a list so if content equals two but then we can get the two indices so aux pop so we can use the pop twice and then we just need to return the check slab result as one I equals S2 from G and S1 J equals S2 I so with that done so I guess that's it for the coding part so now let's do a check for the test cases yeah this part is back now let's uh let's use a identical one to check right so this we should return uh two yeah so let's return true so now let's uh check for the generic case yeah it passes all the generic cases so I guess that's about it for this problem and this video so this problem itself is not complex so thank you
Check if One String Swap Can Make Strings Equal
lowest-common-ancestor-of-a-binary-tree-iii
You are given two strings `s1` and `s2` of equal length. A **string swap** is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices. Return `true` _if it is possible to make both strings equal by performing **at most one string swap** on **exactly one** of the strings._ Otherwise, return `false`. **Example 1:** **Input:** s1 = "bank ", s2 = "kanb " **Output:** true **Explanation:** For example, swap the first character with the last character of s2 to make "bank ". **Example 2:** **Input:** s1 = "attack ", s2 = "defend " **Output:** false **Explanation:** It is impossible to make them equal with one string swap. **Example 3:** **Input:** s1 = "kelb ", s2 = "kelb " **Output:** true **Explanation:** The two strings are already equal, so no string swap operation is required. **Constraints:** * `1 <= s1.length, s2.length <= 100` * `s1.length == s2.length` * `s1` and `s2` consist of only lowercase English letters.
Store the path from p to the root. Traverse the path from q to the root, the first common point of the two paths is the LCA.
Hash Table,Tree,Binary Tree
Medium
235,236,1780,1816
1,044
hey everybody this is larry this is day 30th of the leeco daddy challenge hit the like button to subscribe and join me on discord let me know what you think about today's prom longest duplicate substring okay so that sounds kind of hard already um this is one of those problems that feels like it uh it's easy to state which also means that it's super hard so it's any string that could occur two times or more hmm well so the first thing that i would look for is n and n is three times ten to the fourth they're n square roughly speaking or you want to go and you know n times and we'll be speaking n squared over two number of sub strings and therefore it's gonna be two uh too big right that's like nine times ten to what a for or whatever it is so that's even over two that's too big so we cannot do it proof first because one thing that you might think about is um yeah one thing that you may think about is is just creating um every string or every sub string and then um and then put in a hash table or counting and something like that and get the longest version right so that's not going to be good um uh yeah so also a disclaimer this is friday night for me anyway uh maybe saturday morning depending where you are um i am solving this live and this is a hard problem so it might be really slow it may take a while and these problems and this one i don't have an immediate answer for clearly um so it may be very slow as i'm discovering with you at home so definitely um yeah fast forward if it's a little bit slow and all that stuff okay hey yeah so this is future larry cutting in uh well i'm not that much from the future it's still passed by the time you watch this but uh but yeah so actually i end up solving this with suffix away i'm gonna go with the exploration explanation really quick um because it's really long but feel free to kind of keep going and feel free to skip ahead as much as you like and kind of see how i thought for the process um but yeah so the way that i did it with suffix array i actually believe that i have another video that i solved this last year with binary search and robin carp um definitely check that out i'll put a link in the comments or something like that um but yeah check that out i think that answer is actually to be honest much easier and i don't know why i took it this long wait but that said i am familiar with this one so you can watch me explain it later um live as i kind of go through the thought process if you find that interesting but for now to make it a little bit shorter or at least the hot pot shorter i am going to go over the suffix array solution real really quick um the idea behind the suffix uh let me go over really quick is that you know we're going to use a suffix tree but we're going to store it in a suffix array um and i'm not really going to go over suffix tree and suffix array is one of those things that are kind of to be frank if we are to explain it from beginning to end and explanations and moves and stuff like that we'll probably take like two or three classes in a university setting and that means like you know three hours or so and i'm okay look i'm just a little bit lazy for that so i'm gonna describe how i'm gonna use it right so the short answer is that um and i'm going to explain it in pieces and maybe some parts are hand wavy definitely feel free to ask questions but yeah but basically the thing that i come up with um during the solving is that okay let's say you have a red banana um i thought that it could be a suffix tree and the suffix um it's just okay daddy structure aside you just basically look at all the possible suffix of the um of the word right uh and then now we sort by them right um and that's what i did here um so we take this an array of suffix uh of the original string we did do a sorting um and then now and i was just thinking about this foo and now if you are if you see this you'll notice that or you know and this is one of those things that if um if you do a lot of competitive programming it's one of those probabilities that you just kind of see enough that um that you just know right or you have proved in the past um so to be honest i don't i find it's one of those things that because of that i don't even know necessarily off my head the cleanest way to explain that um but basically um if you compare adjacent indexes uh of this sorted array um the longest duplicate substring will be uh part of this right um so yeah the end a lot of these proof are like proof by contradiction of okay let's suppose some string that is longer lives within a bit of time these and you have to prove by contradiction that doesn't exist that kind of thing right um so there are two problems right one is that um notice that this would actually take n square space right because this takes one plus two plus three plus four dot and you know that is a very um uh you know i mean most people hopefully you're familiar with that's n squared because that just sums to n squared right it's n squared over 2 roughly but o of n squared um so the thing to notice here is that um we can we only need to store the indexes right because everything is going to be because we there's a lot of redundant information because if you really think about it if you think about uh let's represent each uh string here as the original character uh original word then you get like five you get three four five you get one two three four five you get uh zero one two three four five six uh five maybe no sex but you get the point right dot um so this one like if i say it to you like this i think it's very obvious um that you know if you start the index one of course the next child this will be index two and then the next character after that is gonna be an index three and so forth right obvious um so then in that case and it goes all and all the numbers end with all the string ends of five because this is the entire suffix right okay so now that you get that then you realize that then all you have to do is just you know represent each uh string by the first index of the first character right or the index of the first character and that's basically what i have here i drew this out um and then you could also just see that i copy and paste more but yeah and then now if you're storing it in a way you can see that this is gonna be linear space right um i also said that um the way that we're going to do it here is going to be using an n log n algorithm uh and we'll explain the and not get where n log n comes from but know that there is an of and construction algorithm called uh i hope i'm saying it roughly correctly but aquaman uh government uh algorithm um so that algorithm do allow you to get in an off and construction and then you could get this and up and space um the next question that so yeah so now that we have this right the next problem that i faced and you can actually i did troops i did solve this uh in real time so i'm proud of that for that reason um but the thing to notice is that you know if we look at each adjacent comparison right and there's going to be n comparisons or m minus one comparisons to compare n pairs or n minus one pair sorry um and each one is let's say of length roughly n then that's gonna be n squared times still right so that's gonna be tricky if it's still gonna be n squared times still too slow because we look at n and n is slow right or n is big so n squared is slow so then it took me a little bit of time to thinking about it um but then one thing i did notice is that um like we said earlier right yeah oops uh yeah like we said earlier given this thing when we compare adjacent elements what does this mean uh let's actually and for this one let's write it out real quick um so this one what does this mean right that means that let's say we compare uh the ana and uh let's say we can pay compare anna and ananda uh but that means that if we remove the first character what does that mean right well we uh or we after we compare the first character now we have na and nana um which is good but it also you know uh why did i do four two this is so weird i think i was just looking at this suffix array or something i don't know and there's no six but yeah but the key thing to notice is that now this is just 4 5 and 2 3 4 which is this right um so then now because this is not and na uh and now we compare one character and now this is just a and a right which is just of course um here and this right so if you are someone who's been doing a lot of dynamic programming you probably recognize this um and maybe there are i think there are different ways of writing this but the way that i think about it the way that i visualize it is by dynamic programming and here you can see that okay this is just literally okay with the same character we go to the next one um and then so forth and here by here and if we do let's say we do this comparison between these two words um that means that this is done and this is done right so we don't have to do them in the future um so that's basically the idea pretty much it dynamic programming after that um yeah and then so i'm gonna show you the code now and go over the code um we'll prove why this is in a second but yeah so now we like we said we okay n is equal to the length of s we look at all the indexes from zero to n minus one inclusive and then we sort them by using the prefix oh sorry the suffix as the string right um i actually worried a little bit about the size of the string because i don't know how much how many accelerate strings that this compiles um i hope that it is just you know iterators but i don't know um and in here it's just variables to keep track of things um yeah and then we let's skip ahead to line 48 and this is just very basic things of okay we want to compare the suffix of this index and the suffix of this right um so that's basically the idea behind this um so the length is you go to just compare this thing um and if it is better than it then we just start the index at one of them it doesn't matter which one because the length i mean they literally have the same uh substring right so this is the length and this is the index and that's basically your answer right if it is none then we just have no answer otherwise we return yeah we return that substring of starting at that point and of this length right okay hope this makes sense this is linear well this is linear number of loops um and then this is the dp part this is also straightforward if you have done dp i'm not going to go over dp that much in this problem because it's already a long video to be frank and also this is a really hard problem i cannot emphasize this enough this is a really hard problem uh you don't need to know it especially this implementation um so this is more for your fancies so yeah so i think i you know in a lot of my other videos i do explain and spend more time in a dynamic portion port so this time i'm not going to um the tricky so let's go over okay for i and j what happens right well if they're going out of bounds then that just returns zero because there's no more normal numbers to match otherwise if they are not decoded there's also no more uh no more indexes to match no more characters to match if they match then we get one character plus the suffix right like we keep on going so yeah um so the tricky thing is actually recognizing that this actually for a suffix array only of n possible inputs you know i can go from 0 to n and j can go from 0 to n a naive analysis would say that this is n square however note that in this case you know this character 3 right only have let's say 3 is one of the inputs to this go function right well it only has two possible inputs for j right j can either be one because we're comparing the three of the one or we're comparing the three of the five um either yeah so that means that for every i the only two possible alternative inputs uh to j i mean and then some maybe you could time step by two if you won because maybe they're in different order or something like that like three and five and three here i didn't really make the distinction so maybe it doubles but by the way this is going to be all n right so this is actually only all n possible inputs then the analysis becomes straightforward because this is all one time and o of one space for each possible input um this is going to be of n time and over and space and therefore it gets dominated by the sorting right here which is of n log n time and also of n space um like i said you can actually reduce this to or can be reduced to of n space using an outrageous implementation um so yeah um that's pretty much all i have um like i said if you want to know about the binary search answer um i'll put a link below to my previous video um you can watch me solve this live and watch me kind of figure out each piece and figuring how to get each piece step by step like i said this problem is really hard if you want to do it for fun and you know this is a weekend do that but yeah um that's pretty much all i have um yeah i'm you can watch me solve it during the daily thing live next um do you think that so for these kind of problems i think one thing that i would try to do is just try to figure out if i know or try to fill out some answers and properties that we can uh take advantage of um i don't know that i have a great and so on this one off my head i think one thing that can happen though um i'm trying to think about the space requirement for it i think i'm so what so i'm just playing around with ideas in my head one thing i notice is that for a duplicate substring the longest two pickups the longest duplicate substring um there are multiple candidates in the beginning right or maybe another way of saying it is that the longest duplicate substring consists of the longest duplicate substring length minus one or something right basically for example um if the longest duplicate substring is length uh 20 then there also is a duplicate substring of length 19 right so okay so what does that mean um that means that in theory you can maybe build it out from a candidate set um is that in theory a good idea um don't know uh let also see oh they might overlap i just want to check to see if they can overlap um yeah and then the question is and then my next thought was okay we built a try how much space would it take right um also this may just be um i'm also trying to think whether this is a suffix tree problem uh to be honest i haven't used suffix tree in a long time it's something i don't use enough um to kind of have an idea is that but i'm also playing around with either prefix tree or suffix tree though in this case i guess it doesn't you know if you need one or the other you can just reverse the string so i think because it's symmetric in that way but let's see do i need a prefix tree so the prefix tree you would um put in the banana and then you would go maybe stop a and then try again and then 9 and so forth but that l that algorithm is going to be n squared right because it's going to be of length n and then n minus 1 dot and you sum up the series and it's going to be n squared roughly um so that's still not gonna be good but a suffix tree can we build a suffix tree um so there is there's a couple of uh suffix tree algorithms of course um that will do linear time and i think that we can do some sort of sorting but i'm trying to think um i mean so one is i think you can solve this using suffix tree um which is not to be confused of a prefix tree or um a try um a suffix tree is actually a very complicated algorithm that i implemented optimally maybe once in my life maybe twice maybe the second time i even copy and paste to be honest for my first time but there is an of n construction um there are other ways of con or well in technically there's a suffix i believe um but there is a easier uh yeah there's a easier but more complex answer and let's think about um yeah what that means right um because the old van can you construct i don't know i think it's named after uh i could search for it but i don't even know if that's right enterprise but it's ocum suffix it's like oh okay oh going something like that i don't know if i'm spelling this way let me just google it before because i don't want to be disrespectful but it is it's been a while um so play around with w1 but i do have a different way of solving it which to be frank i don't know if it's going to be fast enough it should be fast enough but i'm not quite sure but basically you have um so okay so the first thing that i would say and one way to solve it is that okay you take you look at this um string and then you know what is the suffix uh what are all the possible suffix strings right so there's this uh oops this you know this right um and the suffix of um suffix tree or suffix away will kind of take advantage of this and yeah i think one thing to kind of notice though is that okay um if we sort this suffix these suffix uh characters you will get i don't know roughly speaking uh was it banana this is off my head this is me doing it manually so maybe i'm missing one or two but you get the idea right so you take these suffixes and then you sort them to get this right and then what do you notice here what you will notice is that on adjacent the longest duplicate substring will have to be on adjacent indexes um but that said that was still that's still very potentially um algorithmically expensive right because the sorting we can actually do pretty quickly um but here looking at adjacent it can be for example if you have just a lot of ace um you know so forth right um i mean there are some shortcuts in terms of uh things we can do in terms of like heuristics but i don't know if it's going to be fast enough to be honest um but you can see that you know and this comparison will eventually be um because now comparing the first one in the second one takes one coming the second the third one takes two and so forth so this is also going to be n squared in comparison um not to mention that this is also n square space though there's a way around that n square space which is the idea behind the suffix array even if you don't use the o of n construction you could still have a suffix array that's an over and space um okay let's say we have a suffix array can we do it can we solve this in earth or time um maybe i don't remember suffix i raised as much as i think i do it really it doesn't come up that often um hmm let me right uh so we can definitely create the suffix away but i don't know how to use the suffix array to get the longest duplicate substring off my head um so i think uh or yeah let me think about it for a second it's been a long time i think this is it but i'm trying to think about how to do it in um in linear time um um can we now construct the tree or the oh i see huh so basically if we do it naively then i um we do it naively then that's not the case but we can do i don't remember my suffix tree enough to be honest uh or suffix a way for that matter i suppose um but hmm let me think about it for a second uh i think this is where to be honest where i would uh have to use a pen and paper that as i'm struggling a little bit to figure out uh the visualization um but okay let's say we have the suffix tree or well okay let we add the suffix away how do we go down to it in a good way um yeah i mean i think so this will work but um this is me trying to remember what i learned from like ten plus years ago from suffix tree so okay so now that we created a suffix away we're trying to find the deepest node with more than one child i guess because basically i have to find a piece of paper but yeah but what this is saying is that okay so um yeah because um because here uh if we construct a tree we have a and then we have a an a and an a n a and in this a we have two nodes um but hmm how's this open uh maybe the suffix away isn't the way to do it um okay so basically if we have a suffix array then how do i want to do it um i think i okay i think i get it now um i think one this is kind of hard because i'm uh kind of reconstruct or reproving a lot of things in my head from scratch um like i said a lot of these things i've learned a long time ago and even then to be honest to be frank i don't know that i learned it um very well to be um and i think the yeah i think the thing that i would think about is that okay let's say we're checking out um this maybe uh maybe we'll add a couple more um so let's say we're checking this out right um actually um so the thing that i was worried about was that we're doing n squared we keep so we know that after we sort the suffixes uh we know that we saw the suffixes the answer would be by comparing two adjacent um uh to get con two adjacent suffixes but then the thing that i was saying is that because each one can take off n times to compare and there are n comparisons to do that'll be n squared but one thing that we can use and maybe i don't know how to think about it or i don't know what the academic way of thinking about it is but the way that i'm thinking about it is that it's kind of like dynamic programming in that okay let's say we compared to a's right and then now that means that we can compare the n and then a all together right um yeah um and of course this worked out by comparison these it's just the same as doing this here right these two lines um so here for example what is this index so let's just let me give a second label so let's say this is um so that means that for example here this is the index three and this is the index one right and then after that of course it's two and this is four and this is going to be uh four and two right so in that way the way that i'm thinking about it is kind of like um so yeah so going forward we can just store the answers here um kind of like memorization and dynamic programming there probably is a queen now writing it but i'm just going to do it that way you know that's a little bit messy but i think we have enough to start playing around um yeah uh i think yeah i think that's it so suffix array looking at adjacent elements and that i'm actually pretty happy that i figure out this algorithm because this is actually i would all say um i mean you're a little bit i mean you're uh way too long in but this is a very hard problem it requires an algorithm that maybe isn't very hard as a black box but very hard to get it optimally in uh in implementation especially at any given time but i'm going to try to do it live as you know i am so hopefully this is um kind of interesting um but this is very hard i don't expect i don't even like i don't expect anyone to maybe that's not true anymore i don't know because everyone's gotten smarter over the years but i wouldn't expect this to be on an interview for sure i do not expect this to make an interview i don't even think most people i know would get this um in a reasonable amount of time at least in a not and square time so maybe yeah n square i think a lot of people could get it and again which is my algorithm i don't know that many people could get it and oh and i don't think anyone could get it i mean within an interview timing right like i know how to do an open per se i don't know if i can implement it to be frank um so yeah okay so the first thing uh let's step back a little bit then um uh yeah let's step back a little bit let me say that uh okay so how do you know we said before that we're talking about of n space um or we want of n squared space because of n square space is not good enough and the way that we do it is just by instead of showing the entire suffixes um and then sort them afterwards all we have to do is actually um because these are all suffixes right so that means that the entire substring appears multiple time or the suffix of the substring so we all what uniquely identified this string is just the first um the first uh well the first in the index of the first character right so in this case is this well and this is all more obvious here because it's not sorted but this is zero one two three four five right that's the index of the first character and then after we sort it this is going to be five this is going to be three this is going to be one this is going to be zero this is going to be four and this is going to be two right so yeah so now our way would look like five three one four two after sorting and that's basically the idea really right um yeah uh so then now obviously if you look at this is gonna be linear time because five represents the string from the fifth character three represents the string from a the third character and so forth uh so yeah so i think we're in good place here let's get started um we are not doing this is really hard for models to do in reasonable time uh so you yeah if you have done it uh or like you know you have a pre-implemented library or something pre-implemented library or something pre-implemented library or something like that maybe that's good but yeah um cool uh okay let me think about how to implement this so okay so yeah so we have n is going to think of s we want to sort um yeah we will create uh indexes as you go to um you know a list of uh range of n and then now we want to sort indexes we want to sort by wonder how this works actually um i don't know if this is going to be good enough to be honest um but we'll see this if this is good enough because i actually don't know the um by t uh oops this is not right this is uh distribute this but i actually wonder if this creates too much um too much thingies um i might need to do a comparator maybe i don't know maybe this is okay though we'll see because i don't know how much um because i think this does construct uh thingies let me see if i can convert this into an iterator um string generator doesn't seem like i actually don't know if this is a clean way of doing it in python i'm not gonna lie because i don't know if it can because if it keeps on uh creating strings as it's sorting it may actually be very not good right um let me actually just run it real quick i actually didn't count this so maybe that was a little bit bad um oh whoops so in terms of time it should be okay because we only do log n comparisons but i actually don't know if it's going to be fast enough uh alright i don't know if it's gonna construct too many um what's going on you can go to the bottom easily because there's too many okay uh actually i guess what we can also do is just do uh s is equal to a times uh three times ten times three times ten to the fourth i actually don't know if we construct a lot of like accelerary strings because if it does it may actually be messy whoops like what we're looking for is maybe our memory type things but it seems like it's okay so we won't worry about it yet not actually sure that this is okay but yeah so then now we can maybe print indexes and in theory it should actually be just in increasing order huh okay maybe i was wrong that one is decreasing order oh yeah no sorry i meant decreasing order because it starts with a and then a and so forth and that's going to be decreasing okay so yeah so this is it right this is now suffix array is here right um this is now suffix array so then now we want to look at for each for and we're going to implement it in a not so efficient way to be honest um there are different ways of doing it but i'm going to do it on the stack we might actually run into issues of stack things but you know we'll play around we'll learn um but yeah so now we go for i is in range let's start with one and then now we want to compare indexes of uh we want to compare um i mean yeah okay fine is that the way we're saying it and indexes of i minus one for the longest thing so then now we just um okay so we have a best is equal to i would say best is equal to zero um and then also uh yeah best as you can see well um so i'm just thinking about a different thing for a second but best is equal to zero so what is that um and then just press string uh sorry i was thinking ahead of about something else so i wasn't actually thinking about this like this part is usually i'm just trying to think about whether i'm correct about this memorization but yeah now we can go best is equal to max and this is actually becomes a standard not standard but easier to understand for me uh memorization of okay we'll just look at um indexes of i and indexes of i minus one right um and then this is our memorized thing um and this is a very hard problem so i'm going to skip the dynamic programming explanation to be honest um because i want to focus on the dynamic programming part because i think this part is okay and if you do struggle dynamic programming um and you know and a lot of people do and i am as well from time to time um i do explain them in more detail in other videos especially other daily videos just not this one because this one i want to focus on the core part of this problem which i don't think is it's a dynamic programming anyway or like you can do this without this construction um but that's the way that i'm gonna do it with dynamic programming so i'm gonna skip the dynamic program part so if you need help with dp please refer to some of my other uh daily dp problems because i do go over them in detail i hope you agree with that anyway so yeah so now we have two indexes right and then basically if um if s sub i is not equal to s of j um if s sub i is not equal to s of j then huh sorry i'm just thinking about something else this is quite similar but i'm thinking if i can prove the number of inputs should be o of n um but i'm just trying to think where i can definitively prove it uh for you um i think that there's only two okay let me go for it in a second then um otherwise if they're equal then we do um we if the equation return one plus go of i plus one j plus one we also need to um check um okay fine i was going to say whether we should um check them uh or like we should maybe reinforce like eyes less than j or something like that but i don't think it matters that much like at worst we do double the work or something it's fine but yeah okay it'll be nice if uh if we actually return the string but we do it this way because i was silly i forgot about it um yeah so l is equal to this thing and then if uh best is less than l best is uh if the multiple answers or any okay yeah then it doesn't matter best is equal to l and best s is equal to um i guess the shorter of the two strings um so uh so yeah so if i is greater than j oops if i is greater than j that means i is later so then we want it from i um okay let's actually do we shouldn't do the string we'll just have the index um yeah okay let's have the index yeah okay that's fine um so they're now best what i call fss so then here we take the smaller um yeah okay so this is best start say so then best thought is um i guess it doesn't matter because it's just start plus best anyway right so i think that's okay so actually yeah i guess doesn't matter so we can take item one and it does it should not matter because we don't go overboard and then here then we now go from uh s starting from best start to best start plus best maybe i'm off by one i'm always off by one of these things because i never remember how to do python sub strings um okay well this is off by more than one so that's a little bit unfortunate but uh let's actually oh wow i didn't remove this thing uh don't that's not right because that should give me like a long string right huh give me a second to think about it because basically if this is the right end i mean it doesn't uh we could add that back in later but that means that something's wrong because that should give me a really long answer um okay also i did actually remember this but i well i was thinking about it when i was typing it but i forgot about it um because you know that just has nothing but n-a-n-n-a-n is a valid answer so i but n-a-n-n-a-n is a valid answer so i but n-a-n-n-a-n is a valid answer so i think that's good uh wait is that true well maybe i am just off by one oh i'm doing i but it should be index c survive um okay whoops because that's the index that you're actually starting okay so that's good let's uh bring let's remove this print statement and also bring back uh this thing for half a second it should give me something like this minus one right so it give me like uh well okay maybe i should have kept it in the print statement just so that i can verify a little bit it should be this length minus one if they're all the same characters um so i'm just going to run that real quick um and of course if you're at home you know maybe it's actually protest and stuff like this so that looks good um yeah oh yeah the best starts from zero and the length is okay um okay let's give it a one code uh that looks good um and it seems to be okay for the biggest strain let's give it some it might still have an issue oh look i did huh i did it three times before uh okay wow much faster this time uh cool let me take a quick look to see what i did last time oh i did uh huh i didn't think that was going to be fast enough but did i do this during the contest don't remember this one but that makes sense but uh okay i mean this is based off the same idea-ish idea-ish idea-ish um let me let's go over that one afterwards uh let's go over the suffix tree uh array thing first so this is gonna be analog again mostly because of this sorting so this is gonna be oh uh n log n and of space we just you know keep track of indexes and this cache so it's going to be of n space but uh i'll have to prove it to you right um so yeah the sorting is going to be linear uh here you can see that this is o or n loop but keep in mind that this gets cached and of course as we said earlier uh in this case um between if the two elements are adjacent if you minus one character in the beginning which is the same character anyway these it will also be adjacent in the future so because of that actually every time you minus one character for example even here your minus one character um oops you would just go to five and three which is here right um so in that sense for every space you will only look at actually um you would only process the character twice once if it was the first string and maybe a second time it was part of the second string so that's basically the um the reason why this is linear um i don't know if that's a good um if that makes sense but um but yeah um yeah uh so that's gonna be linear because for each character we only do the work once and the explanation here is that they're really only um like here uh there are only of n possible inputs um because everything is forced right because you cannot have i mean it may look like there are n square possible inputs but there's actually only line of n possible inputs because you know every time you go to the next character everything just gets plus one right like this is very um yeah and you only kick it off with the same i twice meaning uh because you know i either is the first character or is the second character right because like for example either you're doing a or a so that means that this a will only be in two chords uh so that's why this is linear right um and this is essentially a for loop wrapped in um and you could implement it in another way but i did it with dynamic programming so yeah so this is actually you know this is very deceptive there's only of n possible inputs each one taking over one time uh and also a one space so in total this is going to be o of n time and off and space um yeah and that's pretty much it um this is very like i cannot emphasize this enough this is very hard so i would not um i wouldn't worry about it that much if you don't really get it but do spend some time on it and let me know what you think but this function is linear um so this is actually this is linear as well um and because we don't do anything funky this is also you know just straight up for it so that means that it's going to be dominated by this thing which is of n log n time and off and space um of course like i said before i mean the way that we do this suffix array is actually two lines of code so that's actually like three lines of code or whatever you want to say um you can look up a command's function or augments side um you can actually construct this in of n uh time um but i'm not gonna do that and i'm not even gonna explain it not gonna lie there five good videos out there or maybe there are videos out there and they're good feel free to research on your own so yeah so this is the ofn algorithm um yeah uh and then now let's go over really quickly uh really quickly um the binary search run um i forgot about forgot that we can do this but that's fine um yeah so the binary search one we used um we used uh what's it called robin cop um basically it is what it sounds like we and i'm not gonna dwell on it this much um i think maybe i even have a video on this if not let me know because it seems like it was a like i solved it during the daily problem phase but uh but yeah but because this is um rob and cop and then we just do a binary search on the length so basically the idea is that um like we said we have the same idea of okay if there is an answer of length k there has to be ends of length k minus 1 k minus 2 k minus 3 dot all the way to 0 and 1 right um and if k is not possible then obviously there isn't any longer right so then the idea from that is that we do a binary search we try okay it's k possible if k is possible if mid is possible then that means that oh if mid is possible that means that um you know we can try a bigger number if mid is not possible then we try a smaller number right um and then here we just check whether it's goodbye by robin kopp um and i'm not gonna go with robin cough that much because it is just one of those algorithms um maybe we'll go over in another video but basically you um using robin club you try it off length of a certain length and then you do a sliding window um keeping track in a set or a hash table or whatever and if we see something more than once that means that we know there's an answer of length okay and then um and then yeah and that's it you like this is just a rolling hash on robin cobb and then you just literally um yeah it looks like i did uh double hashing um on is it called double hashing i don't know but i did it with two big mods um because i guess i was running that's probably why i was running into uh wrong answer um if i have to guess it's just basically what's giving me a false positive oh no maybe i just have a typo then uh but yeah maybe the time limited was forced i don't know actually not sure why but that said um yeah so this is robin cobb you try it and then if it's good then you return it if not then you it is false and then now uh yeah and you just keep doing it um and each one of these so every time you start with you know n possible search spaces um and then every time you do it's going to cost you o of n times roughly because it's linear um every time so uh it's going gonna be unlocked and also um yeah i think that's all i have um i think there's a video on this i'm not gonna dwell in that much so if you are interested in this solution you know check it out uh but yeah i'm happy that i solved it this way though now that i know that about the binary search engine maybe i should have done that one to be honest that one is a bit easier uh conceptually um but i'm happy to solve it this way now hopefully maybe you know one of you will find it useful uh let me know what you think uh hit the like button subscribe and join me in discord i'll see you later and to commando health have a great weekend happy halloween huh maybe one day maybe not well clearly i didn't do it today um but one day i'll dr um i guess i gotta do it pretty soon i'll dress up as cotton costume just to kind of celebrate with y'all at home anyway i'll see you later stay good stay healthy take a mental health see you later and have a great weekend have a great halloween weekend and i'll see you later bye
Longest Duplicate Substring
find-common-characters
Given a string `s`, consider all _duplicated substrings_: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap. Return **any** duplicated substring that has the longest possible length. If `s` does not have a duplicated substring, the answer is `" "`. **Example 1:** **Input:** s = "banana" **Output:** "ana" **Example 2:** **Input:** s = "abcd" **Output:** "" **Constraints:** * `2 <= s.length <= 3 * 104` * `s` consists of lowercase English letters.
null
Array,Hash Table,String
Easy
350
1,512
okay so the description is given an array of integers nums a pair i js call good if nums of i equals number j so the values at those corresponding indexes equal each other and i's less than j return the number of good pairs so this is like an easy problem if you just brute force it but um there's a clever solution and i wanted to go over that with you guys after we go over the brute force so the example here is there's four so we have this equals this so that's one this equals this that's two the three equals the three over here and these ones so that is four good pairs and this is six so if we look well first let's brute force this so the brute force is pretty easy um so let's create good pairs equals zero and so the brute force obviously is we're just going to loop through every a possible iteration so we're going to set i here and j here um j is always going to be i plus 1 because we don't want to start them at the same we want to check it after i and then we're just going to loop through so it's going to be o of n squared runtime and i less than known to that length so this is a very easy solution there's a definitely a more clever solution that's faster oh okay so i already messed up so like i said it needs to be i plus one we can't start them at the same place and j greater than and this needs to be um nums.length minus 1 um nums.length minus 1 um nums.length minus 1 i believe because we can't we don't want it to be i can't be the last number because j is going to be the last number so we can't do that and i believe this should work um so if nums of i let's just type it out equals num to j then uh we're going to increment good pairs and return good pairs okay let's see if it worked and it is taking way too long let me refresh the code i'm actually just going to turn off my vpn see if that helps okay let's try it again cool so let's submit it and so now i want to go over the um more clever solution that's a little bit harder to think of um so if we look here if we have four ones there's um six so i'm going to write this out so if we have say four fours the good pairs equals six for just these pairs so how did we get that we got these two this one and then this one and this one so um if you guys know this is the co this is just combinatorics um there's a uh a formula for that so we have combinatorics so it is n minus 1 times n all divided by 2. and i'm going to rewrite that n minus 1 times and divided by 2. so here would be we have 4 so 3 times four so we should put these in their own divided by two we get 12 divided by two equals six so that's um we would just need to basically code this out and account for all the frequencies of the same numbers um so let's do one more sin uh example so it makes sense so um we have three now so n minus one so two times three divided by two equals six divided by two equals three and um so let's go over the let's see it check if this is right we have these two we have this one and this one so that's two and then we have this one and this one so it is right this is the correct formula we just need to um create a the code for it and i'm sorry i actually can't make this bigger because it's the size of my ipad i don't think it lets yeah i can't increase make it in enter full screen let's see what that does yeah it doesn't work it doesn't make it any bigger sorry guys okay so let's code this out um so we're going to need first we're going to need an array of frequencies um and let's create a length of 101 for the length down here and i need to zoom in so this is going to be constant space complexity because uh it's a very small size limited size so now we're just going to fill the frequencies so we want to let me go over this on the whiteboard so we're going to want to our frequencies is going to be an array oops so we're going to have zeros we're just going to put the frequencies where they belong and we're going to add them up so if we have uh three threes we're just going to put three here the rest are going to be zeros and then we're going to loop through the frequency array and um calculate this uh formula for each for the number at that frequency and add it to good pairs um that's how we're going to solve this it should make sense made sense in my head actually i less so we're going to loop through 101 and i plus we're going to loop through 101 because that's the possible numbers in um in the so numbers of either values is goes up to 100 so we're just going to loop through 101. so let's we're going to this is where we're going to set the frequencies for the characters uh no so numbers of i plus okay so now we have our frequencies set and now we need to loop through our um frequencies actually this is nums dot length um that was incorrect this one's 101 so because we have 101 values in frequencies we're just looping through the array and down here so we're just looping through the length and so now we want to if frequencies of i is greater than one that means we have good pairs um so it's saying let me pull up my whiteboard try and get it next to the code if there's a say there's a one here just a one um there's no good pairs because there's it's not possible for that value to equal another value that's the definition of a good pair so it has to be greater than like this right here and then we're going to execute the our function up here we're going to write it right below this if statement and add it to good pairs so um let's do exactly that so good pairs plus equals so we have uh frequencies of i minus 1 times frequencies of i and all that's divided by 2 and then we just want to return good pairs so let's see if that works off the first try yeah it did okay cool so i just want to show you guys see this is much faster 100 percent um it's just oven so it's linear and i don't know why the space is we're just doing a very small array anyways let's try and submit it one more time yeah they're sweet i feel like it's so arbitrary like every time it does this um so i just want to go over this formula it's i feel like it's easier to spot it if you already knew about it so there we have our combinatorics formula i write it out one more time so it's oops it's n minus one times and all that is divided by two so that's like for common combinations um if this video helped you guys please smash that like button i post videos every weekday so subscribe to my channel if you guys haven't already and i'll see in the next video
Number of Good Pairs
design-underground-system
Given an array of integers `nums`, return _the number of **good pairs**_. A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`. **Example 1:** **Input:** nums = \[1,2,3,1,1,3\] **Output:** 4 **Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. **Example 2:** **Input:** nums = \[1,1,1,1\] **Output:** 6 **Explanation:** Each pair in the array are _good_. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations.
Hash Table,String,Design
Medium
2285
149
you guys ready to tackle a brand new problem if you want to code along make sure to hit the link in the description below it's time to pop our daily dose of code max points on a line you're given an array arr in which each element corresponds to a 2d coordinate or a point that is a rfi is x i y i what is the maximum number of points that lie on the same line here we can see our input is 5 meaning there are 5 points each point is represented by an x y coordinate 0 1 2 7 5 and 0 4. let's plot it out and once we do we can see this is how it looks these five little colored dots are the points and you can see these three points 0 1 and 2 are lying on the same line now if we take any other set of points say this point right here at this point right here any line that passes through them is going to pass through only two points however this line passes through three points and it's the only line which passes through three points which is why our output is going to be three the maximum number of points any line can run through is three now guys i'll leave it open if you remember how to calculate the slope of a line you're already halfway there if you don't i'll give you a clue and i'll explain how to calculate it really shortly now have a look at this animation right here slope is nothing but the angle made with the x-axis the x-axis the x-axis as we can see two lines with the same slope are always going to be parallel the only case where this is not true is if the two lines intersect if the two lines are one and the same in that case they have the same slope and each and every single point in them is the same so the basic condition for two lines of the same slope being the same line is if they share at least one point because if they share one point they're going to share every other point furthermore this formula you see right here this is what we're going to have to use to calculate the slope if we've got two points labeled x 1 y 1 and x 2 y 2 those are their coordinates the slope is calculated using this formula y 2 minus y 1 by x 2 minus x x1 now these are all the ingredients you need to solve it's up to you to put them together try to solve it by yourself if you know how to do it head on to the coding link in the description below and solve it'll take you to a hacker with platform once you're done head on back to the video and i'll explain the solution here you can see we've listed out the five points we're going to start with point number one and draw every single possible line now if any of these lines have got the same slope that means they are part of the same line as they share a common point in point number one so any line involving point one and having the same slope lies on the same line this we're going to store this slope value into a hash map along with a count of the number of points so initially we start with the first point and we compute every possible line that is with point one and two one and three one and four and one and five here straight away we can see that 1 2 and 3 lie on the same line now we're going to repeat this exact same concept for point 2 now we've already finished 0.1 so we only do it with the subsequent 0.1 so we only do it with the subsequent 0.1 so we only do it with the subsequent points that's 0.3 0.4 and 0.5 similarly 0.3 0.4 and 0.5 similarly 0.3 0.4 and 0.5 similarly we draw every possible line between three four three five and point four and five in other words we're going to have two loops one outer high loop and one j loop that's nested in it the time complexity of this is going to be n squared but you can optimize it a slight bit the first i loop doesn't necessarily have to run from i to n or i to n minus 1. instead this loop can run from i to n minus the maximum number of points the reason being in this example straight away we can see that point 1 two and three lie on the same line meaning right now the maximum is three the maximum count is three now we can hit point two and three but now there's no point considering four and five any blinds involving these previous three points which have already been covered and the next two points have already been considered so the only possible lines that are left are the unique lines that pass through four and five however the only unique line that can pass through four and five covers only two points but our maximum number of points is three now we know if we proceed further on the best we can do is to cover two points however we've already got a solution that covers three points so why continue we can terminate it right here so the algorithm is run an outer eye loop from 0 to n minus i minus 1 run an inner j loop from i plus 1 to n and what we do is we compute every possible slope if it's a new slope value that hasn't been seen we add it to a hash map with a count of 1. if it's our old slope value we simply increment the count and once we're done with the energy loop we're going to have to store the maximum recorded value and we're going to have to create clear our hash map for the next i iteration guys the video feed has stopped but don't worry we're towards the end of the video anyway this is the code right here this is going to store our slope value max is initially zero we're going to keep recording the maximum element and return that in the end the first i loop like i said runs from 0 to length of the array that's n minus max minus 1. now we are going to have a j loop as well we can get a scenario where the denominator is 0. in other words the line is parallel to the y axis the slope of this line is considered to be infinity we'll just store it as this number right here if the denominator is not 0 we simply compute our slope using the formula we just discussed y 2 minus y 1 by x 2 minus x 1. if the key is present we simply take the associated value and increment it by 1. if it is not present we set its value to 1. we record the maximum number of points in this j iteration then we clear the dictionary for the next iteration and here we record the global maximum now we have to return max plus 1 since we don't account for the ith point now let's see if this works compile and test a sample test case has been passed submit beautiful every test case has been accepted so guys that's the solution to the problem max points on a line if you liked it you know what to do the golden trio it's going to show up on a screen make sure to click it also leave your comments down below if you've got a more optimal way to solve this or maybe if you've got suggestions for any future problems any problems you'd like me to solve here just leave it down below and we'll have a look it's very color guys awesome solving this for you and i'll see you all next time
Max Points on a Line
max-points-on-a-line
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\] **Output:** 4 **Constraints:** * `1 <= points.length <= 300` * `points[i].length == 2` * `-104 <= xi, yi <= 104` * All the `points` are **unique**.
null
Array,Hash Table,Math,Geometry
Hard
356,2287
149
Hello friends today I'm going to solve liquid problem number 194 Max points on a line so in this problem we are given an area points where each value in the point array is an x and y coordinate of a point in X and Y plane and what we need to find is the maximum number of points in a line a straight line so here in this example given below we have these three points so this is the point one two and three and we need to find the line with maximum number of points basically we need to find the maximum number of points that lie on a same straight line so since we know that this forms a straight line and all of this three point lie on the same straight line so the value here is equals to two now the problem here is how can we find or how do we know if all of these three points lie on the same straight line so let's transfer this problem here and now this becomes a problem of finding a slope because we know that um if two points have um if three points have same slope which means that suppose we have three points in this is the X and Y plane one two three okay let this be three points uh let this be one um this bp2 and this pp3 so um the x and y coordinate of tsp X1 and Y one and similarly for these it would be X2 Y2 and for this one is 2p X divide three now what's the formula for slope it's uh Y 2 minus y1 by X2 minus X1 so this is the formula of slope oh well we could replace these Y2 y1 with y 3 Y 2 X 3 and X2 so that's just uh one way to do that now what does this slope tell us basically the slope between these two points if we find the slope between these two point these is actually the angle that it's making with the x-axis angle that it's making with the x-axis angle that it's making with the x-axis so since this angle is equals to Theta here now if we find the slope between these two points then that would be the angle between these two points at and the x-axis now these two points at and the x-axis now these two points at and the x-axis now if these two angles are equal then that would mean that these three points lie on the same line so that is how we will be using slope to find the numbers present in the straight line now since we know um we find the slope for each of the points so we find the slope for these two points which is equals to Theta here and then we keep we choose one of the points we keep it fixed and now we take the another point and we find the slope between this point and this to this point so these two points would also give us the same angle Theta right this angle would still be equals to Theta so the number of count for this angle we will use map to store the value of the number of counts that we have identified so far so that would be two for these two points this point and these points that we uh calculated by keeping this one fixed and then finally we would add a value plus one to our result so that would be our uh result and we would do that for each of the points by like um traversing each of the points and finally um these values should be the maximum one so I just hope you get the basic idea of how we could solve this problem basically we'll be using the slope function and we will be using map to store our result and now let's try to code it so we need to let um plant let us Define um our slope function so what do we need two points P1 and P to be two points and then let X1 y1 is the coordinate of Point P1 and similarly X2 Y2 is the coordinate of P2 now we would return our slope that is Y2 minus y1 divided by X2 minus X1 so this is our slope that will return now we will iterate over each of the points and then we will create a new map each time and um let P1 equals to point zero okay points I and now this is our fixed Point here and now we would iterate over each of the other remaining points and find the slope so for okay for like J is equals to zero J is less than and J plus now one thing we need to keep in mind is that these points would not be the same as this point so if J is equals to I then we continue foreign this all right yes what do we do is let P2 equals to points J and then we find our slope is equals to um slope of P1 and P2 and then what do we do is now that we have slope we need to update our map if we do not already have this the value for this slope then we initialize it to 0 else map we just increase mint the value now and now once we have done it for all of the points keeping this one fixed what we'll do is we'll Now find our max value next Point let us initialize it to one now um for off checked and trees of the map Max point is equal to math Max of Max points and the Value Plus plus one and we could finally return our Max points let's try to run our code okay ret u r n all right a lot of typing mistake great let's submit it now cool so as you could see we did it in the time complexity of off and squared this is one time we are iterating over all of the elements in the points array and the next time uh so that would be a total of N squared and the space complexity is also in the worst case it would be off and if all the points lie on different lines so our final result will be here and yeah I hope it was helpful
Max Points on a Line
max-points-on-a-line
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\] **Output:** 4 **Constraints:** * `1 <= points.length <= 300` * `points[i].length == 2` * `-104 <= xi, yi <= 104` * All the `points` are **unique**.
null
Array,Hash Table,Math,Geometry
Hard
356,2287
1,473
hello everyone welcome to learn overflow in this video we will discuss about today's late quote problem paint house three okay so this is the heart level problem and we'll understand what this question is trying to say how we can solve this question we'll also visualize this question based on all the example like uh taking one example i'll specifically take the example to the sort in this case so uh we'll understand how this question is working and what they're exactly asking us to find out and then at the end what we will find out is like we will write some code write a solution to this and after the solution will they can understand how the solution is actually working for us uh or what exactly we did in the solution so that's what we'll do in our uh whole videos today so watch till the end and i'll make sure that you understand this question completely also before moving on i'd like make sure to subscribe this channel for regular latecode videos it says that there is a row of game houses in a small city each house must be painted with one of the n colors okay so there are m houses and it must be painted with one of the n colors level from 1 to n okay some houses have or have been painted last summer and should not be painted again okay so like it says like there are some kind of houses of like in a row and then some of the houses like we need to paint these houses uh with those in colors we have right and it also says like some of the houses are already being painted last summer say some of the houses are already painted so we don't need to paint those again now this is a neighborhood is a maximal group okay now it's uh describing what's the neighborhood a neighborhood is a maximum group of continuous houses that's continuous houses that are painted to the same color okay so that's what our neighborhood is whenever we paint with some kind of same color we uh find this is the maximum houses printed the same color that's the neighborhood we have okay moving on it says like as an example say there are houses of uh one two three two one so it says like it contains five neighborhoods that is one uh two three two and one it's just grouping the numbers uh into like uh same numbers each okay so that's how we are grouping there that's what they are saying as a neighborhood so if we say that there are five neighborhoods like there are kind of five groups of the same numbers each okay so that's how we make it so that's the neighborhood you can say so there's a count over here now uh let's see what further it says like given an array of houses okay so there we have we are given a houses array so this house that it probably stores this number of houses that is what it says for the uh is the color of the house of i uh like the eighth house color is given in a house that is it is zero if it is not painted it like it says like if it is not painted last summer it should go into that so that's what he said if it's not painted last number that means it should be zero else it will have some value in it okay now uh also it says there is the m cross in matrix cost so there's an m cos and matrix cost there's a cost matrix given to us and along with that it says like an integer target is given to us okay so uh now what we uh what is this cost matrices cosmetics is the cost of the paint of the eighth house with the color j plus one okay so that's the more or less the cost matrix we need to paint the eighth house with uh the color j plus one and that is the uh cost being given to us okay now uh just if we look into this then uh further it says that at the end we need to return the minimum cost of painting all the remaining house like whichever house is not painted yet right so we need to find the minimum cost of painting these houses uh in such a way that there are exactly target neighbor okay so that's the catch over here the catch being it shouldn't be like we keep on painting whatever color we find and we do with it should be like uh that our target uh neighborhood should be there so target is basically the number of neighborhood it should be there neighborhood is what the defiance over here so uh now we need to find out the number of target uh neighborhoods we need okay target is given in such that way now uh so uh it also says like if it is not possible then return minus one if our target neighborhood is not possible that it then we should return and minus one in this case okay so uh that's uh the question i think is pretty understandable what they are asking to do let's try to see those examples we have and try to understand uh what exactly uh the way weight is going ahead okay now uh you can see like houses are given the first case zero and then the cost is given in that manner okay like for each house there are two colors being given uh and each color has a cost with it like cost of the paint eighth house this is the zero eighth house right with color g plus one so color one and color two that's the cost being given to us so color one if we paint this house one with color one then the first will be one in case we pump in this house one house like zero eighth house with color two we will get a cost of ten okay so that's what given to us and moving further uh see what exactly we have we are given like this and in case we cannot paint or the like this target houses all the houses then we should return uh minus one so that's given so after like see we will take the minimum from here one and then we find two uh two okay that's how what we went ahead as a solution one then two and two uh selecting the second color because that one has a lesser cost okay like we need to find the minimum cost of painting right and then we went ahead with one and one because those two gave us and lesser cost okay but remember here you could have chosen uh this one right this one because that was much minimum but remember if we have chosen uh two at this place okay then how many neighbors would have been one two three and four neighbors will be there but our target was given as three so we had to do something so that our target remained in our uh like our target was three can be fulfilled so we went after five as a minimum cost okay so there we need to see how we can minimize the cost we have of it so you can see like at every position at every house we need to make two decisions and based on tools decision we need to move ahead with one decision and like we need to take two decisions like out of position we need to move it with one decision it cannot be greedy because if you went ahead with greedy then you see we would end up taking this uh last one we have over here right uh like if i just show you over here if you have taken a greedy approach then our greedy approach would have taken this one we have but we cannot take this one because that will end up in uh wrong like end up in not finishing our target okay like the target neighborhood so we need to have uh when you cannot go ahead with greedy then our approach should be more like an uh dynamic approach of the dynamic programming approach where we will keep an a memorization like memoization of the all the previous calculations we made and based on the memoration will make our further calculations okay so that will be the approach to us so let's uh understand a smaller example brings the this example to let's understand this and let's see how exactly this particular one works for us okay so let me erase all this stuff and then walk quiet with that now let's understand this particular example i just wrote the cost array over here for yeast to understand and then the target is three that you can see over here okay so on each tip we will uh you see that for colors like houses like this two one two we cannot have an um there's no need to paint these houses it's more like we will go ahead with uh not painting them rather we are only going to paint this house and this house like the zero one okay now let's understand how we will go ahead in this like what will be the visual approach to that okay so the first house is zero so uh we'll have two uh ways to go ahead with the best of the course so we'll say the total for say and they're taking with t uh the total cost till now will be one if we take color one okay that will be one and we mentioned that we took color requires one over here okay that's the approach and also uh we'll keep a note that uh what's the till now like till this position uh in the backwards how many neighbors we have over here okay so that means we have a approach of and n equals one so those are three uh things we have over here and if we go ahead with cost uh they cost one like the color one okay and if we go ahead with color two in the first house if we color it with the second two then what happens we will end up having our t equals uh say that the total cost still total cost is 10 till now 10 so if we as we go ahead with further houses it will keep on increasing uh on which house we pay okay then the cost till now will be something like uh now the color will be two this is not the cause this is the color would be two because we chose the second color okay so that's what being said to us and then we'll have a uh like till now the neighbor neighborhood is uh one still after this point there are only one color okay now next thing we find the second like two or two that is already being colored okay so once it's already being colored we'll simply move ahead with this like move down like no need to color this again right so that will be total cost will still remain as one our color will be here uh color here is two being given to us like that's the color we have already and the neighborhood count increased from uh neighborhood counties actually became two uh why in emerald begins to like the first one we painted with uh color one and next we have color two so one and two different errors so that's never found with become two and then if we uh went ahead with this color then what happens our total cost becomes uh remains as it is that is 10 so i'm writing it a bit smaller i'll zoom it if possible uh so the total cost remains our 10 okay because we are not coloring the current house and then further we went ahead with uh for like color remains our uh two now see the previous color was two and this color was is also two so we can go ahead with something like neighborhood remains our one okay so here neighborhood remains one then we find uh one uh next element this we move ahead with our uh step and we find the next uh that is already color so there's no need to color it further we find the total cost uh still remains one in our case okay our color changes to uh one like the current color we have is one and the neighborhood count uh goes to something like three we reached an able country because they initially were painted with one then two then one so never con becomes three and if we went ahead with the other keys of coloring it with two initially then what we have over here that total cost uh remains uh 10 because we are not covering it right now as uh the color we have over here is one and the neighborhood count becomes uh how much it becomes two being we painted two then two is already there and we came across with the color one so see like two and we changed it to one so this thus we it becomes like never contact two our target neighborhood was given as like target should be three now next move ahead they move ahead we find that it has again a two okay once it has a two so we find over here that uh our total count remains um like a one okay and protocol remain one and then color of our current house is two fine and our neighborhood count became something like four because uh one and the change again changes so neither count became four so we know that we cannot move ahead with this because our neighborhood fund became 4 our target was something like to keep it within a range of three so that was our time so we cannot go ahead with this uh step like we cannot go ahead and coloring our first house as one okay now we look further to check if we can go ahead further with our coloring house uh like coloring these houses too so what we found that uh that the total count like total cost we have is remains uh to be the 10th because we are not coloring this house it is already colored then the color of this particular house uh becomes what the color is two fine so see like one so the neighborhood became one never became two and the neighborhood became uh like three over here because we are again changing to neighborhood okay we are again changing the neighborhood over here so we found this next we have another house in our area so we actually uh if we find that this house is a zero so we need to paint this house okay so i'm just breaking it into two parts so one uh okay fine we are going now with the two step because after this uh particular step we will be going out with either painting it with the color or not painting another color okay and let's see what we have say after this uh say we paint this with color one okay so here are our color over here so we paint this with color once the total color count became we had 10 and we paint it with color one so we take it as five so cost became 15. fine now post that we see that the current color becomes one fine and once the neighborhood count becomes um see neighborhood was three uh previous color was two and we are changing the neighborhood like changing the color so it's become one so it becomes four so again we find that this is not an possible case and since our target was three okay since we are given a target of three so we cannot go with the neighbor count of four in this let's see we have another uh way for us to see if we can find a solution to that way or not so the total count becomes something like we had ten previously and the cost we have is uh one so the like the total cost is uh 11 then our current color is we just took the second color so the current uh color we have over here is like uh two fine and the neighborhood count see what really means over here right the neighborhood was three the previous color is true the current color is also two so the neighborhood remains three so neighborhood pond is not increasing so and then we find that our particular house the end of the house array is already so we are now sure like this is our final answer to our array like to our whole uh test case so what the answer we have the answer will be 11 and this will be our answer see the final answer given to us is 11 so that's the answer we should return okay so this is all the stuff we need to do in this particular question so i think you can actually visualize how we can go ahead with uh with this question like this and how we should uh move ahead okay say in see just in case you don't find out that the color at this position or the last house whatever we have we cannot uh paint this without going to like without exiting our target neighborhood okay without exiting this then in that case we should return minus one be honest one thing we cannot uh find a solution to this so that's the more or less the whole uh target behind the whole like the exact question okay so i think it's understandable like how we are going ahead with a question like this now let's like implement this whole concept within uh with some code and then try to find out how we can uh like we can do this in a minimum value okay anyone following the sense in like uh who can do this uh properly okay so what's the idea let's revise this one side what's the idea behind this so we are traversing simply through the houses area right the first thing we did was the left to right traverse the whole uh houses array then we keep up track of the neighborhood by comparing the talent of the current house and the previous house right so we keep a track of the neighborhood whatever the current house in the previous house and we incremented our neighborhood like so that's what we did we keep a track of this and then i think at the point of uh like number of neighborhood excited the target like over here the number of numbers exceeded our target was three so it exited and we did what we keep a backpack we didn't went ahead with this part we moved back and we went down with the other part right now uh so that's like backtracking it's like more like you are into uh moving into the depth of the path if you can find it you are good to go else you move back like a dfs kind of approach uh okay so we are finding our end of the solution and if we cannot find a solution we move back and then you start like you backtrack and then you start again so that's the way and in case like there can be multiple ways that you can see that there can be multiple ways to reach a uh target like it's not only that you cannot reach targets on other two ways and you'll find an only one solution this may not be the ultimate case there can be multiple ways to find a uh target value okay so multiple ways uh you can reach a neighborhood of three over here so that's possible so you need to remember you need to find the minimum of all the cost like whatever with the total found out you should find the minimum of all of them okay so uh for uh like optimized of this code like that's a backtracking you can see so to make it a bit more optimized we should go ahead with a memorization uh what we get in our dynamic programming approach so let's write this whole code over here okay let's write this and then we'll understand again how this codex actually work and let's write and find out how it works okay so here you can see like this is like the 6ms solution that is uh faster than us obviously it's the fastest solution possible so uh what exactly we did over here is more or less the exact thing we uh went ahead with uh doing like explaining in the whole video we will reach back so what exactly we did we went ahead with an tp array the dp of something like first doing the houses the color the group grouping the neighbors we have here okay from then we just filled all of them with the maximum cost we have then we went ahead to find if the house is zero then we just initialize the value to the cost of j that is the this is the first cost we have and else we just uh went ahead with the uh particular file we just said that dp of this target value is zero so we just initialized over here okay say we house zero so we need to color it so the initial cost is something we calculated that the all the cost we have we just calculated those okay we just put those value called refer to the tp array and then also we whenever we got like the house is not zero so we just took off a pointer to find and then we decided that this is zero and so we don't need to our cost at this position will be zero so we don't need to go ahead with our further dispersion okay so basically we just converted this cost and then over here we just uh went ahead look away our initial how zero was done so we went ahead with uh finding uh our search for house one and then house one but we did exactly over here we just checked if our house is greater than zero that means it's previously painted so we went ahead with finding out was the minimum at this position like uh like the remaining bin uh we just took an uh hr over here so hr is basically how many houses remaining okay and uh then what we did like this lit target minus one so we are just reducing the target address from that and also like we went ahead with this dpi that if there is any change like what change no changes are required how's it going for zero and if there is a change is uh going ahead okay the change in the color is happening so all uh remaining or the target should reduce those so remaining minus one is going at over here okay and that's we are finding what the minimum cost we are finding out over here if we like with this change is it kind of like uh so the house is greater than zero so we are not painting this but we need to check uh the neighborhood is at which position how many neighborhoods are there okay and in case like the house is not zero like we are painting the house so we are just painting with like uh current house being if the like the cost being at this position so you can see the cost being calculated and then we're adding the cost to our houses and if not if a change in the neighborhood is happening so that will be managing the change based on the particular conditions we have earlier which is managing the change being calculated for us okay and moving ahead we simply calculated the all the final cost that we are about to find like that's going exactly by what we discussed few minutes back and then we uh here we just took another function this function is actually help us calculate the minimum cost okay at each position so a bad particular find you can find that mean is a function being called and how we did actually you can see the function takes a 2d array uh over here but how are we given it we given uh dp of i minus 1 like dp dpi you could find it over here as well okay so what exactly happening over here we are finding the minimum of this like we are saying that uh i minus 1 and that's sending a 2d array so dp is initially 3d array with showing the three different values different places so uh that's how we are uh finding the minimum cost and ultimately we are returning that the min being the uh this particular value mean that we find out over here doesn't mean uh if his mean is less than max cost then we should return mean and in case our mean is still equal to the max cos that's what we took as the max cost of earlier mean is still the max cost that means no way is possible to pay in the houses with the given target okay so that's the final answer over there and you can see that this answer works pretty good with a six millisecond solution and this is uh like 100 uh faster than like all the solutions you can find okay so i hope you can understand how this uh particular question works so if you have any doubt make sure you just uh point it out over in the comment section below i will help you out any way possible okay so that's all about this question guys so uh that's all uh about this question i hope you can understand this question uh easily so make sure to subscribe to this channel and uh if you face any problems comment down in the course also like this video so that i it helps me motivate to more fun also like these videos so that it motivates me to make more search videos for you thank you for watching this video hope to see you soon in my next video as well thank you you
Paint House III
find-the-longest-substring-containing-vowels-in-even-counts
There is a row of `m` houses in a small city, each house must be painted with one of the `n` colors (labeled from `1` to `n`), some houses that have been painted last summer should not be painted again. A neighborhood is a maximal group of continuous houses that are painted with the same color. * For example: `houses = [1,2,2,3,3,2,1,1]` contains `5` neighborhoods `[{1}, {2,2}, {3,3}, {2}, {1,1}]`. Given an array `houses`, an `m x n` matrix `cost` and an integer `target` where: * `houses[i]`: is the color of the house `i`, and `0` if the house is not painted yet. * `cost[i][j]`: is the cost of paint the house `i` with the color `j + 1`. Return _the minimum cost of painting all the remaining houses in such a way that there are exactly_ `target` _neighborhoods_. If it is not possible, return `-1`. **Example 1:** **Input:** houses = \[0,0,0,0,0\], cost = \[\[1,10\],\[10,1\],\[10,1\],\[1,10\],\[5,1\]\], m = 5, n = 2, target = 3 **Output:** 9 **Explanation:** Paint houses of this way \[1,2,2,1,1\] This array contains target = 3 neighborhoods, \[{1}, {2,2}, {1,1}\]. Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9. **Example 2:** **Input:** houses = \[0,2,1,2,0\], cost = \[\[1,10\],\[10,1\],\[10,1\],\[1,10\],\[5,1\]\], m = 5, n = 2, target = 3 **Output:** 11 **Explanation:** Some houses are already painted, Paint the houses of this way \[2,2,1,2,2\] This array contains target = 3 neighborhoods, \[{2,2}, {1}, {2,2}\]. Cost of paint the first and last house (10 + 1) = 11. **Example 3:** **Input:** houses = \[3,1,2,3\], cost = \[\[1,1,1\],\[1,1,1\],\[1,1,1\],\[1,1,1\]\], m = 4, n = 3, target = 3 **Output:** -1 **Explanation:** Houses are already painted with a total of 4 neighborhoods \[{3},{1},{2},{3}\] different of target = 3. **Constraints:** * `m == houses.length == cost.length` * `n == cost[i].length` * `1 <= m <= 100` * `1 <= n <= 20` * `1 <= target <= m` * `0 <= houses[i] <= n` * `1 <= cost[i][j] <= 104`
Represent the counts (odd or even) of vowels with a bitmask. Precompute the prefix xor for the bitmask of vowels and then get the longest valid substring.
Hash Table,String,Bit Manipulation,Prefix Sum
Medium
null
1,748
foreign problem and the problem's name is sum of unique elements in this question we are given our integer array called nums and we need to find the sum of unique elements inside that array so by definition a unique element is an element that appears exactly once inside the array it means the count of that element should be 1 so we have to find out those elements and add them up and return it as the output so the length of this array is 4 out of this there are only two unique elements because one is appearing one time and three is appearing one time two is appearing twice so it is not a unique element so we add 1 and 3 and we get the sum as 4 which we return it as the output now let's take a look at this example and develop the logic to code it up I've taken the same example given to us so this is the nums array now we have to find the unique elements inside the array so that we can add them and find the sum so I'm going to use a hash map to store the element and its respective count so let's make a hash map now so this is the hash map the key will be the array element and the value is going to be its respective count so to fill the ash map let us accelerate through the input array from left to right so we start off with the first element if it is not present inside the map add it into the map so one is not present so add it into the map and set its frequency to 1. go to the next element is to 2 is not present inside the map so add it into the map and set its frequency to 1. now go for the next element is 3 is not present inside the map so add it into the map and that is frequency to one next element is 2 is present inside the map so increment its frequency by one current frequency is 1 so 2's frequency will become 2 and now we reach the end of the nums arrays and now we have the hash map ready and now we declare a variable sum which will be our output and initialize it with 0 because the sum is 0 as of now we have to iterate through the entries inside the map there are three entries inside the map now we start with the first entry so unique element will have a count equal to 1 so we have to check for Keys whose value is equal to 1 so in the first entry we start off with checking the value its value is equal to 1 so add its key into the sum so its key is 1 so sum is now 1. now check the second entry second entries value is 2 so it's not unique so skip that element and go for the next element value is 1 it's a unique element so get its frequent and add it into the sum so 1 plus 3 is equal to 4 and now we reach the end of the map so all our entries are finished and the final answer is stored inside sum and the sum is 4 so sum will be returned as output now let's implement the steps in a Java program coming to the function given to us this is the function name and this is the input array norms and the return type is an integer denoting the sum of unique elements so first we start by declaring the hash map so the key inside the hash map is an integer and the value inside the hash map is also an integer so keys are going to be the array elements and the values are going to be the frequency of that array element so we iterate through the input array Norms to fill our hash map so we start with the first element inside the nums array and then we're going to check if that element is present inside the map as key since the map is empty it will execute this statement and it will insert that element inside the map and set its frequency to 1 and from the next time whenever you find the same element which is present inside the map as key it will get its current frequency from the map and increment it by 1. so this else statement will be executed for every unique element inside the nums array and from the next time it appears this if statement will be executed so this for Loop will give us the frequency of every element inside the array and now we are declaring our output variable sum which is initially zero and now using the entry method on the map I am creating an entry object to iterate through the entries inside the map using the entry set method now I am checking the value of each and inside the map since unique elements have a count equal to 1 so their value should be 1 so whichever element has a count equal to 1 I'm getting its corresponding key which is the array element and adding it to the sum so in this example one is a unique element because its count is one so I am checking if count of 1 is equal to 1 yes count of 1 is equal to one so I am getting the key so I am accessing the element 1 and adding it to the sum see sum was 0 it will be updated to 1 and next three is also a unique element because its count is 1 yes count of three is one so get its respective key is three so add 3 to the sum was 1 it will be 4 now and now it will check count of two is two so this condition will fail and it will come out of the if statement and outside the for Loop you accessed all the entries inside the map and you have our final answer inside result so for this example we had 4 in our output so we are returning some math output now let's run the code the test cases are running let's submit the code and the solution has been accepted so the time complexity of this approach is of n because we are iterating to the input array Norms from left to right where n is the length of the nums array and the space complexity is also often because we are using a hash map to build our logic and that's it guys that's the end of the video thank you for watching and I'll see you in the next one
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
236
now I have according interview question worst common ancestor that was recently asked by Twitter he were given a binary tree write a function lowest common ancestor LCA that takes the head of the given tree and to note eight and seven and this function should return one because the ancestor of the node 8 &amp; 7 because the ancestor of the node 8 &amp; 7 because the ancestor of the node 8 &amp; 7 are 1 and 5 and the lowest common ancestor each we see 1 so this function should return 1 and for this function LCA hit 4 5 here 4 5 this to note we should return 5 an ancestor open node the node itself to write and for this case this function should return 5 you might say why 4 is not the ancestor in this sketch because here we have a flow from top to bottom we can't go from bottom to top that soy food can't be ancestor in this sketch all right and this function should return 9 the ancestor of this node 9 and 9 is 9 because an ancestor open node the node itself - all right now you might node itself - all right now you might node itself - all right now you might assume that this binary tree have no duplicates node all right and for this binary tree in North may have one child now try solving this problem in Big O of n time complexity when you're done come back to the solution video here's how I think about this problem lowest common ancestor we have this binary tree right then I'm going to create a function LCA that takes 8 of this binary tree and to note on which we're going to find the lowest common ancestor in this gate eight and seven they were going to create a function path to X that takes the head of this binary tree and DA not okay and this function will return the path to this node for this case the path each eight one and five right so this function path to x88 it should return eight one five right and then all going to create another function path to X with head and seven and this function should return in this case a path seven three one five like this alright now we have these two paths as is check okay then we're going to pop out the last element from this stack then we're going to check if that the same element and on the message element or on the same element in these two we're going to find the lowest in this gate we have one and we should return one now let's see how we can find the path now I'm going to explain you how can find a path to a specific node right we have this binary tree right and we call this function LCA with head five and eight and seven node and now we have to find path to eight and also we have to find path to seven all right now I'm going to talk about this function path to X head eight now let's see how can find path to eight we can traverse this binary tree using depth-first search and I'm going to use depth-first search and I'm going to use depth-first search and I'm going to use depth-first search to traverse this depth-first search to traverse this depth-first search to traverse this binary search tree you know we can huge depth first search in three different way in order first order and pre-order way in order first order and pre-order way in order first order and pre-order in this video I'm going to traverse this binary tree using pre-order depth-first binary tree using pre-order depth-first binary tree using pre-order depth-first traversal all right and in pre-order we visit five all right and in pre-order we visit five all right and in pre-order we visit five one three six then seven then here eight then for the nine then - all right now then for the nine then - all right now then for the nine then - all right now let me explain it first I'm going to create a function path to X that takes the root node of this binary tree and the number X in this sketch eight right then I'm going to check if the root is now then simply return now okay for diskette route is five not now so it will not work if wrote to T value equals to X root dot value equals to 5 and x equals to 8 and 5 is not equals to 8 so eat altar faults then here left path left petticoats to path 2 X root short-lived in this kit its points to 1 short-lived in this kit its points to 1 short-lived in this kit its points to 1 and here X equals to 8 and this two condition false that has called this function again which three and eight and it also needs to condition false then it call again with 6 and 8 then it also falls then it caught with now because we have now note here the left and right node of this node is now and also 4 7 9 2 &amp; 8 2 &amp; 8 2 &amp; 8 all right lip not our now for all of this node alright in this kit we have elliptical sternal so we call this function again now + 8 so it returned just now and then now + 8 so it returned just now and then now + 8 so it returned just now and then we go back here if left path nautical sternal but we have left particles to know so this condition is false then it's goes to right path to X root right X in this case root dot right is also now write this it now then it's return now then this condition also false then it's just richer now okay now all right I know it's pretty complicated to understand what did I want to break it down into its separate part now let me explain to you everything what's going on in here all right now let me give you an inside tips first we call this function path 2x with head in the skate he recalled two fibrate and x equals to 8 then organ to call here left path LP for left path and this condition is false for this time because 1 is not equals to 8 also root not equals to now then we call this function the midis function calls again path to X with 3 and 8 because your root dirt left is 3 and we have here 8 then this two condition is false then again this function calls path to X root dot left in this sketch root dirt left is 6 then we have x equals to 8 and we call this function again in this case this to Commission is false then it calls again LP in this case path to X here we have root dirt left and left node of 6-8 now root dirt left and left node of 6-8 now root dirt left and left node of 6-8 now right we call this function week now and 8 there in this get these functions return now right here because in the schedule oracles to know so this function return now then it comes to this line if that part is not equals to null but in this gate let path here L pickles to know so it folds then it moves to this line right petticoats to path 2x it calls path 2x with Rho dot right the root right up 6 each now right and exit 8 in this gate root is null so it also return now all right in this case if a right path nautical tuna but we see here right path equals 2 now so it falls it just returned now in this sketch this function 6 8 is returned now because we have left path equals 2 now and right but equals to also now and here is no chance to execute this statement written led pot or written right path all right now we have finally kept 2 X 4 6 8 equals 2 now all right in this kit 4 6 &amp; 8 this kit 4 6 &amp; 8 this kit 4 6 &amp; 8 it's returned all right then it's goes to this statement if let Pat nautical sternal but we see it equals to null so this condition is false then it's goes to this line here right particles to path to X root dirt right and then it's moves to this 7 root dot right okay then it calls with 7 because here we're 7 &amp; 8 all right then because here we're 7 &amp; 8 all right then because here we're 7 &amp; 8 all right then it calls this function in this case root no decodes to no and root dirt value not equals to 8 right in this case we have 7 right so in this sketch we call this left cut function in here path to X with left now X now 8 right we call this function with now and 8 because the left node of 7 is now then it's return now right it's return now then this condition is false because it calls to now this goes to this line right particles to path to X the right node of this node server is now so now X min 8 so it's called this function again then in this case vertical sternal it's return now all right so here are P path to X now 8 it also return now there we have LP cules to now and articles to know let that and write but both equals to null so it will just simply return now here it will return now all right now we have here 4 6 8 and 4 7 8 now right so in this case this function 3 8 call it should return now because left protocols to for this is now and were also decision now so finally for 3 8 it should return now all right then we got left pot equals 2 now right then it moves to this line left part nautical sternal body T constant also this is false then right particles to path 2 X in this case route right is eight and in this sketch we see that right path to X is 8 and 8 in this case root nautical sternal but in here route Death Valley cots 2 X 8 now 8 equals to 8 so it returned a stack with the route in this sketch the route each this node right 8 so it just returned a stack like this and it just returned 8 like this so this function finally returns a step alright here we return a stack with the route in this case the root node is 8 okay then in this case we have right path equals to 8 right this stack now therefore the function calls pair 2x on 8 left path equals to null and right path equals to 8 and here the right path is not equals to null so right path that push and we're going to push the root in this case the root each one right and we're going to push the root in this stack and then we're gonna just return that and then it will be look like this alright so we just push one two this check and we return the stack and then it'll look like this eight one right now for this function call five and eight we have eight and one right this tech in this gate LP codes to eight and one so now left path equal to this one now this condition is true left path is not equals to null then left path equals to push root here we have root it in this case root is five right then just push the root to this stack then it will be look like this alright finally it will look like this and here we just return let's bet and this is only twit that will result store this function call path 2x finally we have this each our pair I think it's hard to understand but if we try to understand like this way and it will be pretty simple all right knowest with your own examples and this is our pet now let's find out the pets for a hate 7 all right so we have your function back to X and we have to find this path 2x 4 7 and here for first time here equals to 5 and we call this function and it's here in the sketch root is not now and in here we have 5 pipe is not now and it's not equal to 7 right then left path LP calls to 1 and 7 because it's called this functions left Pat root dirt left the left of this node 5 is 1 they're all gonna just call this function then in that kit we have this is false this is also false because 1 is not equals to 7 they're going to call this function again then it calls with root dot left row dot leaves 3 and 7 then this is false they are going to call this function again right then here L pickles to path 2 X 6 and 7 and then we're going to call this function again then it falls this fault and 6 &amp; 7 is not equal so this world and 6 &amp; 7 is not equal so this world and 6 &amp; 7 is not equal so this world then we call this function again so it's become like this apricots to path to X now so it'll return now all right then this condition is false because left particles to now right then right particles to recall this with the right node because we have your left and right is now right and in this case right now and 7 so it will also return in this kit will return now all right then we have left path and right particles to know so this function calls for 6 and 7 it will return now all right finally we have left path for function call 6 7 equals 2 now then lift particles to now then we're going to go to this right path right particles to in this kit 7 &amp; 7 this kit 7 &amp; 7 this kit 7 &amp; 7 all right in this case this one 7 &amp; 7 all right in this case this one 7 &amp; 7 all right in this case this one 7 &amp; 7 okay then organ to call this function again there it's false that it's true right because so many calls to submit it then it's just return a stack with the root equals to 7 right and in this case we have protocols to seven then it should return this stack ok then it returned the stack there's go moves to this line right path Nora calls to know and eats nor decodes to null write it in this gate awright particles to sit stack right particles to stack so left path dirt push here we have root right and we're going to just push the root in this case our root each three right in this case you have root is 3 there we're going to just push it 3 all right and this function here it's return a stack with 7 and this function will finally return 7 and 3 all right in diskette dysfunctions this functions for call 3 and 7 it should return 7 and 3 right and now there we have lead particles to this one right 7 and 3 and in here we see that left but not Eagles to now ok in this case if nautical stew now it's true they let path touch push root in this kit is root is 1 so we're gonna just push here 1 it will be look like this 7 3 1 all right in this case it should return left path and left but ob7 3 one right here we have left PAP equals to 7 3 1 and then for this functions called we have left particles 2 7 3 1 ok in this get this age let particles two seven three one and this age true this condition is true it dis left path historical sternal the end let path that push root in this case or root is five correct finally this function will return 7 3 1 5 in hideous line here left path ok and that's how we get this path seven three one five and now there we understood how he can get the path to X alright now we have does to stack right and now we have the path to eight and path to seven now let's see how we can find the lowest common ancestor all right now there we have this binary tree and forest we call this function with head and eight and seven now let's create a function LCA that takes the root of a binary tree and J and K J is the value P node and also kids develop a note in this sketch eight and seven for J and K then I'm going to find the path to J here so I'm gonna call this functions path to X root and with J in this kit jcots to eight so for this one it will return this stack that we have discussed earlier right and then we're going to call this functions to eat root and K and organ to store that in this path to K and its return in this tech or he helped talk about ally right then I'm gonna check if path to J or pet to K it now either one or two if either one or two is now then simply return now then I'm gonna define a function to l CF for lowest common ancestor recalls to know then I'm gonna run in loop until path to J and path to K is not empty then run this loop then we're gonna just report the last element from this path to J and in this case this one and I will just remove this element and get this element five and kpop equals to path to K let's pop and we get this element and we remove this element from this stack right and then if J underscore pop equals to K underscore pop if this equals then I want to check in this gadget equals right then we're going to check is LCA Norah calls to know but it equals to null for now then it not works goes to this out spurt the LC equals to five in this case we have LCA equals to Phi Brett and for the next iteration we removed this element one and also this element 1 and J Poppa calls to one also gave up equals to 1 in this kit this is equals right then here LC and articles to know and also j-pop less than LC j to know and also j-pop less than LC j to know and also j-pop less than LC j poppies one right and Elsa is 5 and it's true in this kit LC coats to j-pop right true in this kit LC coats to j-pop right true in this kit LC coats to j-pop right in this cage LC equals to 1 there in the next iteration of this while loop it's goes to 8 and 7 and in this Katie just removed this one from this debt is to stack and in this case we have J Poppa coats to 8 &amp; 3 / pickles we have J Poppa coats to 8 &amp; 3 / pickles we have J Poppa coats to 8 &amp; 3 / pickles to 3 and it's not equal right so it falls it on it run then it's go to the next iteration in this iteration we have path 2 J it's empty because we have nothing we just pop out everything from this stack so it stopped here and then finally we're going to just return LCL lowest common ancestor in this case you have will score an ancestor each one all right in this case you find the lowest common ancestor each one and we visit here is node once so our time complexity to this problem is Big O of n all right guys this is one of the hardest interview question right so in order to get it and here to you to practice with your own examples in order to grab it on your head it might look pretty hard pretty difficult to understand no worry try it with your examples it will be clear to you alright guys thanks for watching this video and I'll see you in the next one
Lowest Common Ancestor of a Binary Tree
lowest-common-ancestor-of-a-binary-tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)." **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1 **Output:** 3 **Explanation:** The LCA of nodes 5 and 1 is 3. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4 **Output:** 5 **Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[1,2\], p = 1, q = 2 **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` will exist in the tree.
null
Tree,Depth-First Search,Binary Tree
Medium
235,1190,1354,1780,1790,1816,2217
1,608
all right guys welcome back to study plan binary search day seven the second problem for today last one so special ri with x elements greater than or equal to x you are given normal numbers of non-negative integers not as considerate non-negative integers not as considerate non-negative integers not as considerate special if there exists a number ext such that there are exactly x numbers in numbers that are greater than or equal to x notice that x does not have to be an element in numbers return x if the ri is special otherwise also minus one it can be proven that if nums is special the value of x is unique so for example one with our number you have three and five the output is two because there are two values three and five those are greater than or equal to two for example two this is our array where is one minus one because new number faces the great serial for x if x equal to zero is there should be zero numbers bigger or equal to x what's there r two if x equal to one there should be one number bigger equal than x but they are zero and the same for two okay so versus one minus one for example three this is our arrival it's only three because there are three values that are greater than or equal to three they are four three and four first leaderboard to do binary search it source the array then let's make the left equal to zero and the right equal to the length of our number minus one while the left is smaller equal than the right in this case it's calculated middle it's adjusted let's plus all right minus left divided by y2 for integers and now let's calculate the x should be the length of our numser minus midi let's check if our nums in the mid is equal is bigger or equal to x so if achieve so if it's achieve this okay this thing locked this thing if it's easy let's make sure our m equals to zero or numbers of m minus 1 smaller than x because we have just we want to just say do we want to just say x numbers that are bigger and bigger than x we don't want more like in this case if this is the case we return x otherwise we move the right okay and in this case if we don't have this much we update the left i hope this makes sense to you and finally let's say 12 minus 1 if you don't show anything here so that means you don't find any much okay that's likewise is so it's work i hope this video was useful for you and see you soon
Special Array With X Elements Greater Than or Equal X
calculate-salaries
You are given an array `nums` of non-negative integers. `nums` is considered **special** if there exists a number `x` such that there are **exactly** `x` numbers in `nums` that are **greater than or equal to** `x`. Notice that `x` **does not** have to be an element in `nums`. Return `x` _if the array is **special**, otherwise, return_ `-1`. It can be proven that if `nums` is special, the value for `x` is **unique**. **Example 1:** **Input:** nums = \[3,5\] **Output:** 2 **Explanation:** There are 2 values (3 and 5) that are greater than or equal to 2. **Example 2:** **Input:** nums = \[0,0\] **Output:** -1 **Explanation:** No numbers fit the criteria for x. If x = 0, there should be 0 numbers >= x, but there are 2. If x = 1, there should be 1 number >= x, but there are 0. If x = 2, there should be 2 numbers >= x, but there are 0. x cannot be greater since there are only 2 numbers in nums. **Example 3:** **Input:** nums = \[0,4,3,0,4\] **Output:** 3 **Explanation:** There are 3 values that are greater than or equal to 3. **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 1000`
null
Database
Medium
null
1,704
hi everyone welcome to my YouTube channel and I hope you guys had a wonderful weekend so in this video we will be looking at problem 1704 from the code here is the problem statement um this problem is easy and I think you guys should be okay solving this kind of problem um so actually on my first try I made a mistake because um even though I read the state I read this problem statement and then so when you look at this vowels we have capitalized one but then when I was working on my code I completely forgot about this part so uh to make that kind of mistakes that I just made but anyway this is a problem statement and well try this problem on your own yeah so this video will be quite short um which is good right so um so here is the way I did it since the problem says um s has a even length so we don't have to worry about that like you know the case when we have a odd length so when we have an even length we can just first find the um the total length of this s and then we can do the division by two and so that will keep us um so if so in this case we have a eight right the length is eight and if you divide this by two we will get four means here right because in Python is it is zero index so um so this is the vowels we had we have and so you can just create a set and then I will create a two variables first and second so first means like first means the total number of vowels that uh the first half uh string has and then the second will be the total number of vowels that the second half of the string s has so in this case we have the first will be equal to one right just e itself and then the second one we have two o so we have a two for a second uh so that is the step one and then the step two will be we will be running a for Loop then our for Loop will be from zero to start point right because if you have something like 4i in range of start point uh this I will be from 0 to start Point minus one which is exactly what we want and then you we you know we check the we check if so I and S of I plus start point if they are in the in our panels if that's the case then we increment first or second by one and then when we exit the for Loop we just return if first and second are equal to each other or not so that is for this problem okay so here is the code for that problem exactly the same thing and um yeah let me run this so that is for this problem I don't think this problem was difficult at all just make sure that uh you read the problem statement correctly um yeah and that is so I will see you guys next time okay if my video helps you guys understanding this problem you can subscribe to my channel and please give me thumbs up and I'll see you guys next time bye
Determine if String Halves Are Alike
special-positions-in-a-binary-matrix
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
Array,Matrix
Easy
null
1,673
hi guys how are you I hope all you are doing good welcome to the learn code easily today we will continue with the very stack series and today we will again solve the one more question and here we have solved the 40 plus questions here so if you are new to this Channel please like And subscribe and comment as well and if you are beginners in the coding then you can access my easy level playlist and these are not the limited question in stack also there are easy level questions as you can see these are easy level question and other than this there are a lot of questions are present in my YouTube channel so it's better if you access it because you can find any question which you really want to solve and let's move towards our next question so here it is given that we have an integer and we have to find the most com most competitive uh most competitive secant so what is the most competitive subsequence so it means that we have to find a sequence assume that if we have here we have a three five two six okay and here case two so we have to find the sequence of two so we it could be three five it could be three two it could be three six it could be five two and it could be five six and it could be two six so most competitive means smallest one so here the smallest one is two six so first you will compare the first one so here everyone have a 3 5 and 2. so in this the two is the competitive one so means we assume that if we have a 2 7 as well so again this could be the most competitive because here is the smallest one we have okay so and in this case we have we could have for uh this one sequence then we have a this one sequence we could have two three comma six so which is commodity one competitive one is this uh in and we could have a this one as well we could have a three five so which is completely one this is computer because why because 2 is present everyone but here we have a three so here this could not be possible because here is 4 uh there could be so on but here I am taking some of them some of the sequences so again we have a three here so we will again compare now we'll again compare nine here we have a six here we have four here we have five so which is community table computation is this one now the question is how we can solve with the help of Stack because this is our stack series so here you need to think the reverse bye uh assume again uh three five two six values three foreign this is me who is seeing that whether you are changing the sequence or not okay so do not change as you can see here so the most Community yoga foreign K4 foreign yeah foreign and if you remove the biggest number then you will get the smallest okay so here we have a eight now we will remove the biggest one here we will remove the biggest one and here we will get the smallest one I hope and the biggest number in length is biggest number length is if I take 8 then we have us here we have a eight then we have a six now we have to move two so what is the biggest number we will move to so we will get the length of 6 which is the smallest one I hope this is clear this logic is clear then we will move towards our next uh towards the coding part so here assume that if we have a three so let's do not take this one three five two six now let's take K is equal to three now we will now in the stack we will take the stack and we will append three and what will what we will do 4 minus 3 is equals to 1 means we have to remove the one element remove element so we have to remove the one element so here we have inserted three now when I will now I will set the three now when I will go to insert five I will check the previous element is greater than or not uh is greater than not if it is not then I will insert here 5 now uh now I am going to insert here two here I have to remove only one element so when I will insert 2 here then I will check that to that previous element is greater than 2 yes so we will move this one now we have one as I remove this one I will decrease to zero I will D I will decrease by 1 then it will come to you and as it will become 0 I will come out of the loop as it will become 0 then I do not check I do not need to check the previous element just I will insert all the elements so this is the our length of array which I need to return maybe you could not understand let's take one more example two four three five four nine six now K is equals to 4 and now after dividing K is again becomes equals to four now I have to remove the Four Element here so I have inserted 2 then 4 as 4 is greater than 3 so I will pop it out I will insert here three now your removed element decrease by one then it's become my then income three now I will again install three now five as I will insert 4 then I will pop it out I will make it as a 4 now it's become two now I will insert nine as I will see six here so 9 is greater than so X will be 6 now it will come 4 now the loop is in that and we have a two three and we will insert two three four six but I want the length of four so I will move the last one so simply This Is My Lens because I need the four fourth one I need the length of four assume that if we have a 7 here now if we have a C1 here so the remove the element will be 1 because 8 minus A1 is equals to 1 now we have a 1 so let's 2 4 3 5 4 9 6 now we have a one a v it's a remove element K is equals to 7 here now I will insert It 2 now 4 as I will see three I will pop it out now this will decrease by 1 to come to 0 as it will come to 0 I will insert all the elements in my array so my array is equals to 2 3 5 4 9 6 and this is the smallest length which you can get you can check it out from your side so I hope that this is clear now we will so this is stack and here what and here I have to run a loop so that Loop is going from now this Loop is going and here we have while loop so while Loops stack does not equals to empty and Y and what is the remaining element so I'm taking is a remaining removed element so remove the element is equals to the length of nums minus K so this should not be equal to empty which I have already told that we will move until and stack minus one if it is my the last inserted limit is greater than my current element the last inserted element is my current element then what I need to do here is I need to Simply this one then we have decreased by one uh okay so Coach cases then remove the last inserted element okay so it's tag dot pop come here remove the element code removed element to decrease thank you foreign foreign foreign so I do not do that these type of synthetical readers so I you so this has been run let's try to submit and it will be submitted as well I hope so will always problem yeah so this has been run what is the time complicity the time Community is a bigger fan because we have a private Singapore array because only once and what is the space is time space Community because we are taking a stack so it's a big off and again space so I hope this is clear I will meet in the next video with the next video till then bye
Find the Most Competitive Subsequence
find-the-most-competitive-subsequence
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. **Example 1:** **Input:** nums = \[3,5,2,6\], k = 2 **Output:** \[2,6\] **Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive. **Example 2:** **Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4 **Output:** \[2,3,3,4\] **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `1 <= k <= nums.length`
null
null
Medium
null
94
all right so let's take a look at this problem is called binary tree inorder traversal so generally for these types of problems you just need to be familiar with the different ways to traverse a binary tree and then once you get used to it should be pretty simple to traverse it in different ways so for n order it means that you're just going to start on the left side and then work your way to the right side so let's take a look at this example if your root is one and you were to start going down the left side there is no left side so once you complete the left side for in order your next step would be the root so that's why one is printed next and then after that you're going to traverse all the way to the bottom of the right side and start going left to right on the right side and that's why three then two looking at the next one you have a left side no right side so as i was saying you're going to start going down to the farthest end of the left side first so you have two then one that's exactly what you're seeing as the designated output and then again on this one there's no left side so you're going to go all the way to the right side after you visit the root so you visit the root first which is 1 and then the right side is 2 and there's nothing else over here so 1 and then 2. so how do you do this one of the easiest ways to really do depth first traversal in a binary tree is just using recursion there is other ways to do this with a less space complexity but i would say in an interview or anytime somebody asks you this question it's unlikely that you're going to be expected to use the new method so depth first search should be just fine for this one and for this problem we know that the number of nodes in the tree is in a range of zero to a hundred and the values are between negative 100 and uh 100 so basically we don't have to worry about any kind of crazy inputs that would cause our function to fail otherwise you could do a bunch of different checks just make sure you're not having any invalid input but based on that we should be good so we'll actually skip putting this part first so let's just go ahead and write our depth first function so on our depth first function uh you know they're expecting us to return a list what we can do is we can pass that list into our function and then just manipulate that list and add values to it during our recursion calls so we'll just say this is our result list and then we also want to know what node it is that we are currently looking at while we're traversing it in this depth first function also i need to cover what is being returned in this case we can just make it void because like i said we're going to edit this list that we're passing in and it will automatically update uh that list that will come from this main function we're calling it from so now with depth first functions uh basically you're going to start checking to see if there's a left and then a right and we also want to make sure that the node is not equal to null so if it is not equal to null then we can actually do something so if it's not equal to null let's then jump to that left node first to make sure that we get all the way to the farthest left point and then we're going to work our way to the right so then if node.left node.left node.left is not equal to null then we're going to depth first search on that left side and also i almost forgot we need to pass in our list that we're carrying from function to function the same thing is going to happen for the right side if we have the right side we want to make sure that we traverse to it as well after the left side now here's the part that you can kind of see vary whenever you're doing problems like this is whether or not you want to print certain notes in certain order so they might change it up on you and say like instead of you know a typical traversal maybe they would expect you to go to the left side but then uh print the right node before the left node things like that so just keep in mind that whenever you have variations of that just get used to how you could change the order of how a node would be printed or stored so in this case with the standard depth first uh traversal it is that we want to take that left node first and add it to our list so if the left node is not null and it goes all the way to the far left after it gets to let's say this part it will have added this node in it's going to say the left and the right are null but when it says that the left is null it's immediately going to then add this value to our list and then it will try to add the right into a recursion but it can't because there is no right and then it's going to go up here and then when the one had added itself in right here into our recursion before it ends up going and checking the right side that's when it's going to add itself into our list so res.ad and then itself into our list so res.ad and then itself into our list so res.ad and then we're just going to say node.val we're just going to say node.val we're just going to say node.val because as you can see here if you didn't see this before tree node or you know whatever the class may be that you're using to build your binary tree is defined here so it's very important that if you had an interview or something like that you'd ask is there a class defined or do i need to define a class but in this case only code you could see it's defined here with all of its attributes left and right as well as the integer values is dot val so we add that val to our list and then the rest will take care of itself so when the right node gets added if there's no other nodes after it when it comes back out of the recursion it will essentially end up calling itself to add to the list once it adds this node.right in so to come in it'll say node.right in so to come in it'll say node.right in so to come in it'll say it's not null maybe there's no left on it and then it's going to add itself to the list so after you have populated the list all you have to do now is you have to initialize a list that you can store all these values in so we'll just call result equals new arraylist and then we're going to pass it into the function as i said earlier so dfs res and then we want to pass in our root function so our root node not function root node is basically going to be just the node they give us if it happened to be null we're fine because at that point you have this null check and then when you return the uh result list it's going to be empty so you're fine so now after we've finished our recursion everything has been updated we just return our result list and that's it so let's go ahead and submit this code as you can see it was accepted and considering the fact that you could potentially at worst follow all the way down the left side you can have at worst in elements that have to be stored in memory should go all the way down to the far left so because that is the worst case your space complexity would be big o of n and your time complexity is also going to be big o of n because you have to iterate through every single node in the uh binary tree in order to complete this problem so if you have any questions let me know in the comments below and if there's any questions you want to see in the future please also let me know please take a moment to like and subscribe for future content thank you
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
98,144,145,173,230,272,285,758,799
1,071
Peace be upon you, my dear friend. How are you, Pasha? What are you doing? I hope you will be fine. God willing. Today we will explain together. If you have not solved the problem, of course you should go first and try it, and if you tried it and did not know it, then it is up to us to solve it together. You must give yourself the first chance to solve the problem. So that you don't depend on watching the episode all the time, you must think about it first with yourself. Ok, the first thing, in the name of God, we will start like this is to read the question. He tells you that he will give you black Rings toast perfectly, and after that he tells you the name. So the name consists of a group of T-Plus T-Plus T. Plus, in the end, it is about the second string, ABC. This is in your hands. The first string, the larger of the two strings, is ABC. This will tell you that the denominator is a group of figs. STR One will be if we said the result is equal to ABC. STR One is equal to AB. C which is ok, so an example with us tells you that the first string is EP, but the largest string you can find in my hand, Fayed, the two are IP, you will find that the first string is IP, this is ATS, the last one is no string. On Monday, you will return to him the syringe that is good. This is an easy matter. We will do it because the concertina is not large. We will try all the syringes, meaning that I will take these syringes, but let it be the small syringe. See if I want the benefits of Monday or not, because the IP is not at home. On Monday, I will see the ABC, but the ABC. I want Monday, so if you have lotion, ok, it will work. Continue. No, there is nothing useful. Continue after that. No. Okay. Yes, in the hands of Monday. Oh, then this is our first, which is IP. But I still haven’t IP. But I still haven’t IP. But I still haven’t finished looking at API. The API announcement is not in the circles. Monday. Prepare our strings. If it was just one more pip, I would have been able to introduce him to ABB, which is ABB, and YBEP, which was the second round at the time. It would have been the largest string, which was the ABB, and at that time it would also have been the third round, but this is in our case. This is a sweet little thing. Ok, this question or code will work. My first thing will be the hypnotist between the master and the first syringe. After that, after that, I said that I will have the current and something called my answer. It is what I was trying with. I mean, for example, this will be the first thing. It is empty at the beginning, and when the fur begins, it will take the first letter. For example, the first example is ABC, and the second string is ABC, perfect, ABC, and the second string is ABC. The Panthers of Al-Azhar are among them. Ok, this is what he will work Al-Azhar are among them. Ok, this is what he will work Al-Azhar are among them. Ok, this is what he will work on. It will remain empty if it is. Actually, this will still be considered okay. After that, we are done. I will add another letter to it, which is the letter B. It will also go down, so it will remain A. B. If this A. B., it will definitely be remain A. B. If this A. B., it will definitely be remain A. B. If this A. B., it will definitely be bigger than A. But as long as we keep going, what will we add to it? If it is at all, why will it be because it will definitely be bigger? From the previous one, because we are adding additional letters so that I do not have any other letters. Okay, as for what she is telling you, are you wasting money or not? What are you doing? We agreed that we have an SD that is equal to the set of the ones that are correct. Fine. So, I have something called less than. You can consider the one whose name is Viber. I did it. I said less than Suez. Then I will also have a T. The one whose name is Okay. Ok, when I finish this phone, I still have two possibilities. The first possibility is that it was really me. This notebook was mine, and I actually collected some for the name, so at that time I returned it. The second possibility is that it was actually me. Originally, it wasn't the type I wanted, it was something else. Let's say, for example, this is the EB series, which mine was the cinema letter, so I preferred to supply the C-Plus. Their C-Plus is equal. What happened when I came in the first place? I was going to supply the E-Plus EP, and the wail was gone, and I preferred to supply the C-Plus. Their C-Plus is equal. What happened when I came in the first place? I was going to supply the E-Plus EP, and the wail was gone, and I preferred to supply the C-Plus. Their C-Plus is equal. What happened when I came in the first place? I was going to supply the E-Plus EP, and the wail was gone, and when You get rid of the mobile phone, so if it is, we know that I can buy a bunch of asses, okay, after I finish, I mean, for example, the name came to me. We wrote some letters, or they are similar. I mean, but then again, what should I do? I started my house and the one whose name is here and I will see if Mr. What I have taken so far is less than the best medicines. Also, I consider it for the first string all along, then I will lose money, and the best thing is that. Yes, the last one is my answer, why, because I am not using letters, so the last one remains the largest one, and I don’t really letters, so the last one remains the largest one, and I don’t really letters, so the last one remains the largest one, and I don’t really want the largest one, but that’s it, if there is any comment. Or something, you can write me a comment and I will continue to answer you if you have any questions and I will see you, God willing, the next time will be fine. Peace be upon you.
Greatest Common Divisor of Strings
binary-prefix-divisible-by-5
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times). Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`. **Example 1:** **Input:** str1 = "ABCABC ", str2 = "ABC " **Output:** "ABC " **Example 2:** **Input:** str1 = "ABABAB ", str2 = "ABAB " **Output:** "AB " **Example 3:** **Input:** str1 = "LEET ", str2 = "CODE " **Output:** " " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of English uppercase letters.
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
Array
Easy
null
1,895
hi everyone welcome back to lead coding i am your host faraz so i have decided to make detailed solutions to the lead code by weekly and weekly contest on each weekend so that you don't have to go anywhere else for the solutions so if you're new here make sure to subscribe to the channel and please leave like because it helps my channel grow a lot so we are solving the contest 54 by weekly contest 54 and it is the problem number three basically we are given a grid which is of m cross n and in this grid we have to find a magic square okay we have to find the largest magic square and what are the conditions for a square to be magic so here the row sum that is 5 plus 1 plus 6 should be equal to all rows sums that is 5 plus 4 plus 3 which is equal to 2 plus 7 plus 3 and all the column sums should also be equal to that value here that value is 12. so we can see that all the columns 5 plus 2 is 12 1 plus 4 plus 7 12 all the rows 5 plus 1 plus 6 it is 12 and even these two diagonals 5 plus 4 plus 3 which is the right diagonal and the left diagonal which is 6 plus 4 plus 2 these both are 12 as well so we have to find such a square okay so let me just proceed with the solution now before moving forward if you want to get hired in the top tech companies like facebook google microsoft amazon then you need to check out interviewing.io you need to check out interviewing.io you need to check out interviewing.io you will practice realistic coding interviews with senior engineers working at these places they will give you detailed feedback on exactly what you have to work upon interviewing dot io has the largest network of experienced tech interviewers in the world so you can book an interview with as little as 24 hours notice and the best part is you don't have to pay until you get hired so i have provided the link in the description you should definitely go and check it out here what we can do is we can check it for every square first of all the one by one grids like this these are all magical so the minimum answer possible is one now we need to further explore that can we make a square can we have a magical square more than this size so let's say we are starting from this position okay we are starting from this position this is our starting point and from this starting point the first square that we are going to search is this one of course first it is magical then the second square will be covering this part a 2 cross 2 square okay then the third square would be a three by three square this the four square will be this four by four and they cannot be any other square larger than this size because we don't we cannot go down from here okay all right so this is how we are exploring for this particular column now let us move ahead and explore for more columns so we can start like if this is our starting point we can perform the same thing so this will be our starting square then a 2 cross 2 square then a 3 cross 3 square and a 4 cross 4 square okay and then again we can start from the next point from here and so on so let's say this is m and this is n we have how many starting points do we have so in total we have m cross n starting points okay these all could be starting points but for each starting points how many squares do we have so at max we can have m or n square the minimum of these two okay so for each of these starting points we can have m squares so this is how we can explore all the possible squares now how to check whether a square is a magic square or not so for that let us say we have this particular square now in this particular square we will have to calculate all the rows sums okay and all the column sums and of course the diagonal sums so this operation itself is going to take m cross and time okay we will have to calculate all the row sums it will take m cross n times then again all the column sums is going to take n cross m time so in total it will take m cross and time to verify if that square is magic square or not now how many squares in total do we have to verify so this is the time for verifying it is the first time for verifying one square now in total how many squares are we going to check now for that as we saw that each of these cells could be the starting point of square so each of these cells could be the starting point of square as well and so these and these cells so in total how many starting points do we have m cross and starting points okay now for each of these starting points how many square can we make so we can make in the first time we can make n squares for each of these running points here we saw that uh this is one square this is two this is third one this is fourth one so it is equal to n whatever is the minimum of m and n so in this case it is n so that is why in total we will have these many starting points and these many squares for each of these starting points and this is the complexity to verify if a square is magic or not so in total it will be in the question we are given that m and n both are of the order 50. so we can consider that these both m and n are equal so it will be one two three four five it will be m or n whatever raised to the power 5. and this will give us tle time limit exceeded we have to do something better than this so we are having these many squares okay accepted it will be 15 to 50 into 50 that is going to give us 125 into all right now somehow we will have to minimize the complexity of calculating or evaluating or verifying if a square is magic or not now for that we can use precomputation okay and how can we use precomputation let me just show you with the help of an example so earlier we were using a complexity of m cross n to verify a particular square now we are going to optimize it using pre-computation so let us say we have pre-computation so let us say we have pre-computation so let us say we have these summation we have the row sums okay so that means for each row we have the prefix sum so for that uh what i mean is 7 plus 1 8 plus 4 12 5 17 seventeen plus six twenty three now like this we have for the second row as well two seven eight plus six is fourteen eighteen and similarly for this row it will be one plus five six 10 plus 3 13 and 13 plus 2 15 and 1 3 10 13 and 17. so this way we have the row sums and we can simply calculate the summation of this particular row by taking the difference of this point and this point so 14 minus 2 which is equal to 12. similarly for this particular row we can subtract 13 and we can reduce one from it so 13 minus 1 is 12 and similarly 13 minus 1 it is 12. so we got all the row sums in just using big o of n okay similarly we can get the column sums as well performing the same thing we can keep another matrix which will keep the column summations and we can perform the same operation like this and that will also take big o of n time similarly we can keep diagonal sums for the diagonals and we can simply get in big o of n plus m time so overall the complexity of verifying whether a square is magical or not is big o of n so the overall complexity got reduced from big o of n raised to the 5 to big w of n raised to the power 4 and which is going to work so this will pass the time limits now you will have to make four extra grids one for the row sums okay one for the column sums one for the right diagonal and one for the left diagonal now let me tell you how to calculate the right and the left diagonals so let us say this is the grid which we have now you can start from this point and you can go like this till the end you can start from this point and go like this till the end you can start from this point go like this till the end similarly for here and for here as well so this is how you can make the left diagonals and similarly you can calculate the right diagonals so i think you can implement this i won't be doing the code it is very simple so this is it for the video if you like the video make sure to leave a like and do subscribe to the channel if you are new thank you
Largest Magic Square
minimum-number-of-operations-to-move-all-balls-to-each-box
A `k x k` **magic square** is a `k x k` grid filled with integers such that every row sum, every column sum, and both diagonal sums are **all equal**. The integers in the magic square **do not have to be distinct**. Every `1 x 1` grid is trivially a **magic square**. Given an `m x n` integer `grid`, return _the **size** (i.e., the side length_ `k`_) of the **largest magic square** that can be found within this grid_. **Example 1:** **Input:** grid = \[\[7,1,4,5,6\],\[2,5,1,6,4\],\[1,5,4,3,2\],\[1,2,7,3,4\]\] **Output:** 3 **Explanation:** The largest magic square has a size of 3. Every row sum, column sum, and diagonal sum of this magic square is equal to 12. - Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12 - Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12 - Diagonal sums: 5+4+3 = 6+4+2 = 12 **Example 2:** **Input:** grid = \[\[5,1,3,1\],\[9,3,3,1\],\[1,3,3,8\]\] **Output:** 2 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 50` * `1 <= grid[i][j] <= 106`
If you want to move a ball from box i to box j, you'll need abs(i-j) moves. To move all balls to some box, you can move them one by one. For each box i, iterate on each ball in a box j, and add abs(i-j) to answers[i].
Array,String
Medium
1329
929
uh hey everybody this is larry this is in day 27 of the september lego daily challenge hit the like button to subscribe and join me on discord let me know what you think about these problems so today i am in uh the what city of the beach city of puerto mao uh sullivan portugal so i am just hanging out uh let me know what you think about that uh yeah okay so today's problem is unique email address so yeah i have let's see every email may contain point dot or plus okay so there's a local name and a domain name and the domain okay um i mean i guess this is like what happens in gmail right so that's kind of interesting yeah we can just um we can just basically uh what they call normalize each email and then after normal normalizing it we just put in a set and that should be good enough i believe so then here we maybe do something like for uh for email in emails uh let's just say you unique add email and then we return the length of unique and of course unique is going to be just a set uh oops i mean normalized as we said alright and of course you have to write normalize and then all right is it just a regular yeah okay so there are two parts so you need to apply directx if you like but um but let's see i want to split the email on um the add design first so then now what would we have read the vocal and the domain name is what they call it okay so the domain name what is the domain or like what is uh do you want to be valid i think that's something that i haven't made because they give us all these rules we have to show or do we have to check whether um they're valid like okay but there's no plus or weird signs on the other ones let's actually test that i'm just curious whether they have stuff and maybe don't complain on the router that's actually weird as well but um and i just woke up so maybe my spirit is well oh that is terrible i'm thinking of another function maybe yeah you have to do it like that okay so this is rated input okay so i guess it just doesn't matter for the thing maybe that's my interpretation right now so okay so we just have to normalize to the local name not the domain name and local name we basically get the first index of well the two things one is that we get the first index of plus and ignore everything in afterwards so yeah i just got first half i don't know i mean it's tough that's good um let's just say if you can logo and we do this and i think you can actually uh plan with it to it um and then just ignore the hat a second just and then the other thing is just replacing periods with nothing right so then now you can return you can either return back i don't know i guess it'll be good to kind of return like this but so that's uh yeah you could return other things as long as you could even return the tuple for example but i think that'll be okay so yeah so that's am i happy here well that's at least validate what we think is writing stuff kind of you know go by these numbers which may or may not be true so yeah okay so this is this what we think this should be i think this should be what we think it should be so i think i'm happy here so let's give it a quick submit or a slow submit with it whichever you like them make sure that i got out of there got rid of the output and then that give us some it oh whoa oh i forgot about the wait hmm what that's weird well this should be a easy one but i guess i messed up in a case which input is it i messed that up maybe this is two i think maybe that's why but this is one writing yeah whoops that's what happened when you don't know your helper your second parameters uh because i think that okay let's give her something now and it looks good okay cool yeah man maybe i should hook this up i forgot if it means that you need to break into end parts or you just stop on any things but yeah um well we process these gmail once and each of this is then linear you know because we go for the string ones so this is going to be linear time linear space and that's all i have for this one um yeah i feel silly making that mistake though but that said yeah recently everybody's i don't know mystic quote but to be honest right now like i said i'm in the beach city of puerto maus i think i'm just ready to get out of here and rushing a little bit and stop taking my time but uh yeah you know uh anyway stay good stay healthy to good mental health i'll see you later uh yeah only few more days left go bye-bye
Unique Email Addresses
groups-of-special-equivalent-strings
Every **valid email** consists of a **local name** and a **domain name**, separated by the `'@'` sign. Besides lowercase letters, the email may contain one or more `'.'` or `'+'`. * For example, in `"alice@leetcode.com "`, `"alice "` is the **local name**, and `"leetcode.com "` is the **domain name**. If you add periods `'.'` between some characters in the **local name** part of an email address, mail sent there will be forwarded to the same address without dots in the local name. Note that this rule **does not apply** to **domain names**. * For example, `"alice.z@leetcode.com "` and `"alicez@leetcode.com "` forward to the same email address. If you add a plus `'+'` in the **local name**, everything after the first plus sign **will be ignored**. This allows certain emails to be filtered. Note that this rule **does not apply** to **domain names**. * For example, `"m.y+name@email.com "` will be forwarded to `"my@email.com "`. It is possible to use both of these rules at the same time. Given an array of strings `emails` where we send one email to each `emails[i]`, return _the number of different addresses that actually receive mails_. **Example 1:** **Input:** emails = \[ "test.email+alex@leetcode.com ", "test.e.mail+bob.cathy@leetcode.com ", "testemail+david@lee.tcode.com "\] **Output:** 2 **Explanation:** "testemail@leetcode.com " and "testemail@lee.tcode.com " actually receive mails. **Example 2:** **Input:** emails = \[ "a@leetcode.com ", "b@leetcode.com ", "c@leetcode.com "\] **Output:** 3 **Constraints:** * `1 <= emails.length <= 100` * `1 <= emails[i].length <= 100` * `emails[i]` consist of lowercase English letters, `'+'`, `'.'` and `'@'`. * Each `emails[i]` contains exactly one `'@'` character. * All local and domain names are non-empty. * Local names do not start with a `'+'` character. * Domain names end with the `".com "` suffix.
null
Array,Hash Table,String
Medium
null
1,920
Do Handed over to Lakshman English Video Gyan Tree Another problem is this Zoom permission Subscribe button more Return Do Subscribe Bluetooth on Inch 340 DRR AF Subscribe to Quid Element Video subscribe our So let's see how to this problem should not give the Examiner wash 500 to 1000 subscribe half of it Jai Hind Sir Jeevan Harry and Will Benefit Silver 4220 102 numbers were there because of this these voice messages indexes no veer and subscribe 90 subscribe the channel again for first Indian time lage electronics and Sonu Nigam Services to AIIMS of Measurement Thursday Subscribe Indian President Subscribe Cr Ki Nav Bihar at Third Position 100 What is 300 ft Life in Terms of Service and Swift only Verses Minute Subscribe Loot Element subscribe and Sunao Left Side Office Loot were First Quarter Thursday A Vector Answer Sovan has subscribed National Usha Martin Adhere to that and doing such cases related to answer this question The name of that of norms of pipe is Sudhir and the answer is Let's check that Sudhindra has lived in the state Typing Mistake Ko Agar Hair Loot Ki Surgical Servi Subscribe To Ki A
Build Array from Permutation
determine-color-of-a-chessboard-square
Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it. A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**). **Example 1:** **Input:** nums = \[0,2,1,5,3,4\] **Output:** \[0,1,2,4,5,3\] **Explanation:** The array ans is built as follows: ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\] = \[nums\[0\], nums\[2\], nums\[1\], nums\[5\], nums\[3\], nums\[4\]\] = \[0,1,2,4,5,3\] **Example 2:** **Input:** nums = \[5,0,1,2,3,4\] **Output:** \[4,5,0,1,2,3\] **Explanation:** The array ans is built as follows: ans = \[nums\[nums\[0\]\], nums\[nums\[1\]\], nums\[nums\[2\]\], nums\[nums\[3\]\], nums\[nums\[4\]\], nums\[nums\[5\]\]\] = \[nums\[5\], nums\[0\], nums\[1\], nums\[2\], nums\[3\], nums\[4\]\] = \[4,5,0,1,2,3\] **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < nums.length` * The elements in `nums` are **distinct**. **Follow-up:** Can you solve it without using an extra space (i.e., `O(1)` memory)?
Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern.
Math,String
Easy
null
20
welcome to lead codes blind created 75 where i'll be solving the top 75 lead code questions this problem is called valid parentheses and it's a standard problem you'll see given a string containing just the characters open parentheses close parentheses open squiggly bracket open bracket close bracket blah determine if the input string is valid and it's valid if all the open brackets are closed by the same type of bracket one other thing to note is open brackets must be closed in the correct order so like this would be true because they all have matching close brackets but note that this one would not be true because the open parenthesis or the open bracket is followed by a closed parenthesis and that in this case shouldn't count it needs to be followed by the correct bracket so that actually makes our algorithm a lot easier usually with these problems what you'll do is build a stack of open parentheses or brackets and if you can match the top stacks with the close bracket then you can just pop that off and if the string is valid at the end the stack should be empty because we've matched every open bracket or parenthesis with its closed bracket of parenthesis so what i'm going to do is build stack here oh let's first close this and build a stack and i'll just be an empty list and what i'm going to do to make our coding a little easier is create a lookup table and this is just going to be a dictionary matching the different close brackets to one another so for close parenthesis i'm going to match that with an open parenthesis so bear with me this might take a little bit of time so close point oops squiggly line this and that does that look good i think so all right and that's just to make our code a little bit easier you don't need this but otherwise you'd have to have a lot of other fl statements so for every parentheses in our string first we're going to check to see if it's a open parenthesis or bracket so if p in lookup and notice that these are the values then we'll simply append to our stack otherwise it's a closed parenthesis or bracket right and if that's the case we need to make sure that the top stack equals the lookup key values same parentheses basically make sure the types are the same so first thing we need to check is make sure this there's something on the stack if stack and this lookup values matching parentheses which is going to be a open parenthesis or bracket if that equals the stack whatsoever on the top stack then pop it off because we've matched together otherwise if we can't match this scenario like say there's no stack and it's a closed parenthesis then we've already figured out that it's not valid so we'll just return false there finally once we've gone through our entire loop our stack should be empty so just return whether the stack is an empty list or not if it's not then this will be a false so let's run that look up typos there i'm just going to submit that because i'm pretty sure this will work and there we go um that's really it i looks like i've used a ton of memory that i would have liked but i mean whatever this is basically the standard solution so thank you
Valid Parentheses
valid-parentheses
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. 3. Every close bracket has a corresponding open bracket of the same type. **Example 1:** **Input:** s = "() " **Output:** true **Example 2:** **Input:** s = "()\[\]{} " **Output:** true **Example 3:** **Input:** s = "(\] " **Output:** false **Constraints:** * `1 <= s.length <= 104` * `s` consists of parentheses only `'()[]{}'`.
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
String,Stack
Easy
22,32,301,1045,2221
121
today we're looking at lead code number 121 it's a question called best time to buy and sell stock and so here we are given an array of prices where prices index i is the price of a given stock on the ith day and what we want to do is we want to maximize our profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock and we want to return the maximum profit we can achieve from this transaction and if we cannot achieve a profit we just want to return zero okay so here example one we see we have days of prices the days array which is the indices that are the days and the values of the prices so here we have a price of seven one five three six and four and we can see that if we buy on day two which is this one and sell on day five which is the six then our maximum profit achieved from this input is going to be five here example two there's no way to make a profit because there's no point we can buy where later on we can sell at a profit okay so now there's two ways to approach this okay we're gonna go through a brute force uh approach to solving this and then we'll find we'll look at a more efficient uh way of solving this so here we have seven one five three six four okay so we're going to have an array 7 1 5 3 6 and 4. so now one way we could approach this is we can go ahead and take a look at this seven here and look at all the numbers in the rest of the array and figure out what is the maximum profit here it will be zero because if we take this seven here there's no point we can sell this in the rest of the array where we're going to turn a profit all the numbers are smaller than seven we'll move on to the next number here at one we can sell it at five for a profit of four we can sell it at three for a profit of two we can sell it at six for a profit of five and we can sell it at four for a profit of three so our maximum profit will be five but then we'll have to go through the rest of the array we have to go here at five and check all these numbers here three and check all these numbers so this does work but the problem with this is that the run time is quadratic it's not very efficient we're going through these numbers twice every iteration we're going through the entire array so what's another way we can approach this well we can take a two-pointer approach well we can take a two-pointer approach well we can take a two-pointer approach that's going to be a little more efficient okay so let's say we have a buy index and we'll set that to i and we have a cell index and we'll set that to j okay and so now here we have i and we have j and we want to check is the value of whatever is at the by index minus the cell index is that greater than or equal to zero okay if it's not then what do we want to go ahead and increment our cell index okay now we're going to check again is the value of the buy index minus the value at the cell index is it greater than or equal to zero okay uh it is so when that happens what do we want to go ahead and move our cell index to where our buy index is okay and now we want to continue on we're going to increment this i over here and we're going to check is it greater is the value of this of the buy index minus the cell index is it greater than or equal to zero um it's not and so what we're going to do now is we're going to update our profit we have a profit variable here we'll set it to zero and we're going to get the maximum of the prices at cell index minus the prices at buy index okay we'll just say we'll call this price and then our profit is just going to be our max of whatever is currently in our profit and our price okay and then we will go ahead and decrement our buy index and we'll do the same thing over and over again until we get out of the array okay so let's think about time and space complexity taking this approach well if we think about it how many times are we traversing over this array we're only traversing over at once we're not doing any duplicate traversals so relative the input size our time complexity here is going to be linear okay what about space are we creating any new space or extra space relative to the size of the input i don't think we are because we have a profit variable that we're updating as we go through the array but we're not storing all those values okay so then our space complexity here is going to be constant okay and if this still doesn't make sense let's jump into the code i think it'll make a lot more sense once we jump in the code so here what we want to do is we want to go ahead and create a variable we can call it the cell index and we're going to set this to prices dot length minus one okay and then we'll set a profit variable and we'll set it to zero okay now we're going to create a for loop so we can say four let by index equals prices dot length minus one and as long as our buy index is greater than or equal to 0 we're going to decrement that by index okay now what we want to do is we want to store the values at the buy index and the stell index in a variable just to make everything cleaner so we'll say let buy val equal prices at buy index similarly we're going to do let cell valve equal prices at cell index okay and now what do we want to check if at by val okay if we bought it at wherever that element is if that minus the cell valve is less than uh zero okay so what we're checking here if this is our buy val and this is our cell valve okay we want to check if our buy minus our cell valve is less than zero actually we want to check if it's greater than zero greater than or equal to zero okay if it's greater than or equal to zero then what do we want to go ahead and increment we want to set our cell index to our buy index okay else what do we want to update our profit so we can go ahead and set our price and this is going to be our cell valve minus our bivalve and then we update our profit so we can say profit it's going to equal math.max of profit math.max of profit math.max of profit and our price okay and then we'll just return our profit and the reason this is confusing is you have to remember that because we want the negative value so that's why we're doing cell vowel minus by val because if we do it the other way it's the price will be negative which is not what we want okay so we can go ahead and run that and we have success okay so that is leak code number 121 best time to buy and sell stock it's a much more efficient way of doing it we're using two pointers versus the quadratic solution and it's a good question to be familiar with okay hope you enjoyed it and i will see you in the next one
Best Time to Buy and Sell Stock
best-time-to-buy-and-sell-stock
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock. Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`. **Example 1:** **Input:** prices = \[7,1,5,3,6,4\] **Output:** 5 **Explanation:** Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. **Example 2:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** In this case, no transactions are done and the max profit = 0. **Constraints:** * `1 <= prices.length <= 105` * `0 <= prices[i] <= 104`
null
Array,Dynamic Programming
Easy
53,122,123,188,309,2138,2144
934
hey what's up guys chung here again so this time I want to talk about another lead called problem number 934 shortest bridge here so let's take a look you're given like a 2d binary array basically consists of either 0 or 1 and there are two islands in this 2d binary array here so an island is like it's connected which is one island is consists of once right and now you want to connect those two islands together by changing some zeros to once returned the meaning the smallest number of zeros that must be flipped right so what does it mean right so for example it gives you like several like simple examples here let's say for example this one let's say there's a 0 1 here 0 1 and 1 0 right so there's a 2 island 1 &amp; 2 1 0 right so there's a 2 island 1 &amp; 2 1 0 right so there's a 2 island 1 &amp; 2 right but they're not connected right because the island is only connected by four directions right so in order to connect those two islands you need to flip either this one or this one to one then these two islands are connected right same thing for this one 1 0 1 right so for this one how many like zeroes you need to flip in order to connect these two islands - order to connect these two islands - order to connect these two islands - right so you flip this one or this one doesn't really matter right but there are they're all the same because they're both they're all like two flips right and now let's take a look at this interesting one here so basically this is a 1 right 1 0 1 so there are two islands the first island is a very big one on the on outside and the second element is very this very small one in the middle right so to ask you to find out the minimum right so for this one what's the minimum of this one it's a 1 right so you can either flip this one or this one then you can connect those two islands right so every time you see a smallest something with like a graph you know you need to use the by odd sorry the breadth-first search which is sorry the breadth-first search which is sorry the breadth-first search which is BFS right but in this case there's a little bit difference of the BFS right so our approach is gonna be since it's guaranteed there are only two islands right in this graph here so what we will do is so first we will okay the first time when we see a one here right we will basically traverse all the other area of the first island right which rivers all the area in the first island and then we do what and then we basically we will mark those islands to a like to a value basically in my case I mark off them to my two minus one right so I might mark often 2 minus 1 and then what I would do and then from there going forward I'm going to basically I'm gonna use all those areas all those errors in element 1 as another starting point of a BFS search right basically you can think of like this with mr. with everything we have fine for this island we're trying to expand this island right basically we just use this like as a starting point and we continue our breadth-first search and we continue our breadth-first search and we continue our breadth-first search until we sees another one then we know okay that's the domain that basically destroyed is the distance between the first islands and the second island okay I don't know if you guys understand that so basically to step of breadth-first search I'm sorry the first breadth-first search I'm sorry the first breadth-first search I'm sorry the first one doesn't matter the first search it could be either PFS or DFS right the first the purpose of the first Traverse is just to traverse all the other nodes for the first element for the first island and we'll mark those two miners when whatever value you want and then we'll meanwhile we'll also keep this all those nodes of the first island into a queue and we'll use that queue as a starting point for second phase BFS okay cool so let's try to coat this thing right and okay so first I'm gonna have like two range right length for the two dimensions right and then I'm gonna have answer here and that's gonna be our answer and then directions right directions of four directions right like always and like always so let's see what we come to do so for the first time okay sorry let me finish this I in range M right and then put J in range and right so the first time we see a 1 here right i J okay if the if this thing is one we will use this one basically we see we thought we find the first island right and then we'll mark this first island and let's see okay so I'm gonna use a scene here set so we saw this thing right so we're gonna I'm in this I'm gonna use a cue to do the Traverse of the first island and EQ inj right that's our starting point and then we just first Adam first island okay so kill here and we're going to add the scene to the at current coordinates the senior and since if we for the first traverse we just knew we only want to traverse the all the entire lens it doesn't really matter what sequence we use here we so I'm gonna just use this and so while he'll write for okay aren't I aren't J goes to a DQ sorry pop left okay and then for direction in directions right then new I was to turn I plus t0 and new J current J plus t1 right so the boundary track here as like always and what and we only cares about the ones right because we want to we only want to find the audio island note for this for the first island right so it's going to be new I knew J right and this thing is equals to 1 right then we had all right so now so once this the once the first for loop is finished right will have basically we have traversed basically we have all the added the ones stores in this same set right and then like I said so basically it is the first step right it's to traverse right traverse first island right and once this while loop is finished like it in the first island has been traversed and then now expand right spend the first island until we see it's like a once here right and then okay so like I said since we have the first I island stores in the scene here right so what do we do well we do a queue right so we're gonna use this the first island as a starting point right as I seen here right basically we're gonna assign this all the nodes in this like the queue here so that we can use be using our we're gonna use that as a starting point all right and so here we'll be using you know what I'm gonna remove this theme here so here I'm gonna have a distance here where you can level all right Wow q I mean we just keep doing the breadth-first search right all right breadth-first search right all right breadth-first search right all right that's how it with a breadth-first that's how it with a breadth-first that's how it with a breadth-first search you can also I mean save the latter distance along with the coordinates but I find this thing is easier for me at least so I'm gonna stick with this approach here all right J basically the same thing here right I'm gonna copy it okay I'm gonna copy whatever we have Bob they're basically using the same logic here instead the only difference here we're gonna have a for loop so that we can basically increase this among it insist distance in the end all right okay so we have that and then which to a for loop right T in okay I'm going to copy this thing here actually so yeah I don't want to rewrite things over and again and then and so now okay so just the thing to be noticed that for a second for the second loop here we're not only limited to the wine here right because our purpose is to find one so all we need to know to do is the just to do an that not has not been visited right and new I and new J not in seen right not in seen because we're still keep a rim keeping this scene here right then speaking of that I forgot to add this singer here Jay which means I need to do the same thing here okay so that's the template up for the breadth-first search and how when do we breadth-first search and how when do we breadth-first search and how when do we stop right basically we do this right if current I and sorry if the port not for a sorry he goes to one right then we simply return the distance minus one so but one thing to notice here since the first I the first island we also have once right and since we will just keep everything in the scene here and every time when we start around from the first I from the first or actually no what we can do this you know you can do this yeah cuz I was thinking like I said I was going to a flip I mean mark those the previous island to be one right I'm sorry to from mine from 1 to minus 1 so here I can make sure okay every time when I see this the next one I know I saw the that the second island right but instead of flipping those things we can use the distance here right because we know all the added order yet the ones in the queue for the first island will have distance 0 right so I can we can simply add a distance here if distance it's greater than 0 and we saw another one right then we know ok so this is our distance and oh I think that should just work let's see oh sorry end all right submit alright seems like we have some infinite loop here let's see since oh I know so here I guess here basically yeah I think we need add one more condition here and this thing is 1 and has not been seen before basically same thing here alright and then it should work try to run this thing alright cool so it works all right past all right and just to recap real quick right basically when we see the first one right we first to either BFS or DFS or whatever Traverse you prefer we just need to find out all the elements or all the other ones which belong to the first island right and then we add that thing for me I added to see in here because the later on will also be continued using this scene here right and that's why I thought ok why not I just used the scene to store all those things right and I started to see in here and then next I'll be using this other ones in the first element as the starting point as a starting point of the second BFS search which will be you can think of it like expanding the first island right and then I initialized our queue with our with Audia the notes basically are the ones from first island and I do a BFS I expand from there right and here I'm only I don't care about if it's zero or one I just need to keep expanding right because comparing with the first one I only care about once here but here I don't care I just want to keep expanding the first one until I see another one where and the distance is greater than zero right the distance two equal to greater than zero is for to distinguish the ones that belong to the first island right and then we I just returned the distance minus one who I think that's it for this problem yeah okay yeah thank you so much for watching the video and I'll see you guys soon thank you bye
Shortest Bridge
bitwise-ors-of-subarrays
You are given an `n x n` binary matrix `grid` where `1` represents land and `0` represents water. An **island** is a 4-directionally connected group of `1`'s not connected to any other `1`'s. There are **exactly two islands** in `grid`. You may change `0`'s to `1`'s to connect the two islands to form **one island**. Return _the smallest number of_ `0`_'s you must flip to connect the two islands_. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 1 **Example 2:** **Input:** grid = \[\[0,1,0\],\[0,0,0\],\[0,0,1\]\] **Output:** 2 **Example 3:** **Input:** grid = \[\[1,1,1,1,1\],\[1,0,0,0,1\],\[1,0,1,0,1\],\[1,0,0,0,1\],\[1,1,1,1,1\]\] **Output:** 1 **Constraints:** * `n == grid.length == grid[i].length` * `2 <= n <= 100` * `grid[i][j]` is either `0` or `1`. * There are exactly two islands in `grid`.
null
Array,Dynamic Programming,Bit Manipulation
Medium
null
1,833
Hello friends today I'm going to solve liquid problem number 1833 maximum ice cream bars in this problem we are given an area cost and an intensive value coins so the cost the value at each index I in the cost error represents the number of coins that is required by the ice cream and coins is the total number of coins available so we can only use maximum of coins to buy ice cream and what we need to do is we need to maximize the number of ice creams that could be bought using these integer value of coins now let's see how we could solve this problem so using a Brute Force solution what would we do we need to buy the maximum number of ice cream right which means that we need to buy the maximum buy the ice creams which have the least cost so we need the ice creams that uh cause the least so which are the ice creams that cost at least let's arrange it in an ascending order so we have something like this when we arrange it in an ascending order so this is what we have and this is still the value the cost of purchasing the this ice cream the cost of purchasing another ice cream is this much so each ice cream cost these much values right now what are we given is we are given seven coins so since these ice cream costs only one coin Which is less than seven right so we are able to buy this ice cream now the available amount which is the available uh number of coins after we purchase this which will be minus the uh the cost of this ice cream right which is equals to six the available remaining coins is equals to six now since uh one is also less than six we can buy that ice cream now the remaining amount is equals to five so we bought this ice cream the remaining amount is five we could also buy this ice cream so what's the remaining amount which is equals to three right so we bought this one and the remaining amount is equals to three now three is equals to three so we have three coins and this ice cream cost three so we can buy this one so we bought this and now remaining amount is equals to zero so since now the value of coins that we have remaining is equals to zero which means that we can no longer buy any ice creams right so how many ice creams were we able to buy where we were able to buy four ice creams here so this is one way to solve the problem by sorting the cost which would uh take a Time complexity of oauth and log of n and the space complexity is log of n because uh sorting itself takes log of n time space complexity in JavaScript now another way to solve this problem is by using frequencies so let's try solving this problem using another method so what do we need is we need to create an array of frequencies so what is the maximum length of the array that we need to create of course we have uh coins uh ice cream that cost one that cost two that cost three coins and that costs four coins right so what do we need is we need to create a frequency array I'll just write it c f and each of the index one will have a frequency of what two because we have two ice creams that cost uh one right so this will be a value too and the index 2 would be equals to 1 index three would be equals to one again foreign the highest value we have is index 4 which is equals to again one so this will be our error but we know array is always zero Index right so we will all also have a zero indexed uh array frequency array whose value will be equals to zero and now what we need to do is since we already know we already have the array we are gonna Traverse through the array so we are gonna start from the first index until the last and we are only uh taking the area value up to 4 because we don't need to calculate for five or six because there is no ice cream of that cost right so we do not need to create the frequency for that one so since we have the frequency error now we Traverse from the very first and since the very first index is zero whose value is equals to zero so we don't have to do anything so we keep on continuing now one once we reach this index uh the cost is equals to one right and the coins that we have right now is equals to seven we have not used our coins so far so total coins we have is seven and the cost is equals to one so one is less than seven right and also are we able to buy all the ice creams that cost one coin well yes we are able to buy all the ice creams that cost one coin right because two um the frequency of frequency is equals to 2 right which means two ice creams cost one uh coin and we have uh the total amount resulting amount would be equals to 2 times 1 which is equals to 2 right so since our coins number of coins total coins available is seven which is greater than two so what we'll do is we can buy these ice creams so now our result thing uh coins is equals to six Now we move on to the next value here and what we see the cost is equals to 2 and is 2 greater than or six no it's not so since 2 is less than 6 which means that we can still buy this ice cream and since we its frequency is one so we are able to buy it we subtract it by 2 which is the cost of the ice cream and the remaining amount is equals to four now what we do is we buy we look at this value it's still um for 4 is still greater than 3 which means we buy this ice cream as well and our remaining value is now equals to one now we move on to the next one and we see that one which is the remaining coin we have is less than four which means that we cannot buy this ice cream and what we do is we break from the loop that is we stop here because we know any other uh values would also have been greater than one greater than four which would obviously be greater than one because 4 is greater than one so we stop right there and then we count the frequencies which is equals to four so we are able to buy for ice creams so this will be our result now let's try to write our code so n is the length of the array and let us find the maximum value of the cost so once we have the maximum value that will be the limit that is the size of our frequency array so cost frequency equals to of size M plus 1 and we will fill all the values with zero and what are we going to do is now we fill the frequencies out so once we have all the frequencies uh we Define our result that is the number of ice creams that we can buy equals to zero initially and then we iterate through each of the values in the cost frequency so that's I equals to zero I is less than or equals to m I plus we could just start from one because we know uh 0 would always have like zero frequency it'll always have the value zero so we don't need to do that and it's equals to M because m is the last index here because M here is the maximum value which is equals to 4 will be the last index so that is what we need to do here and now if um the value the frequency is equals to zero then we just keep continuing because we don't have to do anything and if the number of coins we have available is less than the cost of that ice cream that we just break from the loop we are not able to buy any more ice creams so we get out of the loop and then what we do is we return our result if not what we do is we calculate the number of ice creams that we could buy so count equals to math minimum value of either we can buy all the ice creams or we could only buy based on the uh the coins that we have if the coins is um if so what we do is we take the division that is we divide our coins by the number of by the amount cost of the ice cream this would give us the number of ice cream that we could buy and this is the frequency of the ice creams that we could buy so this means that we could buy if the number of coins is less than we would get the minimum value from this one else we will get the value from this one and once we have the count that is the number of ice creams that we can buy so we could just add that count to our result and we also um since we have bought the ice cream so we reduce from our resulting coins total coins the cost of buying these many ice creams it would be the value I now let's try to run our code okay all right foreign because we are using an array here and the time complexity would be this is of and time complexity and this hair is off and this here is of M10 complexity so the total would be of M plus and time complexity and the space complexity would be of n okay we get caught the wrong answer here and why is that okay so what we need is in JavaScript we always need to uh part we always need to do this thing here else we could get a floating integer value because JavaScript is not type specific cool so hope it was helpful
Maximum Ice Cream Bars
find-the-highest-altitude
It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible. **Note:** The boy can buy the ice cream bars in any order. Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._ You must solve the problem by counting sort. **Example 1:** **Input:** costs = \[1,3,2,4,1\], coins = 7 **Output:** 4 **Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7. **Example 2:** **Input:** costs = \[10,6,8,7,7,8\], coins = 5 **Output:** 0 **Explanation:** The boy cannot afford any of the ice cream bars. **Example 3:** **Input:** costs = \[1,6,3,1,2,5\], coins = 20 **Output:** 6 **Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18. **Constraints:** * `costs.length == n` * `1 <= n <= 105` * `1 <= costs[i] <= 105` * `1 <= coins <= 108`
Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array
Array,Prefix Sum
Easy
null
1,094
Ki Kinnar Information Patna Interesting Problem Hai Main Ister Content Information About Item Number Passengers Patient Topic Hai Next 9 News 200 Shopping Radhe Maa The Work Of Bane Vishal A Main Harish Kumar Sauveer Shut down the hotspot till retrograde and Which was their poetry duplicate loot 9483 hotspot on that aap inko art them mundhe sutriya luck plus app hui hari mirchi confirm a and tell hotspots tree picture wali 102 - learn so kitna dhondoon modi up ki - learn so kitna dhondoon modi up ki - learn so kitna dhondoon modi up ki comedy aa ko Well, around the loot, Amrita, newly appointed here, took them to - 200 for newly appointed here, took them to - 200 for newly appointed here, took them to - 200 for one man, 10 plates here, left the shot besan setting on and our circle and like this, Pakistan green field under using it on a practitioner website, ok sir. No problem variation of the calling all problems on recent items for quiet problem 911 meeting a big cardamom problem solve all your computer and legal in this testing center treatment shooting cancel it used to do they morning g a newspaper and happened hybrid-2 through every a newspaper and happened hybrid-2 through every a newspaper and happened hybrid-2 through every Element Half Hour Missionary Triple Attack From This Sunao To Ka Simran Video In Hindi Superhit Ho Jhaal Ab Soayenge Ulte-Sidhe Ko Ajay Ko A Full Of Shaitan Digital Multimeter Spotted At That Edge India Poore A Good Night Kavya Palak Cystitis loot - Good Night Kavya Palak Cystitis loot - Good Night Kavya Palak Cystitis loot - deposit start murderer a now we will cut it you r a am amazed e I have now half felt question was paralyzed ok 110 you are simple or morning and evening meeting yesterday morning that his father Krishna Radhe of Delhi
Car Pooling
matrix-cells-in-distance-order
There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west). You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them up and drop them off are `fromi` and `toi` respectively. The locations are given as the number of kilometers due east from the car's initial location. Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_. **Example 1:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 4 **Output:** false **Example 2:** **Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 5 **Output:** true **Constraints:** * `1 <= trips.length <= 1000` * `trips[i].length == 3` * `1 <= numPassengersi <= 100` * `0 <= fromi < toi <= 1000` * `1 <= capacity <= 105`
null
Array,Math,Geometry,Sorting,Matrix
Easy
2304
528
Hello hello everyone welcome to my channel today is the day 5mm problem is random pick distinction direct problem statements governor-general of weights which governor-general of weights which governor-general of weights which describes of the crescent index of your tips for example of baghwa yadav and the return of the rebel two 500 calls 100 Index of Life and Property Subscribe 1234 nd Constraints of Life But Slang 1054 And Values ​​And Got Into Power Five 1054 And Values ​​And Got Into Power Five 1054 And Values ​​And Got Into Power Five And Up In The Can Call At Most Powerful Times So Let Me Explain With Very Custom Example A Grade Three 500 21 Subscribe From Going To The subscribe The Video then subscribe to A Total Frequency and Total Votes and Total Web Ki Hiss 1052 Calculate the Pick Probability of Creation of Individual Visits Way 205 Button Respectively On Nov Vighn To Acid They Want to Talk to the Number One Class Fifth Class 9 Ek message mil jaayenge a random number in answer hai front mila is show random number will gather next point of from times will give asik ki vriddhi ki prabal numbers between 0 20000 from closed simply advance subscribe problem solve width numbers from ranges like this 60045 youth 80 Subscribe Now Two Numbers From One To Two A Power Rangers 10021 Will Be Na Dhir V Subscribe Now To The Five And A Corresponding Indices 2nd September Maze From Random Number From 3253 25 This Point To Three Lines From One To Two To Calculate Total 10 years ago 0 210 ranges and is getting from one to two and 100 ranges from three 500 ranges from 60 karenge is vansh veer 1000 simple user interface and tried to where is the country in which will return for implementation subscribe and subscribe for the Saint from i option 212 eye lens 10th don't like and i plus vijay simply just i request to cfir - one subscribe and subscribe the channel solve will - one subscribe and subscribe the channel solve will - one subscribe and subscribe the channel solve will avoid 120 first number generator random number directly from nude art c Faint v0 only two sw ne in the garhwal development waits in uncategorized on one to receive a total of soil water and subscribe plus that this f5 victims get the target will just returned at index is a continuous and kashmir will always love oo one Security skating come point and discharging it's correct for example one latest hour custom example2 that I on custom example2 hair and yes also running anti smart reasoning and where getting so let's time tower solution 98100 per solution fennel time complexity subir win from all the whole are switch off band solution of this cream and searching notice like share and like increasing and not from increments obscured by 102 other user based on the final research sorry for brain research 816 is to calculate the target after death will be applied one response so far been That Left 10 And Right Induct The President - Way Right Induct The President - Way Right Induct The President - Way Subscribe And Difficult Subscribe To Was Done To And Wife Effective Shift Medical Store Target And Simply Return Meet Other Wise With Sacrifice Of Mid Is Taken Target Of Bus Update Next Point To Plus One Others Will Reduce ride point to security love that I just Swadeshi Jagran - Research that I just Swadeshi Jagran - Research that I just Swadeshi Jagran - Research Binary Search Web Solution to begin the tower test cases in details and compiling edition running 1658 research solution is a member of accept software time complexity steel the time complexity top this time complexity of creation of Him Ki And Now Time Complexity Of Paying Taxes A Time Complexity Of Sentences Of Long And Aa Log In Such Situation Is Active And Passive Voice Mail Subscribe To Better Singh Like And Please Like Share And Subscribe To My Channel Bell Icon For Getting Notification New Video
Random Pick with Weight
swapping-nodes-in-a-linked-list
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index. You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`. * For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`). **Example 1:** **Input** \[ "Solution ", "pickIndex "\] \[\[\[1\]\],\[\]\] **Output** \[null,0\] **Explanation** Solution solution = new Solution(\[1\]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. **Example 2:** **Input** \[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\] \[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\] **Output** \[null,1,1,1,1,0\] **Explanation** Solution solution = new Solution(\[1, 3\]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem, multiple answers are allowed. All of the following outputs can be considered correct: \[null,1,1,1,1,0\] \[null,1,1,1,1,1\] \[null,1,1,1,0,0\] \[null,1,1,1,0,1\] \[null,1,0,1,0,0\] ...... and so on. **Constraints:** * `1 <= w.length <= 104` * `1 <= w[i] <= 105` * `pickIndex` will be called at most `104` times.
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
Linked List,Two Pointers
Medium
19,24,25
1,040
hi everyone I'm Jack I'll be had a good night today let's look at this new question 10:40 I thought about these questions 10:40 I thought about these questions 10:40 I thought about these questions for a long time and obviously identify myself I read on me some other articles on the web and I finally figured out what is going on so let's take a look so this problem says we're moving stone to consecutive actually we did it finish the question finish the problem with three stones but now we are having we're getting an infinite stones its maximum is 10,000 and minimum is 3 so we are given 10,000 and minimum is 3 so we are given 10,000 and minimum is 3 so we are given these numbers and in each turn we can pick up an endpoint some endpoint stone means it has smallest or largest number at the left or at a leftmost or the rightmost it became end poor endpoint stone and movie to an unoccupied position so that it is no longer and put stone so this move so let's say we have two four one two five we cannot move the endpoint of five two because any position is zero or three or four now two or three or four we remained as made it and still a new endpoint so we cannot move number five the game ends we cannot make any more moves the stones are in a consecutive point positions the game ends what is the minimum and maximum number of moves so I'll just tell you the result but so with a little thinking about it my first thing is that we maybe forget about the end appointment regulations so let's say we can move it freely but what happened yeah so actually for let's say some these stones these are spaced the stone space baseball spoon every time we move end point stone like to the left one or the right one to an empty space without the independent regulation we can actually move one step to get the maximum moves right the maximum actually is the sum of these spaces right oh yeah unless but if this only one end points on its left we can actually you cannot move now we if we move it to any space here this place is are gone but if these are two points actually we can make it one by one like these end points on here then this one points just to here so the well let's say we first we are given the songs without sort so first we sort it defying get main stones next stones get back this is very simple actually with some of the space except for except one cases that only one and point at one site like this one or there's a lot of only one stone and this one so if there is only one stone here if I move start moving here I will just lost this part of space but I can move it till here right and then we can move this by iterations like here like this one by one so to occupy them all so actually which side we start at this matters obviously if you want to start like this which is the start like this size so we can lose only three spaces with this start with this one with us more spaces so actually we will some of the space and - the shorter some of the space and - the shorter some of the space and - the shorter space here and here right so actually so the what's the sub cost some equals stones I say cold stores total minus one okay this total and this stone is 0 plus 1 these are all these dots and then minus the sum of the that this is a range of the studs and then which means distant - the circles which means distant - the circles which means distant - the circles which where is the stone is put so it should be total right sums yes - toto be total right sums yes - toto be total right sums yes - toto yeah this is a sum and we return math main return some - math mean so the main return some - math mean so the main return some - math mean so the minimum of this one and this one so it should be stones one mile stones zero or stones okay minus one because we are calculating a spice stone-still 2-1 stones total minus 2 stone-still 2-1 stones total minus 2 stone-still 2-1 stones total minus 2 minus 1 yeah we're done with the get max and then we get me get minimum the stones about minimum about minimun let's just take a look at this sample again obviously I'm not obviously if you want to move them together we were just these like consequences the longest consequences points or possible consequences point must be reuse right like obviously here we just move say move this what dot here and then this one to here and then it's done so actually if we are saying the target the final composition of these consequence stones it could be start here or here possibly I don't know he and some somewhere like here thus given us passed away to do it with a sliding window which slide this window from left to right and we can we calculate it how many stones are there in this range and we can say how many stone we need to move right at least this minimum move oh this is cool and how we're gonna do it we can just do it by moving one by one but actually there are a lot of stones right you see like these kind of stones if we plus it by one I'll tell you a time limit exceeded you cannot do that and let's take a closer look of this example let's say if because we're moving the ranch within the start and the end let's say for arranged if there is like space with each side of them or any of them actually to say let's say it's at the end that's four inch like this actually it doesn't make any difference of this right why because each position or either here or here could be put because there are stones at the start and me at the end right because he doesn't change it me so there one move needs to put here and this one move needs to be here if this one can be put and then this one could be put right let's say the obvious one is to a fifth - if these two could be per pod then - if these two could be per pod then - if these two could be per pod then this these two positions can also be per because both of them are now endpoint stone-like endpoint stones are like this stone-like endpoint stones are like this stone-like endpoint stones are like this so actually any positions within the them are not endpoint stone right so actually we cannot we can just to forget about it mmm this one is much better I think okay yeah so actually these two and these two are the same right if this one is not n stones to this one then this one is also not the end point to this one so that's why we can assumption these are the same thus actually this assumption just leads to reduce our iterations to not just move this sliding window one by one to the right but just one stone by one stone bust by another stone which means is that we can just say this one and then we'll just this one and there was one more right yeah but then we can jump straight to this one yeah because the ones between them are the same yeah so yeah actually we can move stone by stone right by each by one stone at each but there are some cases we need to take considerations like as we let's say just when we put some cases like we cannot move one way to another like this and this one we end here and ends here let's say we give it more some cases like this or this provides us the smooth start moving by moving B stone and the rightmost this was the stone here right we cannot move any places any spaces to this stone this endpoint new endpoint so we're moving our slides the first slide is here right we need actually if first one is here if we just make assumptions up of the end the sliding window ends out of stone so it should be for like this mm-hmm so it should be for like this mm-hmm so it should be for like this mm-hmm it's okay but what if it's like this yeah we n stones for stone sorry this why stick we in here hmm it's not enough so we choose in here but then we remove it here right you say there are four spaces so the ranch is like this so we say we need at minimum of four steps but actually this is wrong the problem is that we actually could make it we'll just say out here we need two more so out here the first one is Oh move this one moves to here and then this will move to here what's the problem is that like this yeah like this problem is because we are some we assump assume that each slide window can land must land on a Sun as it's rare but actually the solution is not right why our assumption failed it's because of what we're supposing is that for each stones for each range of the store for we just as we an end it an and assist before we must assume that this one this range is the same as something like this right which means we assume that this one is the same as this one right yeah because we're so assume that every space with a wrench could be moving forward so end at this yes that's actually not that case because this one actually could not be moved there it's a it is an it is a and it is an end point but if there is only one before that like this things change it because it is no more an end point stone right yeah so the cases we need to consider these cases like this but for this one let's say this one we will check this one so you will be okay the only thing we need to check is the space between them so we only need needs to care about these cases so what we need to care about is that for these cases well ince cases actually and the minimum is two minima step is to if there are one more at the end with things which include any things change mmm yeah the first one is we just said Lana here but actually we are should come move it by three steps one here and two here that's also this wrench right yeah that's also the ranch here if we move to here it will be three you will be - actually we can make it make bet oh be - actually we can make it make bet oh be - actually we can make it make bet oh sorry can we go back to every space could be checked like we already ghosties for if there are three hmm things be change yeah we just moved three here right yeah but it's our assumption we need to land at the end of some something Oh as we are as we were told as we had honest before if this is one stone like this cannot be moved this definitely gonna be too minimum is to and if there are to each of this each empty space could be fulfilled right yeah even these two could be filled so actually this-this-this range could be filled so this-this-this range could be filled so this-this-this range could be filled so we need to take care of the first consequence also let's suppose that they are already some spaces before them like this if there are no space here what sins get easier we just move them one right yeah so we can just suppose the spaces here could be reach could be reached why because the spaces between them could be reached also suppose they are not two here but one here while things get better for the first six we only need to move them one we are supposing there is no ending so for cases like this we must say there must be two stones outside this range so these two injures could be get right if it's not at the beginning but as it start these days our stones are back here all right so we can just a move it at the end so thing so clear okay first we let our range ends at a stone so let's say the round is like this okay maybe here for this range each space around after it after at the end of this rent could be moved before right so we moved around moved arranged one step left if it is a stone well it's get better because we have a more stones in our range if it's space okay we just remove these space and had a new space it doesn't change so actually we can suppose that all the ranges land ends with a stone but the cases start that are for the first area like there are some stones out as a wrench so there must be some spaces winning them right because like because there are stones after it and this is the start this a whereas actually can be filled with this don't so we can just calculate it them treating them as normal just a for this for the beginning and only one case is that there is only one and because we cannot move the stone here this must be two things got a pretty clear let's cut it oh yeah okay so because we're making a sliding window we set the minimum to infinity left in sorry let left equals zero let's write equals zero we first handle the special cases like this how can we do it's means this range actually pass we can say that this one at this position actually has total minus one stones so okay special case like this some more if watch stones so this stone is stones total net the total equals storm stops and told all - 1 - stones 0 plus 1 and told all - 1 - stones 0 plus 1 and told all - 1 - stones 0 plus 1 actually means told - what yeah and what this is one okay if this speaker like there are more space then it is too okay so if stones tofu - one should manage to if stones tofu - one should manage to if stones tofu - one should manage to this system right this stone so we return stones fall two - one - stones return stones fall two - one - stones return stones fall two - one - stones with full - 2 and then minus 1 this is with full - 2 and then minus 1 this is with full - 2 and then minus 1 this is the space right so the space is one space 2 is 2 minus 2 is 2 also if 0 of course is 0 so math minimum 2 &amp; 2 this one so this is a special case 2 &amp; 2 this one so this is a special case 2 &amp; 2 this one so this is a special case where we are handling right it's just uh and then we can just go to the last one ask for our Ford right for lat four okay right zero so right is smoother than four minus total right plus when we're sliding a window okay so the firt so the for the first will we've already assumed that his space could be reached and for the first patch like this until we get enough length of the ranch like here we move until we get then we so when the length is bigger than the ranch we move the left and make this motor and then that is rancher we need if we for the first total -1 spaces we assume that each we total -1 spaces we assume that each we total -1 spaces we assume that each we already known knew that each area could be fulfilled with these empty spaces and even its other spaces of would is stone it doesn't matter because we will count it once more so actually we can just return oh no sorry mean equals math Ming the length account right so actually account is right - left plus one this is account is right - left plus one this is account is right - left plus one this is the length of the cat stones in it so total - this one and then return me and so ha so when we all meet we move the left we let's say we move the right and here and then here okay four okay three a two or three and then move here so okay we need three stones I know when we move here it's still 4 right 4 we need four for this one stone and then we moved here then we need three yeah okay and then we got it here these are too much we need to move stones so we will move stones to this one and then we need three okay so we can see the rule is that when the length is larger then the required length the wrench should be total right is bigger than 2 we move left so Wow right not right but stores right stones right left - songs left this is stones right left - songs left this is stones right left - songs left this is the coordinate so we should need two plus one that's bigger than left plus what actually for these cases we are doing it right but what if these cases the reversed cases like this for our case here the first word check this one for right yeah and then we've got five exact so we got we need the three and then here three and then two and then here got one but actually we cannot make it one because this actually we cannot move at the end so actually we need to take this into consideration also so this one is stones hopeful -1 stones 1 plus 1 equals 2 hopeful -1 stones 1 plus 1 equals 2 hopeful -1 stones 1 plus 1 equals 2 minus 1 I will say return math main two stones 1 minus stones 0 minus 1 so for the all the other cases it's not like this there must be a small space here and then we can safely just a move to just suppose at the end right so nope no problem I think this will pass but maybe there are some mistakes submit oh yay we passed but we are only running faster than 38% of solutions running faster than 38% of solutions running faster than 38% of solutions let's say let's check where we can improve actually I'm not it seems that there is nothing we could be proved right this to then move left and then we calculated the minimum and then we returned yet it's pretty good stones total stones right that's one total me right it's left let's run it again hmm just I don't know maybe just some unstable things yeah that's let's just leave spirit commands and finish this one of all the other cases we can safely suppose rent sliding window and stores yep okay we are running the fastest I think mmm yeah cool that's for today yeah it's not stable whoo we're running to submit too soon yeah okay I hope you have a good night see you tomorrow
Moving Stones Until Consecutive II
maximum-binary-tree-ii
There are some stones in different positions on the X-axis. You are given an integer array `stones`, the positions of the stones. Call a stone an **endpoint stone** if it has the smallest or largest position. In one move, you pick up an **endpoint stone** and move it to an unoccupied position so that it is no longer an **endpoint stone**. * In particular, if the stones are at say, `stones = [1,2,5]`, you cannot move the endpoint stone at position `5`, since moving it to any position (such as `0`, or `3`) will still keep that stone as an endpoint stone. The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return _an integer array_ `answer` _of length_ `2` _where_: * `answer[0]` _is the minimum number of moves you can play, and_ * `answer[1]` _is the maximum number of moves you can play_. **Example 1:** **Input:** stones = \[7,4,9\] **Output:** \[1,2\] **Explanation:** We can move 4 -> 8 for one move to finish the game. Or, we can move 9 -> 5, 4 -> 6 for two moves to finish the game. **Example 2:** **Input:** stones = \[6,5,4,3,10\] **Output:** \[2,3\] **Explanation:** We can move 3 -> 8 then 10 -> 7 to finish the game. Or, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game. Notice we cannot move 10 -> 2 to finish the game, because that would be an illegal move. **Constraints:** * `3 <= stones.length <= 104` * `1 <= stones[i] <= 109` * All the values of `stones` are **unique**.
null
Tree,Binary Tree
Medium
654
1,438
hello everyone in this video we are going to solve the problem longest can give a summary with absolute difference less than or equals to limit we are given an array of integers n an integer limit written the size of the longest contiguous array such that absolute difference between any two elements is less than or equals to the limit in case this no sir very satisfying the given condition return zero so we are given an array of integers let's say it is 8 2 4 &amp; 7 and the limit is 4 so if we generate &amp; 7 and the limit is 4 so if we generate &amp; 7 and the limit is 4 so if we generate all the possible sub-areas we see that all the possible sub-areas we see that all the possible sub-areas we see that the maximum absolute difference so instead of comparing all the absolute differences we can simply find the maximum absolute difference which is the difference between the smallest and the largest element in the sub array so we try finding them for all the possible sub arrays and we see that for 2 &amp; 4 sub arrays and we see that for 2 &amp; 4 sub arrays and we see that for 2 &amp; 4 it is the difference is 2 which is smaller than their given limit also for 4 &amp; 7 it is 3 which is again is smaller 4 &amp; 7 it is 3 which is again is smaller 4 &amp; 7 it is 3 which is again is smaller than the given limit so the answer in this case is 2 the size of the longest Seabury is 2 we see that we can solve this problem in Big O of n square using this by generating all the possible sub arrays but then this will not pass the constraints because the constraints are higher so we have to solve this problem in Big O of n right now let us look using the next example that how we can solve this problem using the two pointer approach we are keeping two pointers they start in the end pointer and we are keeping track of the maximum and the minimum element so we see that when we are at the 0th index the maximum and the minimum is 10 and the difference between them is 0 so okay also the limit was given as the limit is given as 5 so this is over limit is equals to 5 now we see that the limit is zero so the answer is 1 now next we move and to the index 1 now the minimum element will change to 1 and the difference would now be 9 so it exceeds the limit so we will have to increment the start now we have no other option we have to increment start now once we increment start our maximal element would change and it will become 1 again the difference is 0 now let us move end to the next index and the maximum element changes it becomes 2 the difference is 1 which is smaller than the limit so in this case the answer will also change and it will become 2 next we will implement end and in this case the maximum would change and they will become 4 now the difference is 3 which is again is smaller than limit and the answer will be updated and it will be 3 next we increment over n 2 7 in this case again our maximum would change n it will become 7 our minimum would still remain 1 now the difference is 6 which exceeds limit so we cannot update our answer and in this case we have to increment start when we increment start our minimum will change and will become 2 the difference is 5 which is equals to limit so it is permissible and we can simply have our answer as 3 so we are not going to update it next we increment N and now it is 2 so both the maximum and the minimum would not change and the difference is still 5 so the answer in this case would be 4 because the size becomes 4 so this is our final answer the final answers for in this case we are able to do this in Big O of n but there's a problem how are we going to keep track of the maximum and the minimum so this is the problem which arises in the solution and we are going to tackle this using the DQ's the DQ is a data structure in which we can insert at the front and at the end similarly we can remove from the front and from the end in big off one time so this is what DQ is if you want to study what DQ I will provide the link in the description once you have done that you can come back and try some this problem so we are keeping the start and the end point are again at the 0th index and we are maintaining two d qs one and increasing vq another decreasing TQ so initially our answer is equals to 1 and 10 is there in our both over d qs the incrementing DQ will give us the minimum element at the front the decrementing DQ will give us the maximum element at the front let us move end to the first position now this in the element is 1 so we are going to insert one into the increasing order DQ so for that we have to remove all the elements which are smaller than 1 so 10 will be removed and 1 will be inserted in the decreasing one we can simply insert one so we see that the front of the DQ which is incrementing give us the minimum element and the front of the DQ which is decrementing vu will give us the maximum element the absolute difference between them is 9 which exceeds our limit the limit was 5 so it exceeds our limit so in this case we are going to increment s as soon as we increment s all those elements which are before S will have to be deleted from this DQ so we have to delete 10 while implementing this in any programming language instead of directly storing the values here we can simply store the index so that we can know that whether an index is before s or not so you have to remove all those indices which comes before s but for the sake of clarity I am just going to use the values here while implementing we can use the indices set of values all right so moving on the difference the absolute difference is zero in this case so we will increment and we have to insert two in the increasing DQ we have to key we can simply insert two in the decreasing we have to remove all the elements which are smaller than 2 so one will be removed and two will be inserted now the maximum and the minimum are 2 and 1 respectively the defense is 1 which is smaller than limit so we will increment and our answer will be 2 now next we will increment and we will insert 4 will be inserted and to insert 4 in the decreasing when we have to remove 2 &amp; 4 will be inserted here now the front &amp; 4 will be inserted here now the front &amp; 4 will be inserted here now the front give us 1 here and it gives us 4 the difference is 3 which is still permissible and the answer will increment it will be 3 next when 7 comes 7 will be inserted here for this we have to remove 4 and insert 7 too minty in the decreasing order now the difference is 1 &amp; 7 the difference is 6 which is 1 &amp; 7 the difference is 6 which is 1 &amp; 7 the difference is 6 which exceeds the limit in this case we have to increment the start when we increment the start we see we have to delete all the elements which comes before starts so 1 will be removed and now the elements the minimum element is 2 NMX zoom element is 7 so the difference is 5 which is again in the permissible range and the size is 3 so we are not going to make any changes in our answer next we increment and we reach the end of the array and the element is 2 so in order to maintain the increasing order we have to remove all the elements which are greater than 2 so 7 will be removed for will be removed and beginning we can resort to here to maintain the decreasing order we can simply insert two here now the difference is seven minus two which is equals to five which is also within the permissible range so the answer will be four so finally we will return 4 as our answer and we are able to do this problem in Big O of n time and Big O of N space all the operations whether they are insert or whether they are the remove operations in the DQ is taking Big O of 1 and at atmosphere storing n elements in the queues so the space complexity and the time complexity will be big-oh of n for the queue itself so be big-oh of n for the queue itself so be big-oh of n for the queue itself so this is it for the problem if you want to see the code and providing it here you can see the code these are our two queues or start in the end pointers to maintain the increasing in the decreasing order we are simply popping those elements from the back of the queue and then inserting or pushing this element now from the front of the main queue we will get the minimum element from the front of the Mex queue we will get the maximum element as you can see that I am inserting the indexes instead of the values itself so that it is easy to remove this while we are incrementing s so as soon as we see that the defense exceeds the limit we will have to increment s and we will have to remove all these elements which comes before s so this way storing the indices instead of values would help us and in the case when it is within the limit if we have to maximize our answer and increment end so this is it for the problem thank you if you liked the video please subscribe to the channel and we'll be providing solutions to the weekly contest on regular basis
Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
find-the-team-size
Given an array of integers `nums` and an integer `limit`, return the size of the longest **non-empty** subarray such that the absolute difference between any two elements of this subarray is less than or equal to `limit`_._ **Example 1:** **Input:** nums = \[8,2,4,7\], limit = 4 **Output:** 2 **Explanation:** All subarrays are: \[8\] with maximum absolute diff |8-8| = 0 <= 4. \[8,2\] with maximum absolute diff |8-2| = 6 > 4. \[8,2,4\] with maximum absolute diff |8-2| = 6 > 4. \[8,2,4,7\] with maximum absolute diff |8-2| = 6 > 4. \[2\] with maximum absolute diff |2-2| = 0 <= 4. \[2,4\] with maximum absolute diff |2-4| = 2 <= 4. \[2,4,7\] with maximum absolute diff |2-7| = 5 > 4. \[4\] with maximum absolute diff |4-4| = 0 <= 4. \[4,7\] with maximum absolute diff |4-7| = 3 <= 4. \[7\] with maximum absolute diff |7-7| = 0 <= 4. Therefore, the size of the longest subarray is 2. **Example 2:** **Input:** nums = \[10,1,2,4,7,2\], limit = 5 **Output:** 4 **Explanation:** The subarray \[2,4,7,2\] is the longest since the maximum absolute diff is |2-7| = 5 <= 5. **Example 3:** **Input:** nums = \[4,2,2,2,4,4,2,2\], limit = 0 **Output:** 3 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 109` * `0 <= limit <= 109`
null
Database
Easy
null
200
hello and welcome back to the cracking fang youtube channel today we're going to be solving leap code problem 200 number of islands at the moment this is a really popular question with amazon microsoft bloomberg google and facebook so if you've got an upcoming on-site interview with any of upcoming on-site interview with any of upcoming on-site interview with any of these companies this is definitely going to be one to know let's read the question prompt and think about how we might solve this conceptually given an m by n 2d binary matrix grid which represents a map of ones land and zero's water return the number of islands an island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically you may assume all four edges of the grid are all surrounded by water cool now let's look at an example if we were given this input here this grid what would we expect well we expect an answer of one but how do they actually derive this well remember that an island is formed by connecting adjacent lands horizontally or vertically so what that means is that we can connect all these lands right these are all connected like this and that is our island and there's no actual other islands in this grid so we only have that one big island in this grid we expect an answer of three let's see how they got that well this is one island because these are all connected this is one island because it's uh you know on its own here and this is one island notice that these islands are not one big island because it tells us that we can only have an island by connecting horizontally or vertically we are not allowed to go diagonally in either direction so it has to be up down or left and right cool so if you've already seen my problem uh solution for the lee code i think it was 653 max area of an island you'll know that we're actually going to solve this in a very similar way essentially what we want to do is we want to iterate through our grid row by row and column by column and what we're going to do is the first time that we see a 1 what we're going to do is we're gonna kick off a depth first search in all four directions and we're going to basically find all the ones that are connected to this um one here and we'll do that for every single you know one we see in the depth first search so for example we'd start at this one and then we'd go to this one and then we'd find this one and then from here we'd go here and essentially we'd find you know the entirety of our island and what we need to do is also make sure that we don't get caught in an infinite cycle so what we want to do is actually every time we see a one in our depth first search we're actually going to set it to a zero to make sure that when we go back there uh from the next island that's touching it we don't reset it to zero because we actually you know we don't want to get caught in an infinite loop and when we were finding the max area of the islands we had to count the area but this time we actually don't need the area all we would need to do is just set these equal to zero so that you know we just get rid of them so then that way when we finish our depth first search and we're continuing to iterate you know row by row and column by column essentially you know after we've processed this first one then we're going to be at this position but this will have been set to a zero as well as every other one in this island so that means we won't kick off the process again and recount this island so essentially this problem boils down to two things when we see a one we're going to you know uh we're gonna say islands um you know plus we're going to increment our islands count and then we're going to do you know set ones to zero and you'll have to excuse my terrible uh mouse drawings here but you get the idea so what we're gonna do is we're gonna set all of the ones in that island to zero and you know we're gonna count as if we had seen one so you know let's look at this example and kind of make it a little bit more clear so we're gonna go row by row and let me just delete all of this here so we don't clutter the screen so we're gonna go row by row column by column so we're gonna start here and we see that this is a one so we're gonna say our island count is now gonna be one and we're gonna set this equal to zero and we're gonna kick off the def first search right so we're gonna go to this uh right one we're gonna see it's a one we're gonna set it to zero we're gonna try to go up but this is actually outside of the bounds of the grid so we don't do anything here we go to its right we see it's already zero so we can terminate the depth first search there we go to this one we see it's a one so we set it to zero it tries to go to its right and it terminates it tries to go down it terminates uh it goes to the left it's a one so we'll set this equal to zero again this will go up but this is already a zero because we've set it tries to go out of bounds tries to go down tries to go back and essentially what we're going to do is we're going to set all the ones in this island here to zero then we're going to continue so we know we'd be in our original for loop or we're going row by row column by column so now we're here but this is a zero so we don't do any processing zero okay we get to a one so now let's increment our island count so it's now two and then we're gonna set this to zero and again we're gonna try to go in all four directions but we're actually gonna see that all of these are already zero so every time we hit the zero we're actually just going to terminate that depth first search and eventually we'll just come back here um because there's nothing to set other than this original zero so then we're going to continue with that original for loop through the rows and the columns so we'll see this is a zero then we'll get here so we have a new one so that means that we have another island so we now have three islands we'll set this to zero and then we'll go in all four directions we go up we see it's a zero we'll go to the left it's a zero we'll go out down which is out of bounds which we're going to consider as a zero because it tells us that uh where is it all four edges of the grid are surrounded by water so we can just assume that outside of the bounds it's always going to be water and then we go to the right and we see it's a one and since it's part of the search for the original one we don't increment again um so you know this gets set to zero and this is going to try to go up this is a zero this goes out of bounds which is considered a zero this goes out of bounds and then this goes here which is already a zero because we just set it so that means this dfs will terminate then we'll be at this last one for our you know row and column iteration and then um basically this is already a zero so then we terminate and then we just return our final answer which is going to be uh this three here so that's how we're going to solve it conceptually let's go to the editor and actually put it into code so you can see how we're now that we've seen how we are going to solve this conceptually let's actually write the code out and you can see how it's implemented so we know that we're looking for the number of islands so let's define a variable for that so we're going to say num islands equals zero and remember we said we need to look four directionally when we encounter a 1. so let's define that so we can re use it anywhere so we're going to say directions and we're going to say 1 0 so these are all the four directions we can travel and i think we just need minus one yeah okay so those are our four directions we can travel and what did we say we're gonna do so we said that we're gonna go row by row and column by column and every time we encounter a one we're gonna increment our islands count and then we're going to set all of the zero the ones in that island to zero and then continue processing so that way we can just count all the distinct islands and since we set all the other ones that it's touching uh to zero we won't double count so let's actually do that we'll say four row in range um lan grid and we're gonna say four call in range lang grid of zero we're gonna say okay if grid of row call equals to one and i hate that lead code uses strings here because usually it gives you integers they're just trolling you here it's really annoying be careful with this if you get this in an interview this might actually screw you over if the interviewer you know if it's given to you as strings and use integers so just watch out sometimes they like to pull this kind of shenanigans anyway so if it equals to a one what we need to do is we need to say we need to increment our island count by one and then we need to set the island ones to zero so let's actually you know call a function for that and we'll say set island um and it's gonna take the grid and it's gonna take the row and the column right and at the end all we would need to do is just return the number of islands so let's define this function here to set the island zeros set island zeros we're going to say grid oops actually needs to define it def set uh island zeros and it's gonna take the grid it's gonna take the row and it's going to take the column right so like we did with uh the problem to find the max area of an island we need to make sure that when we're calling our depth first search that we're actually within the bounds of the grid and that we are um you know at a one uh the reason why we want to check the bounds obviously if we try to access the indices um that's outside of the bounds of our grid here um you know we'll have an index error and then you know our code will blow up and you know we don't want to do that so we want to make sure that we're actually in the grid uh so what we're going to do is we're going to say if so we need to check our conditions here on the boundary we're going to say if the row is between you know the grid parameters and also the column needs to be within the grid parameters uh and we actually need to be on a zero sorry on a one because that's what we're interested in equals to one be careful with the strings uh what are we gonna do now well we said that we need to set all ones in an island to be zero so that way we don't get caught in infinite cycle we don't double count things so we wanna say grid of row column is going oops equals to zero so that us setting it to zero and again be careful with the strings um now we just need to go in all four directions so we're gonna say four row increment column increment in um directions what we're gonna say is we're gonna say set island zeros and we're gonna pass the grid in the row uh sorry row plus the row increment and the column plus the column increment and that's really all we have to do now i think it is worth noting and i did mention this in my other video that this assumes that you're allowed to actually modify the original grid um this makes it easy for us because we can just look up the value in the grid with this check here to check if kind of we've been there before or if it's an invalid value if you're not allowed to do that sometimes the interviewer will say hey i don't want you modifying the input what you're going to need to do is you're going to need to define a separate set data structure to basically hold the coordinates um you know the row column points that you've been to and then you can do that check there um to make sure that you actually haven't been there before if you're not allowed to overwrite this and that's really the only way you can get around it but in our case we are allowed to do it or at least you know the problem here doesn't stipulate that um we're not allowed to do that so we're going to just you know do it that way so let's submit and um you know check what our answer would be cool it works um you know before we go i think it's always important to think about the time and space complexity of our algorithm so if we think about it um we're iterating over the entirety of the grid row by row column by column so time complexity wise in the worst case we're gonna have to touch every single um piece of the grid right uh because you know if it was all zeros we would still have to iterate over row by row column my column so we have to touch every single point so our time complexity is going to be big o of the number of rows times the number of columns right and then the space complexity well again like the problem where we're finding the max area of the islands if we're counting the recursive uh stack frames it's still going to be rows times columns because we could have the case where we have one big island that spans the entire grid which means that we would have to basically hold the entirety of our kind of recursion in that one stack frame so it would be you know rows times columns uh otherwise it's going to be big o of 1 if not counting stack frame so this is something you can bring up to your interviewer it shows that you kind of think about these sort of things like hey are we counting the recursive stack frames if not then it's actually constants time uh it's just good yeah it's just good to have these things in your mind and bring them up in the interviewer interview anyway um that's how you solve leak code problem number 200 number of islands i hope you enjoyed this video if you did please like comment subscribe and make sure to check out my other videos if you have an upcoming on-site videos if you have an upcoming on-site videos if you have an upcoming on-site interview happy coding
Number of Islands
number-of-islands
Given an `m x n` 2D binary grid `grid` which represents a map of `'1'`s (land) and `'0'`s (water), return _the number of islands_. An **island** is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. **Example 1:** **Input:** grid = \[ \[ "1 ", "1 ", "1 ", "1 ", "0 "\], \[ "1 ", "1 ", "0 ", "1 ", "0 "\], \[ "1 ", "1 ", "0 ", "0 ", "0 "\], \[ "0 ", "0 ", "0 ", "0 ", "0 "\] \] **Output:** 1 **Example 2:** **Input:** grid = \[ \[ "1 ", "1 ", "0 ", "0 ", "0 "\], \[ "1 ", "1 ", "0 ", "0 ", "0 "\], \[ "0 ", "0 ", "1 ", "0 ", "0 "\], \[ "0 ", "0 ", "0 ", "1 ", "1 "\] \] **Output:** 3 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 300` * `grid[i][j]` is `'0'` or `'1'`.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
130,286,305,323,694,695,2035,2103
263
today we're going to be working only at code question number 263 uh ugly number an ugly number is a positive integer whose prime factors are limited to 2 3 and 5. so we're going to be returning true on uh if n is an is a an ugly number so in this example number one uh n is equal to six uh we're going to be returning true because the prime factors are only to uh multiplied by two multiplied three is gonna make it six uh so this is an ugly number uh in example three n is equal to 14 we're going to be returning false because 14 is not ugly because we don't have enough we have seven and the prime factors the algorithm is going to be that we're gonna try to see if it is com if the number is completely divisible by 2 3 or 5. if that is the case we are going to actually divide the number by 2 3 or 5 and then in the end we are just going to check if we are left with one if not it's not gonna be an ugly number if it is uh if we are left with one that means it is uh gonna be a true meaning it's gonna be an ugly number uh for uh like the code simplicity you can say we are going also going to actually divide the number by four just to keep the code shorter instead of actually doing it three multiple times for uh for i equals to two three and five we're just gonna say that we're gonna be doing it for two to 5 less than 6 i plus so while the num the n uh modulus i equals to zero we're gonna say that n divided by equals to r so again we're gonna end up dividing us using like the logic is gonna see even it's gonna even try to do that when the i is equal to four but that is not going to increase the complexity or anything so we're going to keep it there and then we're going to be returned oh we're going to be checking if n is equal to 1. looking good so we have we forgot to do one more thing that is that we want to also check if the number like is greater than uh like if the number is greater than zero because we don't want to keep just doing it if the number just became zero yep and it works
Ugly Number
ugly-number
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`. Given an integer `n`, return `true` _if_ `n` _is an **ugly number**_. **Example 1:** **Input:** n = 6 **Output:** true **Explanation:** 6 = 2 \* 3 **Example 2:** **Input:** n = 1 **Output:** true **Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. **Example 3:** **Input:** n = 14 **Output:** false **Explanation:** 14 is not ugly since it includes the prime factor 7. **Constraints:** * `-231 <= n <= 231 - 1`
null
Math
Easy
202,204,264
73
welcome to august leeco challenge today's problem is set matrix zeros given an m times n integer matrix if an element is zero set its entire row and column to zeros and return the matrix you must do it in place so that's kind of big because we can't generate a new temporary or can't generate a new matrix and then return that we want to update the original matrix so they give you a bunch of hints and i've seen this problem before so let's see if i can do this through memory the basic idea is what we'll do is use the first row and first column to track whether there's zeros inside of our matrix now the reason for that is if we did some sort of like recursive solution the problem is whenever we update the entire row and column that's going to make it later on when we see that the cell is zero we're going to update things like in two steps right and we only want to update it if it's zeros here for instance if we update zero like and we come here and we update all these rows the thing is if we meet this next column since this is set to zero we're gonna update these as well and we don't want to do that right we only want to set the zeros for the first row and first column once so what we'll do is use that information whether there's a 0 inside of the row or column mark it in the first row here and mark it in the first column so what i mean is we'll move through skipping the first row and first column to see if any of these are zeros if they are we're going to mark the first row column at zero and we're going to mark the first column row at zero here so these will be set to zero and later on we can move through and set all these rows and columns to zero but one thing that's going to be a little bit different is if the zero is inside the first row and first column that changes things because we don't want to set everything to zero because we have important information here right if we set everything to zero then we're going to set all the rows and columns to zero so what we'll do instead have a boolean to mark whether the first row and first column is zero and do that at the very end like if there's a zero inside of the first row or the first column later on after we do all our updates then we'll just update the first column and first throw all of zeros all right so let's begin let's set our uh mnn first let's say n and m and this will be the length of matrix zero and this will be the length of matrix okay so the first thing i'm going to do is uh create a boolean for the first row and first column so these two false at first and we're going to check to see if there's any zeros inside the first row and if there's any zeros inside the first column so we'll say four column or say four row in range of let's see m um if matrix row so row and then zero this would mean the first column has a zero right so if any of these equal zero then first column equals true we'll do the same thing here uh but for the columns instead to mark the first row so four column in range of n if matrix zero c is equal to zero then the first row is set to true all right now we're going to mark our first column and first row with information for all the other cells within so we'll say 4r in range of 1 through m and 4 column in range of one through n if matrix r c is equal to zero then let's mark our matrix of let's see zero c this will be set to zero and matrix of r zero is also sub zero now let's just move through and set all our uh rows and columns correctly so we'll have to do this in two steps we'll say four row and range of one through m so if let's see if matrix are zero is equal to zero then we're going to move through all the columns and set those to zero okay so four uh c in range of one through n let's mark everything at zero rho c equals zero and we'll do the same thing here for column and range of one through n if matrix zero c is equal to zero then we'll set all the rows in here range of one through m also zero c r c equals zero finally uh the first row and first column if first row is set to true then we want to set the entire first row true okay so four column in range of we want everything here and i will set matrix let's see first row all equal to zero here let's clean that up a little bit and we'll do the same thing for the first column for all the rows and range m matrix r zero also to zero and finally we don't need to return anything then right because we've modified the original matrix itself so let's see if this works all right that looks like it's working nope uh let's see i didn't get this one no one why didn't that happen oh okay my mistake this should be c so let's see here all right that looks like a spring so it's going to submit that and accept it hugh i thought i didn't get that so this would be time complexity n times m and we use constant space right so yeah i mean i've seen this problem before i'm glad i could still solve it and really i don't really know what else there is to add i don't i'm not even sure if this is a video i should upload because i've already done it but uh whatever since i've already done it i'll probably put it up all right thanks for watching my channel uh remember do not trust me i know nothing
Set Matrix Zeroes
set-matrix-zeroes
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s. You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm). **Example 1:** **Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\] **Example 2:** **Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\] **Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\] **Constraints:** * `m == matrix.length` * `n == matrix[0].length` * `1 <= m, n <= 200` * `-231 <= matrix[i][j] <= 231 - 1` **Follow up:** * A straightforward solution using `O(mn)` space is probably a bad idea. * A simple improvement uses `O(m + n)` space, but still not the best solution. * Could you devise a constant space solution?
If any cell of the matrix has a zero we can record its row and column number using additional memory. But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker? There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
Array,Hash Table,Matrix
Medium
289,2244,2259,2314
116
hey guys so i'm trying out this problem populating next right pointers in each node okay let's have a read we're given a perfect binary tree it all leaves on the same level and every parent has two children the binary tree the following definition find it as a left it is the right it is the next what is next operate each next pointer to point to its next right node if there is no next right node the next pointer should be set to not initially all next pointers are set to none okay let's understand um okay twos once right is null two is right is three four side is five side is six is seven okay that is how we have to set it up to distance output is okay solution you return node connect node root so we return basically the root of the tree i guess the given the above binary tree your function should populate each next pointer to point to its next right now just like in figure b the class are put in is in level order driver as connected by the next pointers with the hash signifying the end of each level okay empty is empty you may only use constant extra space because your approach is fine you may assume implicit stack space does not count as extra space for this problem okay i mean contradictory recursion users were fine if it says can we use the question we'll use the question let's try and see what we have to so node is a valve when it's left right and next left and lights are populated next is not so in some way if we can do a level order traversal and it's given a perfect binary tree i forget the exact definition but where all the leaves are on the same level that's the important bit all right all that is on the same level i feel like perfect binary tree is the one where each node has two normal nodes right until the leaf and then one of the leaves are basically here so all these are the same level hmm so if i do some sort of a level of traversal then i would know that this is only level and then i'll put two when i put three and sort of in right to left direction so i save this and next guys next is this next place next is something like that so i'm thinking of level reversal uh q1 day out one nothing else is there push 3 and 2 and then look at 3 and save it always save the previous guy yeah so something like yeah i think just a regular level of traversal would suffice let's sort of do a walkthrough so i do one put one into the cube and then i pop one uh remove one from the queue and the level is done right now once i would have inserted it still into the queue so three first i insert the right child and then i insert the left child i'll maintain something called as previous and whenever level is done previous will be set to none so here i pick three out previous is null initially so three is next is null and previous is pointing to three i remove two okay and when i remove three all also i'll add seven and 6 but i will know the indication of 11 right and then when i remove 2 i'll insert 5 and 4. and uh for two when i remove two's previous was uh three so two's right will be pointing to three and then uh because level is done i'll set previous to none so for seven it will be enough for since it will be seven yeah it's pretty i think it's pretty straightforward okay if that's what you think let's try and do it so i define uh which is node what does it mean so what if node is null whatever so first let's do this uh the return route yeah and then for the change that we are making so we take a q so let's also link this other okay so we want to create a queue and insert q dot add root right and then while q is not empty let's also save this node previous as none okay so first you get uh the data attack your point and this the number of levels so in uh i want to keep track of the levels so in this level these are the number of nodes so you run through the list and at the end of the level when the level is done you will set previous cracks to back to null right and yeah so this is fine for each node what am i doing for each node i am first of all i'll pop something out of the queue peak and what do you call this pull i think so you remove the element and its right will be set to previous and not right actually next if not right is not equal to null then first you add right and then you add left next is set and then you also make previous equals okay and this is good and then you said previous small here if the loop is done yeah i think this is good let's run code compilation error yeah this happens okay so one example works let's check the other edge case example as well says empty thing okay and we got some oh i missed the fact that you cannot use extra space fine i'll fix the approach but let's first see how this works null point exception okay it says node is none so let's do this if root is equal to null return yeah okay submit find this works but we cannot use uh imp with this explicit extra space we have been told not to use it we cannot use this cube this one says recursive approach is fine you may assume implicit stack does not count extra space so because this now this is not allowed we can stop and try to figure out the recursive approach so can we do this level order traversal recursively hmm left right node value i don't really want to see all this okay um what to do if you don't take an extra space then i take one element and then call it is a perfect binary tree which i mean every node has two children till the leaves i think that is what i have to rely upon uh so there is no thing about left being alone right not being null that knock and that cannot happen right in which case the roots left child's next will be roots right child and then we go here its left child's right will be this and it's uh the absolute cell is how do you connect these two that's the only question so roots left child's right would be roots right child's left child hmm interesting so could we do just like a obviously firstly if root is null what's the problem here we return now what we do is uh root.next is uh connect is a good hint i feel the word connect so connect uh you have to connect root dot left and root dot right and you return root okay now so you do uh left dot next equals right obviously and is the bit that you have to be interested in so obviously you connect both of them separately so you connect left dot left and left or right similarly connect left uh right or left right or right but you also have to connect uh left dot right to right dot left and you break if f equals to null so it's a perfect tree what would happen is both would be null but let's just do this okay this you don't have to do nulls are already set so you there is a breaking condition and these are three connects uh that we have to do left will connect to right and then one further down tree it's i mean obviously it's left right side will automatically connect but these two also have to be connected and then these calls itself so essentially with these you handle these two and you handle these two as well now let me see the next level what will happen uh let's build another level and see what exactly happens there yeah so we can imagine when we call correct four five uh what will happen is it will connects it will do the connect on uh yeah so you could actually just call connect on just root dot left sorry you can just call connect on left it will take care of its uh subtree and you can call it on right which will take care of its subtree right and the only thing that's left is this connecting these two which you can do via you will just say left daughter okay let's understand again so it was called on one so you can call on two column three and connect two and three yeah i'm missing something again and so when you call on two it will connect four and five when you column three will connect six and seven who will connect five and six that is also your duty only right now only that i'm not sure about is when i say connect on four five it when you say connect two it will call it will connect four and five and call connect one four and five which will take care of their internal sub trees yeah so this i do left dot uh right dot next equals to right dot uh left i think that's the bit what if left or right is null so you can do that if left or right is not equal to null then you do this now let's try to run it again so we're trying to connect left and right really i wonder if these two are needed oh these two are definitely needed so let's build another example uh one two three okay i mean i'm lazy let's just walk through for this so yeah one calls in on two and three way two and three so you call on to call on three yeah that's the problem that it returns okay so then i just call connect uh left or left with uh left or right and i thought left with five dot right which will then internally call on this that guy and that so two is calling on four and five four will do it's on itself and link them and between uh these this is uh so four will connect it before we connect its children firefly connects its children and who will connect those two so six seven connected it's the same as here who is connecting these 500 so we are called on two and three two connects with three which is here right two calls on its children three calls on its children and then we also connect their trees similarly here also four will call it call on its children five will call on its children and will also connect uh their trees as well okay so that works uh but when you're on six and seven six four corners children seven requires children you connect six and seven but what about this the right child of five and left child is six you have to call connect five six you can't just do this you have to actually correct five and six there is some repetition happening that i agree there's a repetition that i agree uh because two is also calling connect four five so it will work on five yeah repetition i agree but this also has to connect only i'll have to try it i mean this works first let's confirm that this works because i feel this definitely works yeah uh okay submit let's see if it causes sometimes an exception no now i feel i just feel that there is some repetition happening which is this left or right left dot right dot left on these nodes i'm calling connector twice i mean won't call any cause any harm but i can't also keep an extra space to not do that so i guess i'm okay with this all right then
Populating Next Right Pointers in Each Node
populating-next-right-pointers-in-each-node
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { int val; Node \*left; Node \*right; Node \*next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`. Initially, all next pointers are set to `NULL`. **Example 1:** **Input:** root = \[1,2,3,4,5,6,7\] **Output:** \[1,#,2,3,#,4,5,6,7,#\] **Explanation:** Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 212 - 1]`. * `-1000 <= Node.val <= 1000` **Follow-up:** * You may only use constant extra space. * The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
null
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
117,199
920
um hello so today we are going to do this problem which is part of Fleet code daily challenge number of music playlists um so we have in different songs and we want to listen to gold songs so this is basically the number of songs in our in a playlist um so you can think of your playlist with tracks like this and this is how many songs we need to be in that playlist um and they say every song is played at least once so what this means basically is that um every song from these and different songs needs to be in goal so that so let's say if you have four different songs you need to have four in your playlist at least four because you need each song to be played at least once so that tells you already that n that goal has to be bigger or equal to n okay um say equal is G and that's already what you see here in the constraint okay um so now we know this first um this first property of our playlist and then the second property is that you can't play and the same song again until you have already K other songs that have been played it's a little bit of a mouthful and the description is like very poor here but what it means is let's say you play song One let's say we have maybe three songs and let's say k is equal to uh let's say two right so you play one song one you have to you can't do play one here no you have to play three because now you have two other songs and then you can play one and now for two you have two other songs that have are played and so you can play two again okay and for example let's say if goal was five um our playlist so now we have one slot two slots and play those three slots four slots five slots so we can have this as a playlist it's valid because two occurs only after k equal to after two other songs and then one same thing okay so that's sort of the idea if we had the goal is six we can play three here as well okay so now that these two constraints are clear I hope um what's the goal of the problem well we want to return how many possible playlist we can create so of course different playlists and the answer can be large so we charge we need to return this so that's the idea and if you look here we can have up to 100 songs so not too big um so how let's see how we can tackle it um Okay so this if by looking at this problem first It's Tricky you don't we don't really have any greedy or any sort of strategy that is clear that we can take so in that case lost this we are looking for the number of possible playlists so we it's sort of a counting problem here and so we should be able to just try all of them and count how many right and so that already tells you we can try to do some dynamic programming solution and always programming solution let's start with the recursive approach so for that what is the state that we have well for we have the inputs that we have is n goal and K okay so we could either try all three as our state or maybe let's try to make it um uh smaller because this K we probably can take it into account in some other way and so here what we want to find at the end is how many playlists so let's call it count we can get out of n songs for playlists with gold songs so this is sort of the length of your playlist okay um I will just like change the parameters a little bit so goal just and so what would be a sub problem here so let's just try to just make this um you know like in a more uh dynamic programming notation so let's say count of I and J so this would be basically a number of playlists we can create of length I right that's the goal is the length of the list of the playlist and J different songs okay so let's say this is the sort of the state that we have now can we do this can we find some problems here well for some problems and especially here because it's just a number of songs then let's just try I minus one in J minus 1. okay so what if when we have let's say um a playlist already of length I minus one so if we have a playlist of length I minus one then what choices do we have let's say I minus one and Json and J minus one songs so in this case well we can just either introduce a new um introduce a new song right so if we introduce a new song let's call it song um a maybe then now the playlist length is I and how many different songs we have well it depends if this song is a different song than the J minus one songs we have then now we have a J songs but if this song is the same then now we have I links of the playlist but J minus one songs so this is just to get your thoughts moving a little bit here of course we still don't know how do we figure out if this song is different or not that's still a tricky part here okay but at least we know that our states are likely our sub-problems our states are likely our sub-problems our states are likely our sub-problems are likely these two to get IJ Okay so let's go back here again so we have count of I and J how do we get these sub problems well if let's say if the Json jth song Here is a new song so either it's we are adding a new song the previous state is that we added a new song through in that case how many playlists we can create well it's going to be counts of I minus 1 so the previous state is we had a playlist of length I minus one and then we added a new song now we have a playlist of length I and we had only J minus one unique songs how many we can have here well depends on how many songs we have so let's say we have an unique songs total and unique songs then how many songs this one is a new song So how many songs unique songs do we have left we have n minus J minus one so when we have J minus 1 unique songs then this is the number of remaining songs that we can pick from to have a new song right and so this is how many playlists we can create because let's say there are many songs we have are four five six seven eight and the playlist already has one two three then we can either pick 4 or pick five or pick six or pick 7 or pick eight and how many are these here we have five so we can create five different playlists because one playlist can be one two three four another playlist can be one two three five and other players can be one three six one two three six another playlist can be one two three seven and so you get the idea right so we can create n minus one minus J minus one playlist which is um if we do n minus J minus one playlist it's just going to be n minus J plus one right okay so that's the first um sub problem now what other things should we add the other case well the other case is we have to play a song that we played before so basically let's call it replay a song okay so if I already playing a song then of course we increase the playlist by one right so it went from M minus one to I because let's say you have one two three and you already played one now your playlist length is it was three before now it's four that makes sense so it went from three to four that makes sense but the number of unique songs which is J here didn't change which is the second parameter didn't change we still have um we still have J songs to be able to go from I minus 1 to J to i j we need to already have had J songs to be able to replay the The Ice song in the playlist to be able to have the eighth song edgy play of a previous song right but how many do we have how many playlists can we create out of this well we have the constraint that you can't replay a song Until you already have K other song so I'll say whatever K was to be able to replay one we need to have K songs here to be able to reply one if we had one two three to be able to replay this three here we need to have K songs let's say maybe K was equal to three then we need to have maybe four five six and then be able to play three here so what does this tell you well this tells you that the K previous songs cannot be replayed so we know that we can't replay four we can't replay five we can't replace six but we can replay either three or two or one so how the question becomes how do we get this number of songs well it's easy because it's just we know that we have J unique songs the K previous ones we cannot three Play Because four we can interplay it five for counter played so it's just J minus K that will give gives us the other ones that we can replay so that means that here we should just multiply by J minus k okay and that's it and we so these are the number of playlists we can play with the two different options so how do we what's the combination of the two well this is just the total number of playlists so we just Plus now one thing I want to iterate here is what's clever about this solution is that we don't actually go and check each solution and see did this specific song was replayed or not which because we care only about the number of playlists we just count how many we have how many we can do and just get add up the total okay um and once you figure this out it's pretty much the problem is pretty much solved so the only thing you need to figure out is what are the base cases well the first base case is that if I is equal to 0 and J equal to zero so this basically means that how many playlists we can create with a playlist of zero length so with the nupture playlist and with zero um zero songs well playlist empty playlist with no songs that's just one playlist which is the empty playlist so here we need to return one and then the other case what if I equal to zero but J is some other different than zero then in this case how many playlists we can create with no songs even if when we have um when we have J songs so um sorry how many playlists of length zero can we create that have um that have j unique songs that J is different than zero well the answer is zero because it's not possible and similarly how many players of length I different than zero in J equal to zero so basically how many playlists of length bigger than zero with no songs that doesn't make sense it's not possible so zero so this we can have these are as our base cases and this is our um our recursion iterations and then we can just cache and get and solve it okay yeah so that's pretty much it now let's implement it and make sure it passes um okay so if we want to write the function here so the state is I and J and we have our two base cases right which is that um when both I and J are equal to zero or when either one is equal to zero so if both R equals to zero we can create one playlist if one of the either one is equal to zero or ten zero and then we have our two states that we saw in the overview so the first one is okay let me just first get rid of the modulo so that this is clear um so the first one is I minus one a playlist of length I minus one and then we want uh with J minus one different songs to be able to get a playlist of length I with J different songs we pick a new song and the number of possible new songs is I minus J minus one okay and then the second possibility is let's actually make this Choice one here let's call it pick a new song okay and then the other choice see two let's call it is um a replay the previous one okay and here we are allowed only to reply J minus K and I put zero here so that we don't get a negative number because we can't have a negative number of playlists um and so if we can't replay any songs then this is just should be zero right so that's why we multiply by zero here if that's the case and then the end we want to return just the sum of the two num possible playlists from each option um and now here we just want to call our function so what is the state so we want a playlist of length goal that's what the problem says and with and different songs because the problem says we need sorry we need every song played at least once so this is what we will not return here now with the problem also asks us to use a modulo 10 to the power of 9 plus 7 if the answer is Big so um let's just introduce that so we want to do like that and we want to take the mod here take the mud here and take the mud out of the sum here so that's should be it and we also want to Cache because this will Pro will get called on the same stage multiple times so we want to just cache you can use a hash map but I'll just use Python's cache here quickly and that should be it so if we run this should work okay submit and that passes okay so yeah that's pretty much it the hardest part is figuring out how many playlists you hear um you can construct and once you have that it should be done um yeah so that's pretty much it please like And subscribe and see you on the next one bye
Number of Music Playlists
uncommon-words-from-two-sentences
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that: * Every song is played **at least once**. * A song can only be played again only if `k` other songs have been played. Given `n`, `goal`, and `k`, return _the number of possible playlists that you can create_. Since the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, goal = 3, k = 1 **Output:** 6 **Explanation:** There are 6 possible playlists: \[1, 2, 3\], \[1, 3, 2\], \[2, 1, 3\], \[2, 3, 1\], \[3, 1, 2\], and \[3, 2, 1\]. **Example 2:** **Input:** n = 2, goal = 3, k = 0 **Output:** 6 **Explanation:** There are 6 possible playlists: \[1, 1, 2\], \[1, 2, 1\], \[2, 1, 1\], \[2, 2, 1\], \[2, 1, 2\], and \[1, 2, 2\]. **Example 3:** **Input:** n = 2, goal = 3, k = 1 **Output:** 2 **Explanation:** There are 2 possible playlists: \[1, 2, 1\] and \[2, 1, 2\]. **Constraints:** * `0 <= k < n <= goal <= 100`
null
Hash Table,String
Easy
2190
863
hello guys welcome back to take those and in this video we will see the problem of finding all nodes present at distance K in a binary tree so this is from lead code number 863 and we will see all the follow-up problems once we see all the follow-up problems once we see all the follow-up problems once we are done discussing this entire solution so stay tuned till the end I would like to announce about our DSA live training program which will guarantee understanding of every programming concept it makes you interview ready in just three months and it will maximize your offers so that you get the best possible pay and in the best possible company you can all the sessions will be live interactive sessions so you will get the feel of a live class and you can ask all your doubts throughout the class in order to get more details please WhatsApp us on this given number let us now look at the problem statement in this problem given the root of the binary tree so the first node is the root node the value of the target node in this case the yellow one is the target node and an integer K return an array of the values of all the nodes that have a distance K from the target node you can return the answer in any order so in this case you are given the root node and you are given the target node and you are given a value K let's say if K is equals to 1 then they are asking about what are all the nodes which are at K hops that means K number of hop distance from the given Target node so if the Hop distance is 1 then you will see it is 3 6 and 2. so in this case the answer can be 3 comma 6 comma 2 in any order now if I increase the value of K2 let's say 2. then it will be the neighbor's neighbor so the answer in this case will be 1 and then you have four you have seven uh but you do not have any neighbor of six so the answer will be one four seven in any order so I hope you understood the problem statement the constraints in this problem are also very important so you should go through them it says that you have notes in the range of 1 to 500 and all the node values are unique now let us look at the problem in more detail so I have exactly taken the same diagram and by the look of it you must have understood that it is a directed Edge so in a tree you always have all the edges as directed so this is the structure node definition in this case you have an integer value and the constraints mentioned that all the node values were unique so you can make use of it as well and it also declared you have a left pointer and a right pointer so if a node only has left pointer and right pointer they will definitely be directed so you will always have directed edges for a tree so let's say in this example if this is the target node in yellow then if the K value is equals to 1 we want to find all the nodes at distance one from this 5 which is the target node we can easily get this 6 and 2 using the left and right pointers but there is no way that we can reach to this 3 right because we do not have any pointer moving from 5 to 3 that is a problem you may say that 3 is the root node but then the question can be changed and maybe 2 will be the Target and so you will never be able to reach to 5. so this is the main problem for this entire question now if we can maintain some kind of child parent relationship in such a way that every child will have a pointer pointing to the parent node if we can have this kind of a structure then definitely I will be able to move given any node I can move in any of the Direction all the three directions right that is one way to solve this problem otherwise another way can be if I can maintain who is the child pointer and for each of the child pointer who is the parent if I can maintain this relationship in some data structure where if you give the child pointer let's say I give two then the value of it should give you the node which is the parent of two now you must have known by now that this data structure can be a map data structure so we can take an unordered map for faster operations so let's see that I have again taken the same example and if you build a map having the child to parent relationship you can do that by using DFS which is by recursion or by using BFS which is the level order traversal on a tree if you want to see my videos on DFS and BFS it will be linked in the description below you can go there and watch otherwise if you already know it then you can use DFS I have used it in the code DFS and you can actually make all the child to parent relationship right so you can just keep moving and you can maintain the caller like if I say that if I my current node is 5 my caller was 3 then 5's parent will be three simply and using that you can build this entire map child to parent map right now once we are done with this given a node we can move in any possible direction right so this was our first goal the most important goal which has been achieved but the next question is how to find all the nodes at distance K so whenever you have a question of finding all the nodes at distance K or moving in all possible directions with equal amount of distance or equal number of hops whatever it may be it is always a BFS problem breadth first search let's imagine that you have a pond somewhere and then you are throwing a stone just from top of it you will see that it will form Ripples and the ripples will travel in all the directions with equal speed right so whenever you get a problem where you have a starting point or you have a Target node somewhere and from that node you are moving in all possible directions but with equal velocity or equal speed then all those problems will be BFS problem you can watch my video on BFS for more details on the same topic so once we understood that this is a BFS problem and we have also made the child to parent map which will help us perform BFS starting from any node in the problem you are already given the root node and the target node and with the value K so now the question becomes very simple we have again taken the same example and uh the node value here is 5 which is the target node right and then we have a hop distance of let's say 2 we have already built the child to parent map so that is there now simply we need to perform BFS so let me show you a diagram of how you will perform BFS user queue for level order traversal or for BFS insert the first node where you will be starting so in this case you will be starting at the Target node right now find the size of the queue and repeat the level order traversal for those many items in this case the size of the queue is only one so at level 1 you will have only five nodes you can also name it level 0 or level one Whatever You Like so you pop this item and you use the map and see who is the parent of five you will see that for three the parent is null because 3 is actually the root node okay so for five how to query that you give five uh in the maps key and you will get the value as three right so you can insert here three always remember that since all the nodes are unique you can use integer type of key and you should use the reference that is node star type of parent you should take care of that don't use integer on both sides otherwise even if you get three you don't know which node you are referring to right so keep this in mind and if the values can be duplicate then you cannot take integer even on the keys but you have to take a node star type because two different nodes having the same integer value occupying different space will be having different references simply right so do keep this in mind but just to save one space if you have unique values then use integer in the key part okay so we will be making use of that property in the constraint once you have inserted five you insert the left and the right pointers if they exist so yes the left pointer exists so we will insert 6 the right pointer exists and we will insert 2 and we are done with all the level 0 nodes so now we will go for level 1 right and you find the size of level 1 you have size as three so try to process each node one by one now we will take out this three okay we will take out this three and we will see who is the parent of three so we do not have any parent of three so no parent will get inserted we will see who is the left child of three now we need to maintain a visited array which will say who are all the nodes which have already been visited I hope you can do that so you can use a map for that as well or you can use an array so I would go with the map simply so 5 is already visited so that cannot be inserted one is not visited so one will get inserted right now after this you need to process the next node which is six for six you do the same thing who is the parent of six five but five is already visited okay now the left child of 6 is not present as well as right side is not present so nothing needs to be inserted next node to be processed is two so for two who is the parent just look at the map it is five but five was already visited right it will be marked in the visited array so we cannot insert five let's see the left Point rate is seven it is not visited definitely we will insert it four is not visited we will insert it and we are done with level one as well so since K value is 2 we need to process only two levels so in this case we did for level zero and level one and whatever nodes are left in the queue those all nodes will be present at K hops in this case k equals to two hops so since the answer doesn't require any ordering you can simply return one 17 and 4 in any order possible so this will be your answer so this entire process involved creating a map to move from child to parent and then the second thing was understanding that the problem is a BFS problem and the third thing was just applying the BFS algorithm now the time complexity will be order of n since we are processing each node only once using the visited array we are not visiting the same node again and uh simple follow-up problems on this and uh simple follow-up problems on this and uh simple follow-up problems on this given problem can be what if the edges were undirected and what if you have Cycles so when the edges are undirected it will not be a tree it will simply be a graph which is not a tree and you may even have Cycles then so how do you solve that so this becomes a typical graph problem of using BFS visited arrays the techniques will all be same so you can just go ahead and think about it so let us now look at the code for this problem this is the code of finding all the nodes at distance K you are given the root reference and the target reference with an integer value of K we will simply be doing a pre-order of K we will simply be doing a pre-order of K we will simply be doing a pre-order traversal in order to make the child to parent map so this has been declared as a global variable so when I call pre-order I will be in making the map pre-order I will be in making the map pre-order I will be in making the map which was step number one after that I will be taking the queue for doing BFS and this is the visited array I was talking about you can take visited array you can take a map or you can take a set as well so I have taken an unordered set whatever notes gets visited I will just push them in the set simple now from here on onwards you just apply the simple BFS algorithm which is nothing but the level order traversal and after this whatever is left in your queue you just remove one item after another and just push it into the answer list and you just return the list this entire process takes order of end time or you can say order of V plus e time where V is the number of vertices and E is the number of edges but in a tree you will have edges of the order of V minus 1 so definitely you can say that it will be order of V time and I'll say that n is the number of vertices order of n so this is all about this problem if you want the PDF of this entire video solution you can follow us on telegram link for it will be in the description below you can follow us on Instagram to be updated with the recent interview trend I hope this video was helpful see you guys in the next video thank you
All Nodes Distance K in Binary Tree
sum-of-distances-in-tree
Given the `root` of a binary tree, the value of a target node `target`, and an integer `k`, return _an array of the values of all nodes that have a distance_ `k` _from the target node._ You can return the answer in **any order**. **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], target = 5, k = 2 **Output:** \[7,4,1\] Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1. **Example 2:** **Input:** root = \[1\], target = 1, k = 3 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[1, 500]`. * `0 <= Node.val <= 500` * All the values `Node.val` are **unique**. * `target` is the value of one of the nodes in the tree. * `0 <= k <= 1000`
null
Dynamic Programming,Tree,Depth-First Search,Graph
Hard
1021,2175
1,730
hello everyone let's solve legal question one seven three zero short is the path to get food and it's a median legal question you are starving and you want to get food quickly as possible you want to find the shortest path to arrive at any food or cell you're giving m multiplex and character matrix grid of different types of cell so star is your location there's exactly only one cell and that the pound is food cell there may be multiple food cell basically this one and o is the free space and you can travel through these cells and x is an obstacle where you cannot travel through these cells and you can take a look at the examples like the x is like the wall and you're not able to move there and you can travel to any adjacent cell north east south west of your current location if there's no obstacles basically it's for directionally moving return the length of the shortest path for you to reach any food cell if there is no path for you to reach food then return uh minus one so you can take a look at this example shortest path is you can go here so basically three steps or here three steps as well it takes three steps to reach the food and in this example you cannot pass the wall right it's simply impossible so you want to return minus one and in this case and you can see there are multiple food options here and i can go down to get the food from here or this one apparently by looking at this you know this one is further because you have to go down so then if you try to reach this food uh the pizza here and then the shortest distance is six it's uh pretty straightforward and you can see there are some constraints here and this is the definition and we can see that the company asked the question in the last six months amazon 12 times google twice by looking at this question you can kind of already tell it's the shortest path and you want to visit this layer by layer and in this kind of case you want to use breakfast search and it's really straightforward so you basically wanted to go through the grid row and columns to add your location first and append it to the queue and the queue is usually the data structure that you want to use together with the buffer search and after that you want to iterate through every single layer and then you can popping star from the queue every cell that you have visited just add it to the visit set and then after that what you can do is you can check that if um if you already find the destination which is the pizza here then you can just simply return the result and if not you just go up one layer search all its neighbor and as long as the labor uh the neighbor is not wall and you can continue to move and continue to add the cell the row column and add them to the business set and each iteration you want to increase your the step to plus 1 so that in the end you can calculate it through and if you popped everything from the queue there's nothing left in the queue and you're still not able to find anything then you want to make return minus one so i'm going to show you how to do this in code so um i know i will use a visit set to put the cell that i have visited there already and then i want to define rows calls equals to length of uh grid and co is length of grid zero right and then um so i want to use q as dq and i wanna i will append the value first so the next what i would do is i will since it didn't pass you the start uh location of where you are so you kind of have to go through the entire grid to check where your location is how to do that is for r in range of rows and for c in range of calls basically every single cell and then what you want to check is a grid or c if your grid rc equals to the star basically where you are you want to queue append the rc to this queue that's your star position so by now we already have your location in the start position already so what we want to calculate is the steps to reach the food all right so i will give the result as zero before i iterate go through the queue i will say while q happens for i in range of length of q so that i can iterate through every layer of the queue and then i would start popping this is like a format of uh buffer search pop q dot pop left i wanna because i put your location here where you are so i want to start popping this location and add their neighbors so rc and i already popped the location and once i pop it i want to say visit ad i want to add the rc to the visit set so i will need to go through the cell again and then so i would say if um i'll give it a base condition to check if grid rc whatever i popped whatever i added in this step is already reached to the food i think that is the food yeah if i already reached the food cell then i want to stop the iteration i will return result immediately right and then otherwise i will just continue to calculate its neighbor for the rdc in 0 1 and then 0 minus 1 and then this 1 0 i want to minus 1 0 and then i want to calculate the neighbor cell roll call equals to r plus the r in c plus dc and that's basically this cell and this cell four directionally um and then i'm going to do a contain uh condition check because if this is like a wall or obstacle i'm not going to be able to move to here at all so i can only move to this and then this position right so i would do check first check if it's within uh inbound and then rows and 0 minus equals to call minus calls and then i'm going to check grid row colon um so the grid for the row column if it's or let's see if it's um if it's a food cell you will actually be able to move there so i would say uh in here if this grid does not equal to x so meaning that if the cell that you move is not a obstacle you can move there and then what i'm gonna do is uh when that happens is i'm gonna q dot append this row and then the column and then visit i wanna add i want to add the neighbor to the row and the column and after the each iteration through the queue i want to add the result one to the result right and at the end of the queue if i'm still not able to find this um answer like this uh the destination where the pizza is i'm gonna return -1 in this case return -1 in this case return -1 in this case so i think that's it for the code yep it went through let's see what went wrong here so this is set um length of grid q equals to dq and i have the visit set and when i go through the four r and c in range of calls if grid rc equals to the star then i want to append the rc and then result equals to zero for i in range length of q then rc i want to queue the pop left visit dot at rc if grid rc equals to food the pizza then i want to return it immediately for dr dc in direction zero one 0 minus 1 and then i want to calculate the new neighbor count row cos equals smaller than cos and the grid uh row colon does not equal to x oh um so the other thing is uh i forgot to check that the rule column um has to i have to make sure that it's not in visit i have not visited yet because if visited again then i missed the one condition check if that is the case then i want to append this to the queue and then add them to the visit set and then yep it accepted i hope this is helpful and let me know if you have any questions please like my video and subscribe to my channel and i'll see you soon bye
Shortest Path to Get Food
special-array-with-x-elements-greater-than-or-equal-x
You are starving and you want to eat food as quickly as possible. You want to find the shortest path to arrive at any food cell. You are given an `m x n` character matrix, `grid`, of these different types of cells: * `'*'` is your location. There is **exactly one** `'*'` cell. * `'#'` is a food cell. There may be **multiple** food cells. * `'O'` is free space, and you can travel through these cells. * `'X'` is an obstacle, and you cannot travel through these cells. You can travel to any adjacent cell north, east, south, or west of your current location if there is not an obstacle. Return _the **length** of the shortest path for you to reach **any** food cell_. If there is no path for you to reach food, return `-1`. **Example 1:** **Input:** grid = \[\[ "X ", "X ", "X ", "X ", "X ", "X "\],\[ "X ", "\* ", "O ", "O ", "O ", "X "\],\[ "X ", "O ", "O ", "# ", "O ", "X "\],\[ "X ", "X ", "X ", "X ", "X ", "X "\]\] **Output:** 3 **Explanation:** It takes 3 steps to reach the food. **Example 2:** **Input:** grid = \[\[ "X ", "X ", "X ", "X ", "X "\],\[ "X ", "\* ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "# ", "X "\],\[ "X ", "X ", "X ", "X ", "X "\]\] **Output:** -1 **Explanation:** It is not possible to reach the food. **Example 3:** **Input:** grid = \[\[ "X ", "X ", "X ", "X ", "X ", "X ", "X ", "X "\],\[ "X ", "\* ", "O ", "X ", "O ", "# ", "O ", "X "\],\[ "X ", "O ", "O ", "X ", "O ", "O ", "X ", "X "\],\[ "X ", "O ", "O ", "O ", "O ", "# ", "O ", "X "\],\[ "X ", "X ", "X ", "X ", "X ", "X ", "X ", "X "\]\] **Output:** 6 **Explanation:** There can be multiple food cells. It only takes 6 steps to reach the bottom food. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 200` * `grid[row][col]` is `'*'`, `'X'`, `'O'`, or `'#'`. * The `grid` contains **exactly one** `'*'`.
Count the number of elements greater than or equal to x for each x in the range [0, nums.length]. If for any x, the condition satisfies, return that x. Otherwise, there is no answer.
Array,Binary Search,Sorting
Easy
null
503
Hello friends, in this video we are going to solve this problem with the next greater element, I will tell you in such a better way that even if you want to forget, you will not be able to forget, so please watch the video till the end, I guarantee you this. I assure you that if you watch the entire video then you will be guaranteed to understand it and even if you want to forget it, you will not be able to forget it. Like see what is the question, we have already solved the question of Next Greater Element or is there a next variation of the same, what is this? That is, our array is a circular array, which means that what we have to do is to return the next greater element found on the right hand side of whatever element of the array is and when you go near the last one, then any element on its right. If there is no element then after this you will again come to the first element and then check from here that means is this the concept of our circular array? So first let me explain the question to you very well and then tell me how things are working and How can you do this very easily? Okay, so look, what we have given is circular error, circular array is given, sorry error, no array, so what will I do, first understand carefully, I will tell you about the normal array, guess what we have. It is a normal array so if you are asked to find out the next greater element then what is the next greater element for one then you will say sir the next greater element for one is two then you will write two here and then you will go to k. What is the next greater element next to two, then there is no one next to two that is greater than it, there is no element here which is greater than this, then what will happen -1 Then you go to one, then -1 Then you go to one, then -1 Then you go to one, then what is the next greater element of one, you will say. Sir, if there is no element on its right, then what will happen - 1 Okay, understand, then what will happen - 1 Okay, understand, then what will happen - 1 Okay, understand it like 1 2 3 4 3 one, what is the next greater element of one, then you tell me sir, what is the next greater element of two is two. Tell me sir, what is the next greater of three, what is the next greater of four, if there is no one greater, what will happen - greater of four, if there is no one greater, what will happen - greater of four, if there is no one greater, what will happen - what is the next greater of 1, no one will be mine, this is ours, normal, now. Let me explain this example: normal, now. Let me explain this example: normal, now. Let me explain this example: Circular A. Now see what will happen, understand carefully now, understand carefully because now the turn has come to understand, this has become our normal array. If it remains a normal array then it will become our next greater element. One2 3 4 3 But What is said in the question now is circular a this circular what is the next greater of one two is two what is th what is three then what is fur see as soon as you go to four you will see that the greater of four is here three but three What will you do if it is not greater? After three you will start checking from here again. Is four's next getter greater than four? Three is not. Is four's next greater one? Is four's next getter two? No? The next greater of four is three, if not, then what will you do, you will assign -1, if not, then what will you do, you will assign -1, if not, then what will you do, you will assign -1, then you go to three, what is the next greater of three, if there is none in the normal array, then you assign -1, none in the normal array, then you assign -1, none in the normal array, then you assign -1, but when near three, you If you come here you will see that after three you can go to one again then what is the next greater of three? One is no is two is not three is not four is yes then what will be the next greater of three is four so in this case In this you have to return a output 2 3 4 -1 4 2 3 return a output 2 3 4 -1 4 2 3 return a output 2 3 4 -1 4 2 3 4 -1 4 And the earlier case which was a normal 4 -1 4 And the earlier case which was a normal 4 -1 4 And the earlier case which was a normal array which was not a circular array then in that case you had to return a output right so how will it be made now The question was that friend, if there was only a normal array then what would I do, I would just do nothing, use eta or use a double array, use a double loop, what would I do, I would grab one element and then write it. I used to check that the biggest element was found first, from this I used to assign it, then I used to come here, then I used to check its right, it was like this, which was its time complexity and n was squared, but Now how should I do it, now after four means the last index, after this I have to go to the beginning again, so how should I do one sir, so let's understand this, then how will it be like see 2 3 4 3 Now pay attention, understand if I am saying that after three I have to go here again 1 2 3 4 means after three like I will go to three or if I search for a greater of four then if I do n't find it here then what do I have to do then what to do with this It means that I have to traverse this same element again. I have traversed the 1st 2 3 4th element and what do I have to do again. I have to traverse this element, so whenever circular Area comes circular area so what will I do see 1 2 3 4 3 and again I will write this one more time 2 3 4 3 Understand carefully what we did whatever we have given array whatever we have Array is given, we know that in circular array the same array comes again means after three our one is coming, after three one is coming so after three look here 1 2 3 is coming again so what will I do which We will have an array given that I will add it to the same array like 1 2 3 4 3 so in this I will add 1 2 3 4 behind it, okay what will I do now like the next greater element is If we had taken out the next greater element, then we will start taking out its next greater element. Now I will take out from here, what is the next element, if there is nothing, then -1, what is the meaning of four, if there is nothing, then -1, what is the meaning of four, if there is nothing, then -1, what is the meaning of four, if there is nothing, then -1, what is the meaning of 4, what nothing, then -1, what is the meaning of 4, what nothing, then -1, what is the meaning of 4, what is the meaning of two. What is the meaning of one, what is the meaning of th, here is four, what is the meaning of four, otherwise -1, what is the meaning of th, otherwise -1, what is the meaning of th, otherwise -1, what is the meaning of th, what is the meaning of two, 3, what is the meaning of one, 2, then what I will do is I will add the same array to that and all I will remove the greater element and from the beginning like n e if phi if it has five elements then what I will do from the beginning is I will catch the five elements and return them then 2 3 4 -1 4 Our answer has not come Yes the 3 4 -1 4 Our answer has not come Yes the 3 4 -1 4 Our answer has not come Yes the answer has come When ours has come, first see how you have to think that Sir, I will not do anything, whatever array we have given, I will add it to this array, it is okay to add it in the last. So what happened if given, our circular concept is done because after three our 1 2 3 4 was going to come so after three again as I have added then 1 2 3 4 3 has not come, it has come now what will I do? Now what will I do, just like I used to find my next greater element, I will take out all of them, and then what will I do, because I only need the names whose length is fv, then what will I do from beginning to fv, I will return From the beginning till the end, our answer will not come, it will come but look at the work you have done by adding it here, you have added it again. Now what we will do is we will add it virtually, meaning whether in the answer or in the program we will make. You will not see it being added physically, but I will take its index value. It will remain added. How it happened, now understand carefully how it will happen. What you have to do, what you have to do, simply like it has come, how far have you got before, like 0 1 2 3 4 5 6 7 8 Aur kya na aa aapka fo tak hai aapka aa kitna hai four of this array original array ka aa kitna hai four jo aa aap palay were you starting here but if you have to add virtually then where will be the index value The last nine will start from i 2n - 1 2n - 1 so 2 * 5 - 1 i.e. 2n - 1 2n - 1 so 2 * 5 - 1 i.e. 2n - 1 2n - 1 so 2 * 5 - 1 i.e. 10 - 1 means 9 will start from 9 but you will 10 - 1 means 9 will start from 9 but you will 10 - 1 means 9 will start from 9 but you will not keep adding it virtually, right so I think you understood this. Well, let me draw it for you so that you can understand things better. Okay, so see what I will do. Understand carefully what I will do. Like we have a tooth 4th t 3 4th y. What will I do? Take out this size. I will take it, what do we have, it has come, okay, I have understood, our F has arrived, look, we have taken it out, now what will I do, I will keep a stack, it is stuck, so I will keep a stack once, what have we done, we have a stack. I have kept Y, stuck, okay, now what will I do, I will keep one answer, so I have kept one Y answer which will be of size, I have kept the answer, okay, now I will see what I will do, now understand carefully, I will start with i = 2n - 1, will do, now understand carefully, I will start with i = 2n - 1, will do, now understand carefully, I will start with i = 2n - 1, meaning this Our zero is then t 3 4 and since I am adding it virtually then 1 2 3 4 3 will play again so this is 5 6 7 8 9 the original element is our A. What do I do, I close it in the box so that you understand. I came in what is our array what did I do to it made it an array okay this was our index value okay now come equal to two I will start from here what I do is I take the ridge first why am I starting from the last Because what I told you that the next greater element, I start from the right because who is greater to the three, there is no one greater to the right of three, who is to the right of four, so I just Whichever is greater, I will compare with it. If I start from here, then for one, I will have to check everything. For Fatu, I will have to check all its rights, so I will start from here, then I would take the value of aa. Where am I from, I will check from the last one, I will check the value of aa from the last one, but I will store it in the answer, from where to where, just look from here to here carefully, I will traverse all, but I want the answer five. Of size five because I have tooth 4, this is the number of elements, so in the answer, I will store only this element which is greater, right, now see what I will do now, aa, our na is done, aa ira na is done, okay now the stack Unless it is MT, not mmm, but it is MT and then I wonder what is the lesson A, meaning do we have to store it in the answer only when whatever is the lesson A, the meaning of A is here. From here till here, the value will be there only then I have to store the answer, even if it is not there then what will I do, will I push this element in the answer, how will I push this element, how will I push, you know that What are the numbers? What is the value of the numbers? Pushed like if I push then aa minus then the value of aa will become how much now the value of aa will become a aa the value of aa has become at then I will check whether the atk mt is ours is not stuck so mt is not stuck not mt Is and the top of the stick means th is that less than hai Names of us A means four se and less than is yes less than then remove it because our th in the greater of four cannot be because that is our st The top of which is three is the same lesson, the lesson is from four, which is right in four, there cannot be a right which is greater than four, so what to do in this case, pop it, yes, our pop is done, okay then check what? Whatever has come, if you do n't want to take it, then what to do? Add push name means put four in the stack. We have put it then what to do. Aa minus aa's value has come and aa's target has been updated. Now check. Do it now, check whether the top of the skirt is laced with the four and the stem, no, it is not stopless, when there is no lace, then what to do, put the stitch inside the stem, then the condition will not be there, now it is not laced. So you have put 'Aa' in it, 'Aa' is reduced again. you have put 'Aa' in it, 'Aa' is reduced again. What is the top of the A and is it laced or not? Otherwise what to do, put the 'R' in this and not? Otherwise what to do, put the 'R' in this and not? Otherwise what to do, put the 'R' in this and you have put it in this and then what to do is to reduce it to 'F' and it is done ' do is to reduce it to 'F' and it is done ' do is to reduce it to 'F' and it is done ' F' now then check. Do what is F' now then check. Do what is F' now then check. Do what is one which is the top of t is two is it less than one if not then put one in it and reduce the value of i to 1 then the value of i becomes four. Now see now from here it is important to understand. There is a thing to be understood from here, what is to be understood from here, now listen carefully, now we have to check again, now what is the value of i, four while stuck not ill to i and stuck ka jo top hai stuck ka jo top How much is one kya less than names of i muddle n i how much is the value of i become four 4 mddle n what is the value of fi meaning four which is the four of the stick how much is the four on four what is the top of the thr what is the top of n It means one, that is less than three, yes, there is less than, so what to do, as long as there is less than, it is equal to two, keep removing it. As long as there is less than, it is equal to two, then keep removing, this is also less than, remove it, lesson. Remove equal to less than is equal to remove this is our less than is not equal to two it is greater so what to do in this case now come to the lesson if n is then what to do in this case top of eta in the answer what is the top of a four A ka top kya hai four to four ko ya keep ko answer you kept ya answer kept again what did you do jo nama ama aa aka l kitna hai ab ko what will you do me If you push, what will I do? I have kept it in the corner, I will also write 'Y' and ' kept it in the corner, I have kept it in the corner, I will also write 'Y' and ' kept it in the corner, I have kept it in the corner, I will also write 'Y' and ' Fo'. Again I have Fo'. Again I have Fo'. Again I have put 'F' and again 'T' has been put in it. Now the put 'F' and again 'T' has been put in it. Now the put 'F' and again 'T' has been put in it. Now the value of aa will be reduced. Now the value of aa has come here. The value of aa has become our three. Right now the top of the stick is it less than what is less than that. Yes four to yes four to less than. What to do with four then remove it d remove it means if there is no three in the greater of four then remove it, what is the next lane of four, yes of this also, remove this and what to do in the last place now Look what is the top of the Atai which is MT if stuck is MT then what to do in the answer if stuck is MT then if you want to put mive in the answer then put -1 in the answer right and then put -1 in the answer right and then put -1 in the answer right and then what to do like if you come out of it then put it in the stack If you have to push this element, then what you have to do is to push this element in the stack, push means four, then again you put this four in the stack, okay then you will have the value of a, th a will become two. What will you do? Whichever is on top, you will put it in the answer, right, so what did you do, put it in the answer, as you put it in the answer, what do you have to do, you have to go back again, now you have to check and Before that, what has to be done is to put this th in it. Then is the two which is two greater than that three? Is the three which is less than two? No? What to do when it is not less than two? What is the top of the stack? i is the top of the stack, it has to be put in the answer and at the same time two has to be put in the stack. You put two in the stack, then you went back to the stack. Now the value of i has become zero. Now you will check that you also put two in the stack. Put what is the top of the stack 2 and less then equal to two is one If it is not there then what to do is to take out the two and put it in it and put the one in it and in the last which is our The answer is still left, if we do minus then it will be finished, there is no index, so what to do with it, reverse it, so 2 3 4 -1 4, it has to be reversed, I 4 -1 4, it has to be reversed, I 4 -1 4, it has to be reversed, I want 2 3 4 -1 4 2 3 4 -1 4 So this is what want 2 3 4 -1 4 2 3 4 -1 4 So this is what want 2 3 4 -1 4 2 3 4 -1 4 So this is what I want, so I think you got this and you understood, you see what you have to do, you do n't have to physically append the entire array, just get the index value from here. All you have to do is start the index value here and in the answer you have to store it only if i is less than n because in the answer I want only from here till here the answer is where I want i lesson n one Minutes What I do is change the marker You only need up to four in the answer So when a condition is true You have to put it in the answer So I think you have understood all the explanation as well as the code and just in case You did you subscribe the channel, what do I do, now I move ahead in the video, I will tell you this time committee, when you talk about this time complexity, then look, you are feeling 2n here, if you do it then it will become t o 2n. But in the world's world, it will be considered as the same and you are also using the space. So, it is yours, so what do I do, I will show you the solution of Java also, this is our Java solution, it is same to the same. Also, we did not hit any arrow, it is the same code, same to the same, there is nothing extra in it, let me run the code and show you, okay, but before that, if you want to read DSA in a very structured and organized way through a notes, then you can read this link. You can take it by going to , it is very structured and can take it by going to , it is very structured and can take it by going to , it is very structured and organized, the link of which will be found in the description or if you want to take any course of GFG like DSA Development, then you can go to this link and use Trillo 10 coupon code. If given then you will get instant discount of Rs 15 at the same time and you will get the link of both in the description, apart from this you will be getting that too, you can go and check it out, so now let me run the code and show you, okay So see what I will do now, I will take you to my lead code and this is our c+p code to my lead code and this is our c+p code to my lead code and this is our c+p code which I told you is the same saying code, I will simply click on submit. Now many people might not have understood that I Modulus. Why am I doing n? I am doing modus n so that I have to keep the circular array concept so after four I have to go to zero again right then 0 1 2 3 4 then after that I have to go to zero right so that's why I have done this, now what will I do, I will show you the Java code, so this is our Java code, I will simply click on submit and if you have any doubt related to this, brother, if you have not understood then you can definitely comment. New channels. If you have come then you can subscribe the channel, like the video and share it with your friends, friend, let's meet you in the next video with some such videos till then keep supporting and keep exploring.
Next Greater Element II
next-greater-element-ii
Given a circular integer array `nums` (i.e., the next element of `nums[nums.length - 1]` is `nums[0]`), return _the **next greater number** for every element in_ `nums`. The **next greater number** of a number `x` is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return `-1` for this number. **Example 1:** **Input:** nums = \[1,2,1\] **Output:** \[2,-1,2\] Explanation: The first 1's next greater number is 2; The number 2 can't find next greater number. The second 1's next greater number needs to search circularly, which is also 2. **Example 2:** **Input:** nums = \[1,2,3,4,3\] **Output:** \[2,3,4,-1,4\] **Constraints:** * `1 <= nums.length <= 104` * `-109 <= nums[i] <= 109`
null
Array,Stack,Monotonic Stack
Medium
496,556
35
in this video we'll be going over a search insert position so given a sorted array of distinct integers and a target value return the index if the target is found if not return the index where it would be if it were inserted in order so in our first example we have one three five and six and our target is equal to five is found in our in the input rate at index two so we turn two in our second example we have one three five and six and our target is equal to two is not inside our input array but it can be inserted at index one so we have one two three five and six so let's first go over to that process we are trying to look for elements or insert position inside a sorted array when looking for it when looking for an element inside a shorter array the most optimal approach will be to use binary search so for each of the elements at index mid if nums mid is equal to target then we have found our element so we can just return the index so we will return mid if nums mid is less than target so in this example if our current target is go to 2 if our target is good to 2 and we're currently at index 0 here if one is less than two we want to search rightward from mid plus one from bit plus one then if nums mid is greater than target so in this example if we're currently at index at this index of the number 3 and 3 is greater than 2 this may or may not be the insertion index so we need to search to the left with three inclusive so we need to search to the left with mid inclusive let's go over the pseudocode so we'll create two variables left the current left boundary and the right to current right boundary initially at the end of the rate then we'll promote binary search while left is left and right calculate the mid index if nums mid is equal to target we have found our target index so we can return mid and then else if known's mid is less than target we need to search to the right with mid inclusive so we set left it goes to mid plus right mid plus one and then else we search to the left with mid inclusive and then if nums left is less than target the mean this means the whole input array has elements which are less than the target so in this example we have one three five and six where all the elements is less than target so insertion index is right after the end of the array at index four so we have to return left plus one else we can just return our insertion index at return left let's go over time and space complexity then time complexity is equal to oh log of n where n is the length of the input rate this is for the binary search and our space complexity is equal to old one because we're not creating any extra data structure let's go through the code so create our two boundaries perform binary search calculate mid index and then if nums mid is equal to target we have found our target index so return mid and then else if norm's mid is less than target then we need to search to the right so we said left let's go to middle plus one else we search to the left with mid inclusive and then return if nums at left is less than target that means the whole input rate is less than target so we turn left plus one else return just turn left let me know if you have any questions in the comment section below
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
1,358
Hello Everyone And Welcome Back To My Channel Algorithm HQ Today I Am Going To Write The Code And Also Explain You All The Algorithm To Solve This Number Of Sub Strings Containing All Three Characters Problem Which Is There In Lead Code Again It Is A Part Of Also like the video and also subscribe to My channel if you have not already is datchi and it can contain only letters A, B and C. Apart from these three letters, there cannot be any other letters. Okay, so we have to tell all such substrings of that A which also contains A. There must be at least one occurrence of all the three BCs, there can be more than that, but there must be one, that is, all the three A, B and C must be present at least once. It is fine, as seen in this example, S E A. S and A S again, okay, so what are the substrings being formed in it, A B C, because A is present once, A B C, all three, A B C A is present twice, B S, A is present once, okay and A. B C A B is like this in this also A B C Sorry A B is present twice and C is present once so it means once is present in every substring only then we are considering it, so do it like this here. But 10 substrings are being formed, so basically how are we going to solve this, we will take a particular window like now take ABC, okay and in that window we will see that if one array is present in the list of any element then we will open that window. Taking that window as a considerable window value, how many further substrings can be made, that is, how many further substrings can be made using the number of further elements that are left? bcc950 Okay, so from now on when we contract it, this BC will be saved. Okay, now why are we contracting from now on, so that we can also consider the window in which all three BC and A are present one at a time and consider that window also. Find one in which all three are present more than once, okay, so if we look at this example, till we reach the last index, we will not get such a thing that all three are present once, okay, last index. Only when we reach P will we get such a window in which all three will be present one at a time, so its answer is one, but still it is not, its answer is three, it is such that we have considered this entire substring once but will contract from it further. Due to which we were able to consider the window in which A was present thrice, then came the window in which A was present twice and then came the window in which A was present once and the remaining two elements were present once each. The same was present in the earlier window too, it is okay, so we will contract it, now how are we going to do it exactly, let us see using this example. Okay, so we will maintain a frequency array in which the frequencies of all three will be A B C All three are ok and the rest will keep start and end and answer. Start and end are two points ok through which we will maintain the window and answer in which we will store the answer. Ok so in starting we are at zero. Ok index is at zero so what will we do. Zero Whatever element is on the index, its frequency will be changed from zero to one, that means we will keep incrementing one by one. Now we will check again whether we have found one currency or not, we have not found all three. Okay, then what will we do? Which element was at the index, sorry, and which element was there, we will increase its frequency again and will check again. Is one currency of all three found? If not, then again that element will go to this second index. Sorry, yes, we will go to the second index and that But we will increase the frequency of whatever is present. Okay, now we have got a window that is ABC in which all the three elements are present one at a time. Okay, so what will we do now? We have to take this window. And we have to create substrings by using all the elements present in the future, so what will one become? All those substrings are ok so what is the number of substrings length minus end is ok length minus end what is length in this case six and end what is we have two ok so by using this window we have four substrings created so we We will update the answer to four. Okay, what will we do now? We will start contracting the window from here. Okay, ABC, so now we started from here on A, so now we will subtract one frequency from one. We will go back to zero and move the start forward from zero to one. Okay, so now we don't have one array of each of the three. Okay, we only have one array of B and C, so now moving the end forward and And P is present A, okay, we will take that and increase its frequency again from zero to one, now again we come to this window BCA P is okay, what will we do again using this, we will try to create substrings and how many substrings. If three are formed then 4 + 3 will become 7. substrings. If three are formed then 4 + 3 will become 7. substrings. If three are formed then 4 + 3 will become 7. Our answer has been updated. Okay, now what has happened again is that if we get one currency then the window means that we have already used this window, so we will contract again at the start, whatever. Element A will be removed, its frequency will be reduced and the start will be moved forward. Okay, so again it becomes zero. Again, a and c have a difference but b does not, so again a is a and b will be added to it, meaning. We will add one to its frequency and will move the end forward to make it four. Okay, now what will we do? Again the length means 6 minus whatever end is there. If we subtract from that then we will get two, so here it will be 7 p. What will we do now? We will move the start forward again, contract that window and reduce the frequency of whatever was there at the start to zero. Now we have a window in which all three are not present at one time, so then We will move forward from end to end and will add whatever is present at the end. Okay, now once again one frequency has come. Okay, now what will we do here? 6-5 That is one, here we will add 6-5 That is one, here we will add 6-5 That is one, here we will add plus in the answer. Okay, now when we move forward, we mean we will contract, then when we four from r, then again one a will be reduced. Okay, and then what we will do is try to move the end forward. When we move the end forward, we will definitely get some element on it. No, so we will end the loop and we had to do 9 p 1 10 here and return 10 from here. Okay in the answer, so by doing this we will solve this question by expanding the window and contacting the window back. Okay and I had already told you why we are doing the contract, now let's quickly code it. Okay private int, ok this is sorry, there is no need of any extra function in it to store the int a b c frequency. For this, its length will be three, then we will take one start, we will initialize it from zero, we will take one answer, we will initialize it from zero, then we will take for loop from which we are going to add it will be a variable and we will initialize it from zero, it should be less than s dot. The length is fine, then we will make the end plus, then in ABC, every time we will increase the frequency of whatever element is present at the end and how to find its index will be by minus a from it because if ABC is C then it will be 0 1 2. Okay, then we will see that the frequency of all these three is more than one, if it is okay then this loop will run, ABC is present at zero, if greater than is equal to two and then whatever is present at one is all. Greater than equal to two and a BC Greater equal If these are all three, then first considering our window, we will do all the strings in it plus the length of the array I mean string minus which is our end currently okay, then after that starting. If we contract from ABC then we will start the caret from ABC, we will make it minus, okay and if we move the start forward, then we will make the start plus here, okay, that's all we have to do, okay and from here the answer. If you have to return, sample test cases are being run, let's see after submitting and if the submission has been done successfully, then we have solved this question. Before going on, please like the video and subscribe to my channel if you have. Already and also please tell in the comment section what improvements have to be made to the content and anything else also that is for the video Radhe
Number of Substrings Containing All Three Characters
find-positive-integer-solution-for-a-given-equation
Given a string `s` consisting only of characters _a_, _b_ and _c_. Return the number of substrings containing **at least** one occurrence of all these characters _a_, _b_ and _c_. **Example 1:** **Input:** s = "abcabc " **Output:** 10 **Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_abc _", "_abca _", "_abcab _", "_abcabc _", "_bca _", "_bcab _", "_bcabc _", "_cab _", "_cabc _"_ and _"_abc _"_ (**again**)_._ **Example 2:** **Input:** s = "aaacb " **Output:** 3 **Explanation:** The substrings containing at least one occurrence of the characters _a_, _b_ and _c are "_aaacb _", "_aacb _"_ and _"_acb _"._ **Example 3:** **Input:** s = "abc " **Output:** 1 **Constraints:** * `3 <= s.length <= 5 x 10^4` * `s` only consists of _a_, _b_ or _c_ characters.
Loop over 1 ≤ x,y ≤ 1000 and check if f(x,y) == z.
Math,Two Pointers,Binary Search,Interactive
Medium
null
1,319
hello so continuing on this little code weekly contest 7171 so the third problem was number of operations to make Network connected so what the problem says is we have in computers numbered from 0 to n minus 1 and they are connected by some Ethernet cables connections forming a network where the connection when you when we have a connection that's position i8v means that there is a cable connecting A to B computers a and B and then any computer can eat any other computer at the direct or indirect and direct it through the network so for example here is your courage to by going in there directly from 0 to 2 or 0 1 2 and then given an issue of computer network of connections you can extract certain cables between 2 directly connected computers and plus place them between another pair of disconnected computers to make them directly connected so for example here we have this cable connected 1 &amp; 2 but 1 we have this cable connected 1 &amp; 2 but 1 we have this cable connected 1 &amp; 2 but 1 &amp; 2 are already connected via 0 here so &amp; 2 are already connected via 0 here so &amp; 2 are already connected via 0 here so we can just move this cable over here and connect 1 &amp; 3 with it there are way and connect 1 &amp; 3 with it there are way and connect 1 &amp; 3 with it there are way we can make the entire network connected and so the problem asks us to return the minimum number of times you can do such operation where we get a cable out from a redundant connection right because connecting 1 &amp; 2 year is redundant and connecting 1 &amp; 2 year is redundant and connecting 1 &amp; 2 year is redundant and we connect to that one connected 1 &amp; 3 we connect to that one connected 1 &amp; 3 we connect to that one connected 1 &amp; 3 so the minimum number of those that we can do we need to return it if we can't connect the entire network using this interest and minus 1 and so there are the other examples are very similar and then the boundaries and is all the way it can get to 10 to the power of 5 connection lengths same almost similar thing it can get there and then so the balls are kind of the bigger set big so we can do an open square solution if another okay so now let's see how we can solve this problem okay so let's see how we can solve this problem so if we the what the problem said is that we can we want to find the extra cables basically and then we want to see if those are enough to connect the entire network and then are they enough to connect the entire will Network basically not really are they enough but how many can we use to connect entire network to connect inter to connect all computers essentially so they can be more that's fine but if we can't if it's less the number of extra cables is less than we need to return minus one if we can't we need to return minus one so if you look at this then we need to okay we need to find the number of extra cables so that's like the first step we need to do so find the number of extra cables and then after that we need to find the number of unconnected computers right number of unconnected computers and then from there we can just check if number of extra cables well is less than the number of unconnected component computers that means we can't write that means we return minus one otherwise which means there are enough extra cables then what should we return so we know the number of unconnected computer so if you have for us a three and connected computers or maybe it can be like these are connected right and this is maybe with another one so these are two are connected so to connect these three together what do we need well we need a link between these two so once we put this link well it became connected with all of them and then when you didn't link either between this one in this one or this one and this one so needed only two legs so for three components we need only two links and that's this that's basically a general case right like for M components to connect them we need n minus 1 edges so here that means we need to return components minus 1 right number of unconnected components which is just the number of components actually right so it's just components minus 1 return components minus 1 and so how can we do this so finding the number of components here we can do that with the with Union front or decision set right so we can do it with data structure called Union find to try and set right and so also the we can find it with DFS but for this if we use Union find we can find the number of extra edge the cables by doing Union and find let me explain why so let's see if we have let's take an example so for the 0 the first example that we had there in the problem so we have 0 1 2 and then we have 3 year we had links between 0 &amp; 1 have 3 year we had links between 0 &amp; 1 have 3 year we had links between 0 &amp; 1 and between 0 &amp; 2 and then we have an and between 0 &amp; 2 and then we have an and between 0 &amp; 2 and then we have an extra one here and then we have 3 not connected right so when we are doing Union find first we have these here right we have 0 and then we have 1 as a components and then we have this as component and the parent of 0 is just 0 the part of 1 is just 1 and the parent of 2 is just 2 now we go through each collection so we go through the connections in order to Union them so we will have to write Union and find but for now let's just suppose we have Union that can Union two nodes if you are not familiar with Union find I suggest that you look at that up first but it has this one that can your Union two nodes and then we can have find that finds the parent or the representative of this set and so for a node so we have these two functions to find now we will need to go through the corrections that we have so for every connection but these are the two edges in the connection so what we need to do is we will need to take get the parent for each one of them so the point of view would be finding the part of U and P V will be finding the part of it right and so now if both are in a different components which means that their parents are not the same so basically being in the same component means that part are the same here in this union-find framework here or this union-find framework here or this union-find framework here or context so if both parents are different that means they are so there is an edge between them but they are not hitting the same component so we need to Union them so that will put them the self confidence because they are connected right so if you have something like this and then you have this and you already set up the components for this well this is part of the component as well so we need to include it so that's why we do Union of U and V now if the parents are already equal like the case here so if we once we do this so once we let me just get this back so from this case once Union 0 and 1 because we find an edge between them what do we get something like this 0 1 and then we have 2 here and then we have 3 years still so what we have now this component right because we Union them and so 0 is let's say you choose there are that presentative in the step after that what will happen is that well now we also find the link to 0 in to we because we are traversing the connections so now we would have 0 1 and then 2 and now we have this entire thing as a component right and then we have we Traverse we process the link 1 &amp; 2 but now if we process the link 1 &amp; 2 but now if we process the link 1 &amp; 2 but now if we will find that the parent of when we do find 4 0 sorry we are processing the link so processing the link 1 2 so what we will find is that find of 1 is equal to 0 because we already put them in the same components and then find of 2 is the same it's 0 2 right so that means they already aren't the same components but there is still an extra edge between them so that means we found an extra edge right so found an extra edge because they are already in the component in the same component and we find another edge that connects them so here in this else here that means we have an extra edge so we need to initialize a variable here that keeps track of the extra edges and we need to increment it here so you can see here with union-find we can both find the with union-find we can both find the with union-find we can both find the number of connected components and we can find the number of extra edges and so once we do this how do we know the number of components so in order to find the number of connected components we can just get the so in order to find the number of connected components we need to get the D we can just do find again right so we can just take the set of the find u so this will give us all the parents right for you in the range of n right so this will give us all the remaining so it will give us all the parents of and then that would be unique because of the set and now we'll get the length the number of components by just getting the length so this will give us the common number of components and now how can we know that we have enough to connect so now we found the number of extra cables we know the number of connected components and the number of connected components is just the number of unconnected parts right and now we need to do the check right we can just check if the number of extra cables is less than the number of corrected components we'll return minus one otherwise when it's in the number of components minus one so we just do if extra edges are less than components minus one then we return minus one otherwise we return the puritan components minus one right and that's all there is to it we will need to define Union and find according to Union find data structure like implementation but essentially what we will be doing extra is just going through the connections connecting everything that and putting everything in a component that is already connected and then if we find that there is an edge that connects two elements or two nodes that are already connected then that's an extra edge so we counted and when we do the Union find for all the connections we now know the number of components and we can just do the extra check the number of extra edges if it's less than the number of components minus one if it is that means we don't have enough edges enough extra edges over a 2-1 edges over a 2-1 edges over a 2-1 otherwise we need to return what we need to connect the components which is just components minus one okay so now let's just write this in a more organized way in our late code and see if it passes the test cases so the first thing we need to do is write our Union data structure right so we need find for a node or let's call it x and y right and then we need so they're not the nodes that we have are just let's just put them in this data it's just a list of range from zero it's just from 0 to n minus 1 so let's just say list of range of man and now to find for a fad for finding in a union fine we just check if the parent of X is X itself if it is then we are done that we can't that's the parent right because in unit find the pant is the value for which its own parent is it stopped right so at that point we can if it's equal to you can just return it right otherwise we look for the parent of its parent because that's how you need to find work right it's part is the parent of span and keep going and to reach the upper level pattern so we do find up there X and then for union it's pretty straightforward we just say the parent which is one of them we make one of the part of one of them be the parent sorry we make the parent of one of them be the power of the direct parent of the other one that's how it works so we just take the parent of one and make it the overall parent essentially right okay so now we'll go through the edges in connections and we will take the finder part of you the part of B as we said in the overview so we do that like this and then we check if they are different them is they are not yet in the same components but here they share an edge so that means they are in the same component so we need to Union them otherwise they have the same parent so in the same component which basically means that they are in the same components right but there is an extra edge that they share but and so here that means that we have an extra edge so we need to count that right so we count the X right and once we are done here we have we can know the number of connected components and so to know that number of components is just the length of all the parents of the sets right and so to find the part of the sets that just that's just T so we put them in a set to get the unique ones and so the set here is so for each node in the range we found it and find its parent and because we are doing set we get unique ones and so we'll get only the unique representations of components which will give us the number of connected components and so now we can do the check if the number of extra edges so extra edges if that's less than the number of components minus one so this is what's required to so this is required links alright so this is the links that we needed so if the number of extra edges is smaller than those that means we can't panic we can't cut the components we can't connect to the entire network so we need to return minus one otherwise that means that there are enough extra edges so we can just return how much we need so we need the wire number of lights right and that's pretty much it so I suppose one this yeah okay lah submit okay so this solution passes so one thing we can notice here though so there is another way to solve this one so it's actually we don't need to contact righteous why is that because the extra edges here will count them so that we can return -1 right if we can that we can return -1 right if we can that we can return -1 right if we can detect if it's if we need to return -1 detect if it's if we need to return -1 detect if it's if we need to return -1 if we don't so that we can detect that we don't have extra edges but actually you can do that easily with just here you can check if the length of the connections is so if the length of the connections is less than n minus 1 so we know that for a graph the number of nodes the number of edges needed to connect the entire graph is n minus 1 that's so we know that right we have n nodes right in order to connect all of them with n minus 1 edges so if we have less than those that means we certainly don't have extra edges enough to connect all of them so can return minus 1 but otherwise if we have either n minus 1 or more then by definition one of them the rest that are not the in minds when H is needed are that are not connecting to other nodes they are connecting the same nodes multiple times right so we don't need actually to count extra edge you can just say okay if you don't have enough edges return minus 1 otherwise now we just need to find the number of unconnected things or unconnected nodes or the number of unconnected components and we can just return that minus 1 right because in order to connect those and connected components we just need to get the number of them and to minus 1 right just by treating the components as if they were nodes in order to connect 3 components we need two nodes right we need two edges right and so that's what we use here so we will keep this the same except we don't need to count the extra edges so we can remove this we still do Union and fine to connect to get the connected components so now we know the number of connected components but now we don't need to check this we can just directly return the extra the required length and that is just the number of connected components minus 1 and that's pretty much it so if we submit this it still passes right so now so well we actually have another way to just to show you another way of doing it we have another way of counting the number of connected components without doing Union fine unified is a little bit complicated because yeah I'm not used to implementing it so maybe it's a little bit complicated but we know how to find the number of connected components using DFS right and so we could just use DFS here and so in order to use DFS let's just keep this because this is needed we it allows us to know if there are enough extra edges or not but here we just change how we compute the number of connected components so how can we do that so we can just construct a graph and do DFS right so we need a graph and we need the number of visited nodes so our graph would be ticked of either a list or a set I'm going to use a set here to have only unique edges and that's the visited set and then I will go through the connections and basically since it's an interrupted graph or add for you and now we can start doing DFS so our DFS that will come the connected components and so DFS starting from a node or check if the node is in visited while this is not a connected components because it's already included in another connected component that won't be counted separately so we need to return zero and then we need to say if it's not and visited then we need to add it to the visited because we just visited it by calling this function and we need to go through its neighbors and call DFS on each one of them so that this all forms one connected components right and we'll return one because this forms one connected component starting from this you right and here we need to call DFS on every node and then just get the Sun because any node that was already included in another connected component will be skipping here with this return zero so getting the Sun will give us the unique connected components or you could do it differently here which means let's just initialize the number of components like this equal to zero and we could say for I in the range of so these are the nodes right range of n then we can check if then we can just call the FS of I and then whatever result we get that we add that to the number of components right so if I was already included in a component organ zero because it's already visited if not we'll get one and it will be all those that are connected to it will be added to visit it so we won't count them again and that's pretty much it within the components at the end so let's run this so here we will make sure we have enough extra jizz and we count the number of uncollected compound and collected places which is just the number of components and just we return there number minus one because that's the number of edges we need and suicidality okay so this passes a slight small modification that women we may want to do here this is not really necessary so we can just do the sum of DFS of I for I in range of and this does the exact same thing and should give us the same result okay so that also passes yeah so these are three different ways to solve this problem yeah so that's it for now thanks for watching and see you next time bye
Number of Operations to Make Network Connected
unique-number-of-occurrences
There are `n` computers numbered from `0` to `n - 1` connected by ethernet cables `connections` forming a network where `connections[i] = [ai, bi]` represents a connection between computers `ai` and `bi`. Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network `connections`. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected. Return _the minimum number of times you need to do this in order to make all the computers connected_. If it is not possible, return `-1`. **Example 1:** **Input:** n = 4, connections = \[\[0,1\],\[0,2\],\[1,2\]\] **Output:** 1 **Explanation:** Remove cable between computer 1 and 2 and place between computers 1 and 3. **Example 2:** **Input:** n = 6, connections = \[\[0,1\],\[0,2\],\[0,3\],\[1,2\],\[1,3\]\] **Output:** 2 **Example 3:** **Input:** n = 6, connections = \[\[0,1\],\[0,2\],\[0,3\],\[1,2\]\] **Output:** -1 **Explanation:** There are not enough cables. **Constraints:** * `1 <= n <= 105` * `1 <= connections.length <= min(n * (n - 1) / 2, 105)` * `connections[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * There are no repeated connections. * No two computers are connected by more than one cable.
Find the number of occurrences of each element in the array using a hash map. Iterate through the hash map and check if there is a repeated value.
Array,Hash Table
Easy
null
528
uh let's talk about the random peak with weight so you are given a in array and then the inner rate uh is going to be what uh you want to find out the probability for every single index so uh let me do the drawing so the calculation is this w i over some y that's some w right so the sum is x equal to y uh in this case it's four right and then for every single index it's gonna be one over four comma three over four right so this is twenty five percent this is seventy five percent right all right so if you do like this it's pretty straightforward for the problem as well the problem will be your brain your random function so how do you pick the value between zero to the last integer in the array right so again so this output will be probably uh different than yours because it's different in mind because my random peak rating function is not the same as uh sentence this problem right so above but the idea of ish i mean should be the same so what do i have to do is i'm going to use a prefix function so put a prefix idea so i'm gonna just keep adding my value for the curve index so if my array is w equal to one w so using the previous some ideas it's gonna be one this is gonna be two this is gonna be four and eight and one fourteen right so this is a perfect sum w this is another array of blue sum and then my total sum will be what the sum will be equal to one plus one two plus two four both bars four eight a plus 6 14 and this is not coincidence this is not this is the math and then i will i would definitely pick a number between 0 to 15 times 0 to 14 and then this is why this is exclude 14 and it includes the right so it is from zero to 13 sometimes right so again i mean for evaluating the w right this is going to be one this is gonna be about uh fourteen over eleven affordable one i mean one over fourteen this is one over 14 and this is what 2 over 14 this is 4 over 14. this is 6 over 14 right and then if you know the probability right if i pick a number between 0 to 13 just include it right so if i pick a num between 0 to 13 right so if i pick 0 right you know if a number is 0 and i'm going to from w sum right from left to right to see if the random number is actually less than the current value if this is true i'm going to return the index okay so if you notice 0 is going to be return index 1 zero right and then this is because well this is because this is only one probability right so in this case you only have zero right and in this case you only have one two minus one and then this one is one four minus two a minus four fourteen minus eight six right so if you notice this is what exactly the numerator right numerator so that is right numerator right and then we can actually just conclude like uh this is a probably the same scenario and then later on i will just return the index and this is the solution so let me start putting so i need a i need another and any another w sound right so w sum will be initialized uh by w array and then right and then i'm going to just uh keep updating my w right starting from 1 because uh there's no meaning to update uh the index view so w i wi is equal to uh w i plus w i minus one and after i have a i'm going to just w sum equal to w right so whatever w change and double sum will be changed right and uh you so i basically like remain the industrial for the w and then and everything i will be just keep updating the previous prefix so right so again keep uh pick index function uh it determines the render function i'm going to just close the window right now i put a new render name random content and i'm going to give a randomly uh integer right so random it's equal to what i'm not typing in because the red container will return a double or four right so i'm going to say other connecting and this is from the uh this is the range is from between zero to the last image right so it's going to be what download song and then i need to know what's my largest value um in the uh in my uh w sum right so the largest value should be the last index inside the double sum so i'm going to traverse the entire array for what on that right and then if my random num is actually less than the w sum i prefer this i'm going to return right so again if you didn't know what uh what's the problem probability right so you can rewind the video and then just see what happened to uh to my exponential and then if you cannot find anything you will return negative one and then this is the solution so if i have a zero typo uh i do have so this is one line five and nine five first right over here i less than right and then this is the solution so look at this my output and expect output is different this is because my render function my renal function is different but the probability should be the same right so if you submit right so let's talk about time in space this is going to be a space right this is all of n and represent i mean all of w right i'll be representing the uh w array right and then for the time this is all of w right and then this is all of w so it should be less than and if you have any questions leave a comment below subscribe to opponent and i will see you next time bye
Random Pick with Weight
swapping-nodes-in-a-linked-list
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index. You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`. * For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`). **Example 1:** **Input** \[ "Solution ", "pickIndex "\] \[\[\[1\]\],\[\]\] **Output** \[null,0\] **Explanation** Solution solution = new Solution(\[1\]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. **Example 2:** **Input** \[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\] \[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\] **Output** \[null,1,1,1,1,0\] **Explanation** Solution solution = new Solution(\[1, 3\]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem, multiple answers are allowed. All of the following outputs can be considered correct: \[null,1,1,1,1,0\] \[null,1,1,1,1,1\] \[null,1,1,1,0,0\] \[null,1,1,1,0,1\] \[null,1,0,1,0,0\] ...... and so on. **Constraints:** * `1 <= w.length <= 104` * `1 <= w[i] <= 105` * `pickIndex` will be called at most `104` times.
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
Linked List,Two Pointers
Medium
19,24,25
140
hello friends today that's the word break 2 problem given string s and the dictionary of strings will dict add spaces in f to construct a sentence where each word is a valid dictionary word return all such possible sentences in any order this problem is different from 139 because that problem only asks us whether it can be divided into several words that in word dictionary this question asked us to construct all such valid sentences uh i'd like to remind you that we don't necessarily it is unnecessary to return the minimum length of sentences you may mix up this question to what letters too would like to ask us to return the shortest transformation but this question don't ask about a minimum length so for example in this example we split into four words in the word dictionary in this example we only uh we split two three words in word dictionary so ending is ending sentence is correct only we only need to split into words that exist in what dictionary so how do you solve this problem uh well let's think about it example if this is the input s and the word dictionary these two are possible sentences uh because cats is in vertical and then and dog and the cats cat in and the sets also in and don't also eat so what should we do at this time point um we need a pointer or index we should iterate all the characters in the string right so when we have a begin index let's say start from zero then the current chart is c we also need an end index so that we get a substring for example if the current and the index is in two so we have a substring right s sub string zero actually three because uh the ending next is exclusive so we have cat then we check cat where the cat is exist in what dictionary yes if it exists uh we may want to append this cat in some result string or something then we use the same function to handle the rest of this string because we uh essentially do the same thing when we get a cat then we can let her begin x in uh at this s and then we iterate to the end index check whether s is in what dictionary and the sa in the dictionary or s a n is in dictionary so on so forth so this problem is just a uh i mean standard backtracking problem so let's uh this is what i drawed uh it's just so we use index and we check c a c ht and we find cet in the dictionary then we handle the last part so s-s-a-s-a and s-a-n-d in the so s-s-a-s-a and s-a-n-d in the so s-s-a-s-a and s-a-n-d in the dictionary then wear it and then we find dog is also in so what's next is this is not the only uh sentence so then we should backtrack uh by mean backtrack we need to dump this dock and we dump sandy uh set then we dump c80 so uh at for the previous solution our ending index is in t so now we can move it forward then we have c a t s that's a possible a word in the word dictionary so we append this ca ts in the maybe result string or something else and then we handle the rest just like the previous iteration so this is just a backtrack we add the new word to the string and we code this function we name it the dfs and then when we get a possible result we just remove that word and try every possibility uh just some um hands up first is a pro pruning what do i mean by some simple prune pruning that's if there is some character in s that it does not exist in word dictionary we know we cannot get a result so we just return an empty list so that's one thing we should check um yeah i think that's it okay let's write a code we need the result new array list okay then we check whether it exists in the word diction so we need a counter array we only have 26 because uh i think it says only lowercase so what we should do is iterate every word in word and iterate to every chart in word to char array then we let cow to see do not forget to minus a because this is just the offset ascii code i think it's 96 or something else so we get the offset so then we check every uh char us yeah char e uh s2 chart array then uh we check if cal to c minus a equal to zero then we don't find it so return result okay then now see that the given uh data type of what direction is list but we all know if we want to check whether a string exists in some connection what is a faster way that is use a hash set so we just call it a word set okay here we should initialize word set a new hash set we parse this word okay then we do the dfs and then we return result okay let's see what we should use in this uh dfs well first thing first we need this string and we also need the index and i think i said the we must maintain some result string uh we call it substring curve okay so what is the best case about ending in backtracking a problem we should think about it so the base case is if index in uh it's reached the end so we write the s equal to s length okay if indian equal to n then we add the current substring to result so curve two string right and then we return okay then we need to iterate the ending index i equal to index i less than an i plus oh we check if the word set cont oh sorry contents of this s substring or that will be index i plus 1 because never forget the ending index of the substring is exclusive so we should increase increment by one if it exists remember we need to backtrack so we must know the index current index uh we call it before adding we save the current length why because uh when we backtrack we should remove occur delete this substring so the beginning index is this before ending the ending index is that time length so we remove this basically we remove the substring from the curve okay uh here we also have two cases one is if it is the first uh first if we do the first uh word then we don't need to add the space otherwise we need to add a space so if it is equal to zero then we know curve should just append this substring okay we just append this substring if not we should occur append the space right space and the curve append the uh well okay uh then we do the dfs string index i plus one right do not mix up the index and i in the curve and we backtrack okay so that will be f index zero new string builder okay i think that's it okay thank you for watching see you next time
Word Break II
word-break-ii
Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in **any order**. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "catsanddog ", wordDict = \[ "cat ", "cats ", "and ", "sand ", "dog "\] **Output:** \[ "cats and dog ", "cat sand dog "\] **Example 2:** **Input:** s = "pineapplepenapple ", wordDict = \[ "apple ", "pen ", "applepen ", "pine ", "pineapple "\] **Output:** \[ "pine apple pen apple ", "pineapple pen apple ", "pine applepen apple "\] **Explanation:** Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** \[\] **Constraints:** * `1 <= s.length <= 20` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 10` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**. * Input is generated in a way that the length of the answer doesn't exceed 105.
null
Hash Table,String,Dynamic Programming,Backtracking,Trie,Memoization
Hard
139,472
215
Hello everyone welcome to my channel but this is going to be a very easy question, we will make it from multiple approaches, we are ok aa khet largest element in and hey ok main by Microsoft question is very simple, you are waiting for the number and one. The interior of the name has been given, you have to remove the khet largest helmet, okay then khet largest element in D, sorted note D, khet distinct element, okay, you will also understand the meaning of this, why is it saying note D's this here, they will also understand it okay. Can you solve it without sorting? Okay, I understand that given in the example, its largest element is five. If we take mother, I have sorted it. One, two, three, five, six, so this is the largest element. This is the second largest. It is five, right? If you had to find the second largest, then the answer is five, I am fine, so we will make it with multiple approaches. The first approach is the same as mentioned in the question, without which you have to do it. Without shorting, I will make one by sorting. After solving the bar, I will show you that there is no need to do anything in sorting, you simply sort it in descending order or in ascending order, I sort it in descending order but if we Indonesia is short in sorting then what will I do? I will sort it in descending order by applying a Comparator and applying a Greater Eight, then what will happen in the descending order, okay, I want the cake i.e. the second largest okay, I want the cake i.e. the second largest okay, I want the cake i.e. the second largest element, which means in which index it will be on the minus one authentic, okay so K - 1 means 1 K - 1 means 1 K - 1 means 1 What will happen, if it becomes one, then it will be zero index, first index, second third, fourth fifth, so my answer here will be five, so it was very simple, we have shorted it, what is compressed of sorting, what is unlocked n, okay, now look at the approach. Let's come to you, see what approach you have, we will do it only minimally, so let's see what was our example. We have given the value of 321 564. Okay, so see what I will do. Now see what is the size of the hit. One. Is it, how big is it? No, how is it not big? Now see, you came, you also added me, what happens in the hip, the one which is smallest is on the top, so you came on top, okay, now look at the size of the hip. What is two, which is fine, because we have to take out Kerala, so I will keep the size somewhere up to two, okay, now one is gone, okay, one is the smallest, so one will be on the top, so now look, what has become the size of the hip, it has become three, which is greater. Give 2. Okay, as soon as &gt; 2 happens greater. Give 2. Okay, as soon as &gt; 2 happens greater. Give 2. Okay, as soon as &gt; 2 happens &gt; K happens, what I will do is I will pop the &gt; K happens, what I will do is I will pop the &gt; K happens, what I will do is I will pop the smallest element which is on the top, meaning I will hit bread top, then the top one will be removed, then one is removed. Okay, great, back. What has happened, it has become two, okay, now look, it is five, but look, 5 science is a bigger element, so it will go down here, you here, then five will go down here, now look at the size of the hit, so what, now it has become two, which is greater, sorry. Greater Dane, so again we will pop it, okay, all the time I am maintaining the maximum hip size, okay, so I have sinned this too, now let's move ahead, six is ​​the big element, so six will be at the bottom is ​​the big element, so six will be at the bottom is ​​the big element, so six will be at the bottom because it If there is a hit in I, then three will go here, five will go here, six will go here, then look, its size will be three. That is K, so I have popped the top. Okay, now coming to four, so if you put four, then four is the smallest. So 4 will go above A. Okay and again if the size of hip is bigger than K then we will pop it again. So look at the size of HIT, I have kept it as maximum as K and all the smaller elements are coming. No, I deleted it above, I kept popping it as its size was getting bigger, so what about the child, what is after that, what happened because of that, the biggest elements which were made last, are the big elements or they have gone back. Okay, so remember, the largest element will be this, after that the second largest element will be this. If the key value was Tu, then the element which is at the top will be my answer because see what is the size of the priority, then the largest element will be at the bottom. Okay, so first this is the first greater element, this is my second &gt; So it is &gt; So it is &gt; So it is very simple isn't it will be bigger than the mini hip, it will be made simple, by coding both of them, you can easily submit it quickly, okay, we will come after that. It is okay on one approach three which is very important. There are many chances in the interview that in the interview you may be asked to follow. Look, till now I have not seen that this question has been asked in many dubs in the interview. But approach three which is I will tell you that it will help a lot, it is very important from the learning point of view and I think in today's time the level of interview has gone up a bit, so you should learn that thing too. Definitely, sometimes that question can be asked, okay? So let's go ahead, before taking it further, let's see the time complexity of this also, how much time complexity will there be in using it. Look, we are traveling all this time, neither is it, but whenever we travel, it is in the hip. We put it right and when we take the mother, we also pop it, which is an off key operation. People are of the maximum hip. The size of the hip is of the maximum. So the size of the hip is the maximum. What am I keeping? I am keeping it as if it is bigger than this. What happens is that if I pop it, how will the size of the hip never increase, then its time complexity is n * log of n, but its time complexity is n * log of n, but its time complexity is n * log of n, but in this year, if the value of the cake is equal to n, then what will happen of n * log of n, equal to n, then what will happen of n * log of n, equal to n, then what will happen of n * log of n, which is The time complexity of our sorting will almost be equal to that, okay then, is there any better approach to solve this and after that we will come to our approach three, okay for that which we also call quick select, okay now. Today we will learn what is quick select, its other name is where partition, we do the code of one or two approach but I have received many suggestions in which people have told me that the video becomes too long, so I What will I do, this is approach three, I will upload it on the next video and it will be done today itself. Do n't worry, it is okay, it will be in the next video and it will come today itself. Don't worry about it, now let's go and make the approach. Broach is coding it with you. Let's submit and complete it quickly, then a next video will come today itself, it will come soon, in this I will tell from approach three why I will take priority, either the men do the sorting first, neither do the sorting by the first nor do the sorting began Namas and Norms. Greater Eat Okay, what did we do, we sorted it in descending order and what will we do in simple return, the element with 1s will be the field largest etc., let's see by submitting the right. Dada, there etc., let's see by submitting the right. Dada, there etc., let's see by submitting the right. Dada, there was no need to tell anything, it is infact but style. I am late after submitting it, okay and after this we will make the approach using sorting from minihb, okay, now I have done it, okay, so after submitting, let's see the Puri pass which dates in these cases and don't worry, the next video will come soon in which Will tell you through approach three, okay using quick select, there is any doubt, combination tree, help you see, gas video, thank you.
Kth Largest Element in an Array
kth-largest-element-in-an-array
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element. You must solve it in `O(n)` time complexity. **Example 1:** **Input:** nums = \[3,2,1,5,6,4\], k = 2 **Output:** 5 **Example 2:** **Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4 **Output:** 4 **Constraints:** * `1 <= k <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
Medium
324,347,414,789,1014,2113,2204,2250
143
foreign hi this is Topher with the lonely Dash and today we're going over leap code number 143 reorder list which states you are given the head of a singly linked list the list can be represented as list 0 list 1 all the way through list of n reorder the list to be in the following form list zero list n list one list n minus one list two list n minus two you may not modify the values in the lists nodes only nodes themselves may be changed so what does all of this fancy stuff mean well it means that you're going to be given a linked list that looks like this so this list is one going to two going to three going to four going to five and it needs to end up as one five two four three so you can see that this fifth this last node was placed in between the first and second here it is here's the fifth this second to last node was placed kind of in between the second and the third okay so four was put into here five was put into here so we end up basically cutting in half our linked list reversing the second half and then zipping them together so it's a little bit difficult to explain but we're going to explain it in three parts the first part is that in order to solve this question we have to find the middle of our list so if this is our list one two three four five we know our middle is three okay then we're going to reverse the second half of the list so after we've found that this is three up here from here we're going to reverse the second half so 5 is going to replace where the 4 is and 4 is going to go where the 5 is and then we're going to combine these two lists at the every other node so if this 5 is the last then it's going to obviously go here this 4 is second last it's obviously going to go here and we end up with one five two four and three so it's a little bit difficult to explain but it's a conglomeration of a couple other lead codes we've done before but in essence just to kind of go over these three parts again we're going to find the middle of our linked list we're going to split it into two different linked lists one is the first half two is the second half we're going to reverse the order of the second half right and then we're going to zip them together so that they make a final list where every other node is the reverse of the second half and the normal order of the first half okay that sort of explains what we're gonna do let's work through this process and we're going to work through in parts so we're going to deal with part one find the middle of the list and split it into two lists okay now I've kind of worked it out where part one quote middle of the linked lists middle of the linked list is actually Elite code for which we have a video so if you haven't watched middle of the linked lists yet please watch it explains in a little bit more detail we're just gonna kind of glaze over what the first part of this question is which is using a fast and slow pointer so we'll have a slow pointer we'll have a fast pointer and we're going to have a head to pointer but we'll talk about that in a minute because we're going to use our fast and slow pointers to figure out the middle of our linked list our slow pointer moves one position at a time our fast pointer moves two positions at a time and this is going to happen over and over again until we find out that there is no next position for our fast pointers so if it reaches the end and there's no next position we stop and you'll notice that our slow pointer is sitting on this three which means this is now the middle of our linked list okay so part number one is finding the middle of the linked list we're going to use our fast and slow pointer moving one at a time for our slow pointer moving two at a time for our fast pointer and once we identified which node is our middle uh or middle position we are going to have to identify the next node and we're using that as our head too and why is that well because each one of these nodes is connected going One Direction and we know that we're going to have to split uh our linked list into two by making that connection disappear once that connection disappears we have to have a reference to the head of the second half of our linked list so we can basically reorder or I'm sorry I shouldn't say reorder to reverse this half of the linked list so all we're doing part one is finding the middle of our linked list by using our two pointer selection figuring out what our slow pointer is we're breaking the connection by having this uh node point off into a null Direction null and then we are identifying the second half of this linked list now after part one we found out our position we've split it into two linked lists the next step is to reverse the linked list that is the second half and you'll notice again a reverse linked list is in quotations that's because there is a lead code question called reverse linked list which we've already made a video for and it's going to help you understand the part two of this question so part one we have identified that 4 going to five is the second half of our linked list so we need to reverse it and then to do that we are going to have to create a dummy node right and we're going to put our previous pointer on our dummy node we're going to have to create a current pointer uh sorry previous pointers on our dummy node current pointer is on our first or head or in our case head 2 of the second half of the linked list and we're going to follow the rules over here until our current pointer kind of gets to the end now our rules these are just reassignments of variables that show um or basically show how we are going to reverse our pointers so our dummy node points to the head our head points in the next and so on and so forth so how are we going to do this well we're going to follow along and we're going to use our temporary variable here next to our current pointer so it doesn't matter how long our second half of the linked list is our temporary variable is going to hold the value next to our current pointer so current pointer.next meaning wherever current pointer.next meaning wherever current pointer.next meaning wherever it's pointing it needs to point at our previous pointer so we're going to get rid of this break we're reversing it and it has saying that our current pointer is going to point backwards to our previous pointer and our current pointer can't point in more than one direction so that also gets rid of this point right and then we're going to move our previous pointer to our current pointer position and I hope I can do that without having to no it's going to be hard for me to do so I'm going to have to sorry oh my goodness I'm going to delete these orange parts so I can move our previous pointer to our current position moves to where our temporary position is and our temporary position moves away I'm just going to add our re Point here because sometimes the Whiteboard doesn't like to do that so again previous pointer is then equal to our current pointer and our current pointer moves where our temporary pointer was and our temporary pointer is off into nothingness or to the next um next node right and then we do it again so we know that our current pointer.next is going to point to our pointer.next is going to point to our pointer.next is going to point to our previous pointer so CP gets reversed to previous pointer and then we have to move all of our items so previous pointer moves up current pointer moves and disappears in temporary pointer disappears and we're done and you'll notice if we follow along with all of these rules all of the pointers are pointing the opposite direction so we have essentially reversed the direction of this linked list and previous pointer is now the head of this linked list now eventually we're going to have to you know reassign the value previous pointer is not a great name for the head of a linked list I prefer head 2 because it has the word head in it so we might say to ourselves okay previous pointer now is head two so head to um is uh point or I'm sorry head two is now the link list five going to four going to nothing else and we'll say that our dummy node which is way off here has no value so it won't matter so part two um just to recap is an exact copy of reverse linked list which is already solved for us in a video you should go back and watch it and so you'll better understand the solution we just came up here and then we're moving on to part three and we're gonna scoop down here to part three and this is where it gets slightly more complicated for us so you can see up here this one two three is the original head of our linked list because our original head went one two three four five and then five and four with an extra D over here for our dummy node which was null and value so it's just removed from here is the second half of the linked list but reversed so we have two separate linked lists here okay so the head of this first linked list I'm just going to have H1 represent head one and V2 kind of represents variable or sorry V1 represents variable one and down here we're going to have H2 representing head two and a variable two representing variable two and you'll notice that the variables start with the heads at their respective positions so we're going to start H1 and V1 at the first node of the first half and same thing with H2 and V2 and over here you're going to see that we have specific steps that we're going to go through in order to zip them together because remember the outcome is supposed to be 1 going to five going to 2 going 4 going to 3 and that's the outcome we're really hoping for and the steps over here really show how we're going to get to that point we're combining these two linked lists so we're going to follow along with our steps so if H1 and V1 are starting on the at the first node of our first linked list we're going to say we're going to move our H1 forward our head forward so eight head one is going to move forward to the next position so now head 1 is on our second position and variable one is on our first position and we're going to say that the variable one dot next needs to point toward the head of the second linked list of H2 so I should make this a little bit more clear right now all of the linked lists are pointing in this direction and we're going to be editing where they're pointing so we're going to come back v1.next v1.next v1.next is equal to H2 which means V1 which sits here on the one is pointing to 5 which is where H2 currently sits so we've gotten rid of this pointer here okay and then v2.next is equal to H1 so okay and then v2.next is equal to H1 so okay and then v2.next is equal to H1 so V2 is sitting here at the five we're going to point it where H1 is currently sitting all right so far so good now V1 is equal to H1 which means we're just moving our V1 over to the position where H1 is and V2 is equal to H2 which is already sitting there which confuses me because I feel like I'm missing something here let me make sure I've got this all right should we have moved our H2 forward yes we should probably have moved our H2 forward somewhere in here so let's make sure we've got that in there as well at any rate we are moving V2 equals H1 great we're going to move our position here H2 equals H2 dot next okay let me make sure this works so we're moving H1 first great then we're moving V2 down to here to H2 then V2 is going to point at H1 we're moving H2 there we are okay yeah sorry I had to add an extra step in there I must have left it out sorry everybody it is important to make sure that is there so then we're moving everybody forward our V1 equals H1 and V2 equals head two okay I'm saying H1 and H2 instead of head one eight and head two I hope that's okay at any rate when V2 dot next points to H1 we're going to break this here right but we still need to have this reference was what I was talking about so it needed to be kind of before we pointed V2 to H1 so V2 pointing the H1 we're going to make sure there we go now I've figured out sorry everybody sometimes you do leave things out so for our sake we're going to continue through this motion here so when V1 moves to H1 V2 moves to H2 we're all in the same position and we start over again so H1 is going to move to H1 dot next so it's moving on to the next position v1.next equals H2 so we're going to be v1.next equals H2 so we're going to be v1.next equals H2 so we're going to be pointing it down to the 4 which means we have broken this value again this H1 was moved first so we could hold that value now H2 equals H2 dot next now in our case that doesn't really exist so it floats off into Oblivion and V2 is still kind of stuck there but v2.next is equal kind of stuck there but v2.next is equal kind of stuck there but v2.next is equal to H1 which means we are pointing it upward and then V1 matches H1 V2 matches H2 and we're done and you can see how this kind of connects all together now I feel like because I left out that one section we should probably do it again just so that there's some clarification on how this works there's nothing wrong with doing that so V1 and H1 and V2 and H2 again start at the beginning of each one of their respective linked lists we're going to start at the beginning H1 equals h1.x removing H1 forward a equals h1.x removing H1 forward a equals h1.x removing H1 forward a position v1.next is equal to H2 stuck here on v1.next is equal to H2 stuck here on v1.next is equal to H2 stuck here on this five so it's going to be pointing this direction awesome once that's done H2 is equal to h2.next which means 5 is H2 is equal to h2.next which means 5 is H2 is equal to h2.next which means 5 is already pointing to 4 we're moving it forward right because we already know 5 is currently pointing at 4 2 is pointing at 3 1 was pointing at two but when we moved it was broken apart because it's now pointing at five so once H2 is moved then V2 dot next is equal to H1 which means V2 going up to H1 and that breaks this here all right then V1 is then put into the position where H1 was awesome V2 is put in the position where H2 was and we start over again so H1 moves forward H1 equals H1 dot next v1.next is equal to H2 so that of course v1.next is equal to H2 so that of course v1.next is equal to H2 so that of course H2 is down here we point this direction and we're good uh V2 dot next equals H1 V2 H1 points that direction and so on and so forth and you can see that then goes from one to five to two to four to three and as long as we follow all of these steps here on the right we are going to be just fine in zipping them back together so we're going to move forward from here we're going to take a look at our constraints and see if there's any edge cases okay so our constraints basically say that there's going to be a number of nodes in the range of one to five times ten to the fourth so there are going to be a bunch of nodes at least one node and the value of the nodes is going to be anywhere between 1 and inclusive one and a thousand now there's a whole bunch of possible edge cases here because we split it into three separate ideas right so the first part is middle of the linked list finding the middle of this linked list there's not too many edge cases but if you go back again and watch middle of the linked list video we'll talk about whatever edge cases there might be in reference to the first part of this question similarly when we go to the second part of the question we're reversing the second half reverse linked list our video on that we'll talk about any edge cases that may exist but most of them are taken care of when we add this dummy node because when we're dealing with linked lists always use a dummy node it helps with edge cases but finally when we get into zipping It Together part three this is the only part of the question that's kind of new um there's not really any issues with our constraints so as far as I'm concerned for the purposes of this video there's nothing to concern ourselves with as long as we've covered the other two videos prior okay so let's go forward we'll talk about some pseudo code and then we'll get coding okay so for our pseudo code we're just going to write in the C plus version of the leak code website and we're going to split it into parts right because we talked about the parts so part one is finding the middle of our linked list okay so the first thing we're gonna have to do and I should preface this by saying this is literally word for word the pseudo code we used in our other videos whether it would be middle of the linked list or reverse the linked list we're just gonna do it word for word so at least starting off at part one this is middle of the linked list we need to initialize uh we need to initialize a fast and slow pointer starting at the head of the linked list right and then we're going to figure out a while loop so while the fast pointer exists and while the node after the fast pointer exists what are we doing well we need to move the slow pointer slow I got to spell slow right pointer one position forward and then we also need to move the fast pointer one position forward uh sorry and when I say that the fast pointer moves two positions forward okay and that's basically all we need there so the loop then breaks and the middle of the linked list will be the slow pointer position okay and then everything basically after that needs to be reversed so what are we going to do now that was where we stopped on our middle of the linked list but essentially we need to sign a variable to hold the head value of the list after the slow pointer so that'll be slow dot next will equal head two that's what we were talking about when we were understanding this question so break the link by assigning signing the next value after the slow pointer To None or null right so slow will then point to nothing and the null the node after that would be the head 2 of the next linked list and that's the end of part one pretty simple part two is slightly different let's reverse the linked list right and when we do that we need to do a couple of other things the first thing we need to do is create a variable that represents the previous pointer and give it a null value right we don't really have a previous pointer and I'm going to spell this right pointer at right now because that was what slow pointer was so we may have to create our own dummy node in this case um so keep that in mind right dummy node question mark however we're going to have to do that's the previous pointer so um create a dummy node for this value all right that makes sense then we need to create a variable that represents the current pointer and that current pointer is really the head two right so assign it the head 2 value that's what we were talking about earlier so we've created our new dummy node and we've added our previous pointer to it and we've created a variable that represents the current pointer and we are assigning It To The Head 2 value so if we wanted to go back just to kind of recap a little bit we've done the part one we've created our linked list we found our slow pointer we've assigned head 2 to the head of the next value and we've moved on to our reverse linked list where we've created our dummy node and we put our previous pointer on it and our current pointer on the first node so that we can start the reversing process okay now what do we need to do after that um well for part two we need to create a while loop that will iterate through the entire linked list okay so it's going to go through the whole linked list or at least the second half which is it's only last by now so every iteration will be assigned a temporary variable to hold the node next to the current pointer right because we've already created our current pointer it's somewhere up there then what are we going to do well then we will make the node next to the current pointer the well become the previous pointer right because we're trying to reverse the direction then the previous pointer I'm just going to use PP will be assigned the value of the current pointer because we have to move it forward and then the current pointer will grab onto the value of the temporary variable v-a-r-i-a-b-l-e and that is the totality v-a-r-i-a-b-l-e and that is the totality v-a-r-i-a-b-l-e and that is the totality of that Loop just slowly reversing um reversing the way the nodes are pointing at one another and so when this Loop is complete all the way or once this Loop is complete the previous pointer will be the head of the new linked list right and so that's something to keep in mind when we finally get to the end we may have to reassign I don't like you could just go through saying previous pointer but I would reassign the value previous pointer to a head value just for my own sake and so let's kind of do that for clarity because we're on to part three and what happens there well I'm just going to call it a sign variables for clarity and this is just going to be a section for me so we're going to say there's going to be head one right and variable one and that's head one and V H1 and V1 what we were talking about in our understanding the questions those should be at the head and that's the head of the very first linked list so head of first linked list awesome and then we're going to have head two and variable 2 or H2 and V2 and that should be at previous pointer right because previous pointer was the head after it was reversed of the second half of the linked list so hopefully that makes sense and that's what we're doing when I or what I'm doing when I'm saying I'm assigning variables for clarity I like to have variables that make sense okay so now we know that we have a V1 and an H1 as part of the first half of the linked list and we have an H2 and a V2 at the beginning of the second half that is reversed of the linked list now we are going to use a while loop to kind of zip them together right so while there is a value for head two all right because head two no matter what is going to be equal to the length of head 1 or even one longer than that so as long as it exists right so while there's a value sitting in H2 or head two we need to exchange let me see if I can pointers to meld or zip I'll do or zip because I think I like Zip better zip the lists together and essentially we're going to do exactly word for word what we did before we're going to move the head one uh value to the next node leaving I guess V1 behind right because we're going to keep moving that the head value forward then we're going to point our V1 to the head to or to head to then we're going to move the head 2 to the next node leaving V2 or variable 2 behind and then we're going to point V2 to the Head uh or to head 1. then move V1 to head 1 position and move V2 to head to position and these are the Motions that we went through that I may have kind of confused a lot of people with when we got down here to part three all of this which was slowly swapping positions for these um these variables having V1 and H1 and H2 and V2 kind of in the same positions but it's just so that we understand how we're moving it H1 moves to h1.next so we're moving it H1 moves to h1.next so we're moving it H1 moves to h1.next so it moves there so when this is broken so we can point this direction here then we move H2 so V2 stays here so we can point this direction here and then everybody moves together and then each one kind of moves again and we start the pointing process over and we're done so that's the very last step that we're just writing out here in our pseudo code and then finally do we need to return anything I'll be honest I don't actually remember but we're just going to say probably so when this last Loop completes uh all nodes have being rearranged oh you know what I'm after thinking about the question I don't think we have to return anything so no need to return anything um we modified it in place and we're done so by splitting this question into three separate parts part one which we already learned from middle of the linked list part two from reverse linked list and part three which is the only part that's kind of new and requires the knowledge of how to zip together these linked lists we can solve this question so we're going to take all of this pseudo code we're going to copy and paste it and we're going to figure out how to write the code and get a perfect answer so let's do it let's get coding here we are in the JavaScript work area of the leap code website and I'm just going to copy and paste our pseudocode in there we are so we're starting with part one here and you know we're going to maybe label these so part one what are we doing well the first thing we need to do is initialize our fast and slow pointers and again we've already covered this in Prior videos so I'm not going to take a lot of time so we're going to let slow equal head and we're going to let fast equal head both the slow and fast pointers are starting at the head and we're going to say that while fast is not null and fast dot next so the node next to fast is also not null what are we doing well we're moving our slow pointer forward one position and we are moving our fast pointer forward uh two positions so dot next all right so that's our while loop we've initialized them we moved our while loop and the loop breaks and the middle of the linked list will be the slow pointer position everything after this will need to be reversed so this is how we find uh the middle of the linked list now we need to assign a variable to hold the head value of the linked list after the slope pointer so what are we doing for that well let's just let's see here we're going to call it head two is going to equal slow dot next okay and we're also going and I'm just maybe kind of catch up this way here we need to break the link by assigning the next value after the slow pointer to null or none so we found the middle is where the slow pointer is we're saying the head 2 is the point uh the node after our slow pointer and that slow dot next should Point into Oblivion which is null so that we've broken apart the linked list into two linked lists one with a head of head which is provided and the other one with head two okay so that's all of part one and again part one is from all of the information previous of our video middle of the linked lists check it out okay so part two and let's see here do your part two we're basically going to be taking the second half of that linked list which the head is now head to and we will be reversing it so we need to create a variable that represents a previous pointer and it's on a null node and a variable that will represent a current pointer and starting on the head 2 value so uh we're going to say let previous pointer equal uh null because it doesn't need a value and that's one pointer and we're going to let current pointer start at head 2 because that is the head of our second linked list and it's time to reverse them again if you need some refresher on how this works please look up reverse link list we're just running through it pretty quickly so we're going to have to create a while loop that will iterate through the entire linked list every iteration will be assigned a temporary variable to hold the node next to the current pointer then we will make the node next to the current pointer become the previous pointer and so on and so forth so while the current pointer is not null right so as long as there's something to swap what are we doing well we're going to get a temporary variable to hold the value that is next to the current pointer so current pointer.next pointer so current pointer.next pointer so current pointer.next right and then we're going to have that current pointer Point backwards so it then it's going to point backwards to the previous pointer and that's what's actually doing the reversal and then our previous pointer is going to move forward to the current pointer position and then our current pointer is going to move forward to the temporary variable position so this is what's actually going to be reversing the entire second half of our linked list that we were talking about so that's almost all of part two again check out our previous videos about that so when this Loop is complete the previous pointer is going to be the head of the new linked list because it's completely reversed so don't forget that's going to be important when we move on to part three here we are part three because I like to reassign variables so they make more sense to me so assigning a variable for clarity so we're going to need to zip together the two link lists so the first half of the linked list is in correct order the second half of the linked list is in reverse order but let's just make sure we have all of our stuff together okay so we're going to have something called V1 and that's going to start variable one it's going to start at head right and we're going to say that there's also going to be a head one and that's also going to be at the head so these are representatives of the first node of the first half of our linked list which is the one that is in current the correct order we're going to also going to have variable two which is going to start at previous pointer which is the head of our second linked list that is now reversed and just for argument's sake we're going to reassign the value of head 2 to a previous pointer okay and this is what we're getting into when we're starting here um so let me just kind of reset it so we've got V1 is sitting at the head of our first linked list along with H1 representing the head of our first linked list and V2 and H2 are sitting at the head of our second linked list which is reversed and we're going to go through these steps where H1 moves forward V1 is then pointed at ah2 works for me H2 moves forward where V2 points at ah1 and then V1 comes here V2 comes here and we start the process over again where H1 moves over and V1 points at H2 and then H2 moves over and V2 points itself at H1 and continues okay so that is where we are in our writing and here is the while loop that will help us so we've completed the new assignments of our pointers and now we're going to have our while loop so while there is a value at head two so while head 2 does not equal no because there will always be a position in head two and the way we're writing it uh head two is always going to be equal to or greater than of course sorry the length of the second half is always going to be equal to or greater than the length of the first half so this will work out just fine what do we need to do well we're moving head one to the next node so head one is going to equal head one dot next awesome that leaves V1 behind so variable one however is going to point toward whatever head 2 is and then we're moving head two forward so head two is going to equal head two dot next and we're going to do the same thing with V2 dot next so V2 is going to point toward whatever is at head one okay and then we just start over again by making sure that V1 joins wherever head 1 is and V2 joins wherever head two is and we are done with the coding for zipping together our two linked lists all we have then when this last Loop completes all nodes have been rearranged there's no need to return anything because we modified everything in place so we can just get rid of all of that text so again we've split it apart into three sections the first section is finding the middle of the linked list once we've done that we split it into two separate linked lists we have used part two to reverse the second half or the second linked list and when that was done we zipped them together the first linked list and the second linked list so that we have one linked list which has been zipped so I'm going to hit run and hopefully I didn't make any spelling mistakes or any punctuation mistakes we're good I hit submit and see how we did against all of the test cases and of course uh well it's not the worst I always try to hit it twice we'll hit submit again and uh and oh gosh it seems to be get worse every time I click it but we're looking at a fairly fast way of solving this using JavaScript there we go so 86 uh 28 but we've taken what we've previously learned from middle of the linked list and reverse linked list stuck them together and it's a great way of solving reorder list using JavaScript foreign
Reorder List
reorder-list
You are given the head of a singly linked-list. The list can be represented as: L0 -> L1 -> ... -> Ln - 1 -> Ln _Reorder the list to be on the following form:_ L0 -> Ln -> L1 -> Ln - 1 -> L2 -> Ln - 2 -> ... You may not modify the values in the list's nodes. Only nodes themselves may be changed. **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[1,4,2,3\] **Example 2:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,5,2,4,3\] **Constraints:** * The number of nodes in the list is in the range `[1, 5 * 104]`. * `1 <= Node.val <= 1000`
null
Linked List,Two Pointers,Stack,Recursion
Medium
2216
470
Hello, let's start because this is very interesting, and I think even if you are a non-rotating hormone, even if you are a non-rotating hormone, even if you are a non-rotating hormone, you have to take time, that is, very cute chords in English, it is nominal in mathematics, so this question is increment sentence function. Using r and function, the question was raised, friend, we have the function surprised seventh, what does it do to generate a random number? We have to write one and a half inches in the middle of 127, so my friend there is a function named seven, what will this function do? What will this random number do by giving the criminal number? Where are the numbers, from one till evening, I have a Friday number function, the numbers till 11110 were generated by random number generator. Now friend, what is the problem in a small question, is it okay? If you want, then it is in 951 AD. Intact to 170, send an add in the same on 21st of the number and if you have the intention then he will also give you the number 110, but if there is a problem with all the numbers then who should it be, okay friend, I would like you to give me a solution by crossing the video. Think about it and I mean this showroom is a bad mission then you can definitely sleep ok and maybe you like the thought that we are fine, if you talk about solution then friend, the worst solution is the one which is filled in my mind. Friend, rank 7th twice, call this remedy twice and multiply it, okay friend, call seven twice, close Amlido, friends, now call us twice, will you like the square meter, both the creams are 72727, the screen is 127, other people also have debts. If I fly both of them on 127, then which possible number will they give? Will they give 12420 or not? Now what can we do in this, that we have set all the TVS people, that is, 127 came from the first one and 127 came from the second one. Divided that number into seven. Do it has become 12429, now let's do it in this or 120 I am thinking of myself, I am proposing Solan, now we will reject the Clear Forty Plus people, now when we will make the number for the positive press people, from where will we keep getting 120, what will they do? We will take a tension reminder, after the tension meter comes, from where to where will we give it, till that day we will give it, then we will take bread, which is the number, we will add it on WhatsApp, we will add it, could it have been this portion, what did I say, I said twice, Rank One Pension Got excited, called him 127, both will be given, ok, mixed both and gave 127, that is the possible number cream we have, in this we have rejected the part plus ones, now the number will be called, it came pure till 1-2-14, took its tense reminder. came pure till 1-2-14, took its tense reminder. came pure till 1-2-14, took its tense reminder. And after taking the tension, I will take the tension back, he will give 20, he will add one to it, then he will give inches in the middle of the bus stand and I will return this, then Vinod, the first question in your mind is, am I in the office, am I going down from some number? If I do, then I say that when you fly both the numbers then it is once upon which is good between us, yes, if it has the property of getting all the numbers, Prince, if we increase 12429 by getting all the numbers, if it is so. That there is any chance of getting all the numbers. If you see both then the chances of getting part plus are 90. Okay, believe me, for the first time, both of them have set me up and if I can travel, then I can do it. Well, for the first time, Bloody Mary Celeste. Do it spoil the number 99 or 2000 can do in 12 if play again by like this then the number which I have pinpoint taken the decision is two for the first time brother one but 9920198008 third time in that 30 on cent a which come There is no chance, meaning score, changing every number is not a problem, if you can quickly then it was better to like the channel one to 9 4, in the year 2002, there was a little problem like ticket problem, I have written that on the board but boiling liquid time. There is no problem in such a situation, if we can see mental, different teams of India, different projects, see how Chinese sub numbers, what should I say, I will update and write sub criminal here, remittance divides, momentum, what do you say? We kept the line there so that when decisions were mentioned, I cut them off, rest of them I have put a reminder along with the tank, so how many times is Raghuvansh coming, so when the product is made, there will be a reminder that the product is made here, I can see this one. Is there a forest somewhere else and remove the post? Apart from this, I have not found Bandh Bhaiya anywhere, so I can see that the song is being made in three such cases, three are in such cases, if the Judgment Bhavan is being made more interested, then in how many cases is it being made? Reminder Two, I am looking tied, Hey minute, it is looking good here, okay, now two-three times that good here, okay, now two-three times that good here, okay, now two-three times that here, four times here, five times, I write yours that here six times how to remember two, I can see that being made. It is 6 times, it means that it is wise, very wise, they will talk that one will be generated more often or if you do infection, we will do everything, then the number of forest that will be generated will also be allocated in case of this increase. If you like it then definitely like it, I got a reminder 9234 11 2012 I would like that you are there when we do plus one, meaning I say it again that if I say that we have maintained the brand only mental harassment will not come in 20 hours to make us. In the end, if we do 118, then how many times has one reminder come, it has come thrice, it means that it will be made two to two, it will be made advocate and these are for going, it will be made two-three times, I am going, it will be made two-three times, I am going, it will be made two-three times, I am talking about property and these were the same time 30 which is By combining this with you, it will become 210, but actually it will become 6 which is wrong because we have cut it and then we need a distributor, so what an illiterate distribution this is, so I say for the sake of purity, as if we cannot use it by adding this product. The vegetables Kunwar comes to mind again but I say hurt, what did I say, we have formed a line, friend, we will call random seven twice, both will come 72727, we will mix them and take 128, the range is that the one with part plus will make it great, 120 numbers are left. I will take the tenth reminder, after taking the tension, I will give you the responsibility when I will become plus, what should I say now friend, now let's discuss two things in this, what can we do, we can delete the number and tubeless people can click because fifty plus number. The chances of him happening are very less and the chances of him happening are very less. Even if he comes to fifty plus numbers then the problem with lipstick is also very less but we will think again after deleting the number. If it comes this time too then there will be 99 more forces on Ruby, then cr is there, if you will join the number again on the contract then it will be one in one click on the button, hair tips are increasing and decreasing, is it including sleep percentage? Our number of Haryana has increased from 14 to me for the first time whether the note length of the charges is not done for the second time whether 98100 Verilog Arrow Command gift again play it a little again friend do intermediate again this time Yogeshwar's chances That is, we report it increased to 999 9999, relax, then after three or four times the object will never come to your verification tab. Okay, second thing, what did we say that we had decided that the airplane was running well but there was a problem. But what do we have to do, brother? What have we seen? Are n't all the reminders coming at the same time? The one who is there is coming in his turn. In the same time two reminders are coming in six turns. Have you seen that there is one element? The one that was being made from this Vansh was being made from 21, okay it was tied with a ribbon, brother, what is happening, that is your house, you are drowning in darkness filled with 63, this is a reminder, that is your 652, so we did not take this plan from the number. Will be able to work but will have to be changed, I am fine, my airplane which I have set, I will use it as my own, then the new platform is like this, we said what we do, we have to do Hindu random numbers, we will use only number 2, enter this channel again. Subscribe I take the second number first, second in this manner, I asked for one to three, then if in the first and second, I am asking for the first, second and third number, in the first and second also, in this manner, why are we zero in the subject? I will not think about it is not a big thing, it is a big thing to be ashamed, so what did I think, friend, this is my grace, it means that apart from me, all these numbers are coming equal, it is a good plan, we will explain, the forty plus people will get it, I am fine brother. We will not take the Forty Plus people and they are not even doing the work for the Defense people. Let us assume from the beginning that we will not give account to the Forty Plus people. Okay, as per your wish, Planets, there is no problem, what are you doing now how to delete this number. So I say that friend, the first random number that comes is the first one, but from that we decide from where we should start the work and update the second system. For example, if I am 30, if the first number comes three, then the account Where should I start? Should I start with cotton? Na, if I am satisfied with the first number, generate two random numbers. Na, I am generating two random numbers. One more is generating, far from the night shelter and call Ranger Bowl. A gya. If he comes even once, then he has to attend this dual meeting, so you can see that when he comes completely, when I get a call on the first random number, then my cutting is 92125, so the cutting is from half an hour. Found the pattern, I need to increase the liter, so basically what I said is that the first remedy which will come, subtract one from it and make it ₹ 70, then first take the random number it ₹ 70, then first take the random number it ₹ 70, then first take the random number four, then now my counting assistant will be and - 132. 06 came 20100 comments be and - 132. 06 came 20100 comments be and - 132. 06 came 20100 comments on the second one who will take this much of yours - medical on the second one who will take this much of yours - medical on the second one who will take this much of yours - medical but now how by secret came to you five of fish 561 I have page number five second number is 6 so first point you first what did I know how to do counting assistant I figure out that I will get less of it from home consumption, then I give 7286 corn flour points, how much will it be, I get 55325 monthly, I get 5 monthly, I am getting extra cute, what is the rendering, take Jai Hind Pandit I am getting 13238 1431 whether I have to complete it, I was thinking that I will not face any problem in this situation, then I was very surprised at the work, so that if you warm up the number, then I choose the number, late for my Kill friend number four, kill 7 blenders, kill fishes, so how will I do it, I was worried, I will give the number from the first number, so he - 1313 give the number from the first number, so he - 1313 give the number from the first number, so he - 1313 and add one by one to the second number - 600 E will be - 600 E will be - 600 E will be ready to call, school is early They can delete it, loot your eyes, take away the Chief Justice, go, it will not make any difference, so do I accept an inter result, I accept the inter result equal to 241, it just did not work, to make a mistake for the first time, the results were wild, created by Hussain. Equal to Fati means I go and TV results are not there, I will tell you that the results are 272 A friend of 7 A minus one plus A friend of 7 that I have two, so what have I done, we will see it as soon as possible, okay all this. I will tell you why torn or grade film party tour is not done here and what will I return here only chart A percentage stand person is plus one then you have to see the truth tell me what did I do Why what was the talk that the one who stays first Murga, what did you see, I have to transfer the account, so we have used it, if the first number comes five, then it tells me that you have been injured by r5 -1.2 tells me that you have been injured by r5 -1.2 tells me that you have been injured by r5 -1.2 and one of the second numbers is completely medical so that I can do current column calibration, in this way I get 2010 numbers, everyone's problem is fine, now see this is just a reminder, Kayan Judgment Alka Yagnik, on dividing tense, two will come from the other center, it will come for free and only another 500, 600, 800 will come. Till 9, when we use the number, set it to number nine, make it 10:30 white, either the rate from which the number 10:30 white, either the rate from which the number 10:30 white, either the rate from which the number generates the reminder, that from zero to the right leg network, then back to time, the reminder will become the hero and will become the 11th, 12321 will go to the settings. It will become water for and ₹ 90 will also become a serpent, is and ₹ 90 will also become a serpent, is and ₹ 90 will also become a serpent, is n't it? A reminder from 80 to 9, from where till Bandeya, it is fine, from tan to 9, made of cement, again became a blasphemer, and from then onwards till old age. If you get one till you take 3915 rupees from your husband or whatever it is, it will be given to you once. Sir, my video will become 720, it will become 1000, the interview in 2012 will become 3720, it is not four numbers, neither will 0700 become 0, nor will it. Selects only mental hero, 1000 is made of 28.80, 3701 is made, if the party will have 1000 is made of 28.80, 3701 is made, if the party will have 1000 is made of 28.80, 3701 is made, if the party will have five members from Milunga, then the judgment will be followed. Okay, how many people are making one, so one is making one, second is making level, third is making 21st, 1264 are making. Everything else is Vansh but this is a number, isn't it, he is becoming a receiver, there should be four 120 thoughts, only then will all the numbers become records, only then, how many times will zero be made or not, so to do this, you are not playing an important role, I am It's just a simple Jhala, I accept it, I immediately kill it and see if there is a mark on it so that I can see it and the carrier will put it only in three submit cases, in the submit market it is said that it is left, is anyone logged out yet? A very good question, Thursday, all this. How to decide the mission etc. whatever is required otherwise it may be the previous one you will make the random Kohli and madam call back person longer cutting babes set number on the accused and video and so I repeat that we have decided by clicking subscribe or not subscribe If we make choli, we will do every position in the same way, don't smoke like this, we will smoke Salman, we will give money, look at the numbers from zero to quoted, we have found a way, brother, if you wake up during this, then what comment will be necessary in it? No and all this problem of numbers is fine, this time it is the same, we have given brigade to the party, why in the year that we will keep them to the post and party, then only one change has been generated and we have as many as 101 but the same number of ministers, this is what I did. I whitened the potency from zero to 1000, it started getting stronger and all the winters started turning off in equal numbers as if what did I do, don't take tension now, I made you a cutlet, reminded you to make Suman Tech, this raised the question, one cup interesting success meaning. The thing that should have been tried with non-rotating hormones is that tried with non-rotating hormones is that tried with non-rotating hormones is that you guys are challenging the list and that means take advantage of this thing, it is for you, thank you.
Implement Rand10() Using Rand7()
implement-rand10-using-rand7
Given the **API** `rand7()` that generates a uniform random integer in the range `[1, 7]`, write a function `rand10()` that generates a uniform random integer in the range `[1, 10]`. You can only call the API `rand7()`, and you shouldn't call any other API. Please **do not** use a language's built-in random API. Each test case will have one **internal** argument `n`, the number of times that your implemented function `rand10()` will be called while testing. Note that this is **not an argument** passed to `rand10()`. **Example 1:** **Input:** n = 1 **Output:** \[2\] **Example 2:** **Input:** n = 2 **Output:** \[2,8\] **Example 3:** **Input:** n = 3 **Output:** \[3,8,10\] **Constraints:** * `1 <= n <= 105` **Follow up:** * What is the [expected value](https://en.wikipedia.org/wiki/Expected_value) for the number of calls to `rand7()` function? * Could you minimize the number of calls to `rand7()`?
null
null
Medium
null
1,584
hey what is up guys we're back with another decode video today we're going to be doing 1584 minimum cost connect all points so you're given an array points representing an integer coordinates of some points on a 2d plane reports i is equal to xy okay so just an array of points the cost of connecting two points is the manhattan distance between them basically the difference between the x values and the y values where about the next absolute value okay to turn the minimum cost to make all points connected all points are connected if there is exactly one simple path between any two points this video is going to be really short uh some of you guys are probably going to hate me for it because i'm not exactly going to provide the code solution and the reason is i'll explain in one second so we have the example and you see we have this list of points and we want to find um a we want to find the minimum cost it takes to have all these points connected and basically it's really simple if you know two certain concepts and that uh if you know one concept and two solutions for that concept i guess which is um the idea of a minimum hispanic tree and what a minimum expanding tree is and then the two solutions to that is either the prim's algorithm or cross calls algorithm that will help find the minimum spanning trees what's expenditure is basically uh under a connected uh non-cyclic uh under a connected uh non-cyclic uh under a connected uh non-cyclic graph where only points basically all the points in the graph are connected to each other and there's no cycles and the minimum spanning tree is basically one once one such spanning tree where um all the points are connected and the in the cost of all the edges of summing up all the edges is at a minimum and that's basically what this problem is you're trying to find the minimum cost that where all the points are connected and so if you know what a minimum spanning tree is or quest calls or premiums algorithm is all are all about then you'll get the answer just like that so what i'll do instead for this video is um i'll just link you guys a bunch of videos if you don't know what those are to just explain them because i don't want to waste my time or make useless new information that is already out there so here are some good resources um the first thing i recommend is watching um well the first thing is probably watching crimson chris paul's algorithm reading method by abdulbari makes a lot of good videos especially on graphs and algorithms or if you kind of know them about them already you just need a refresher you can watch these two really short videos questions algorithm two minutes and uh prim's algorithm in two minutes and then also the william uh set uh also has some great videos i love watching his graph theory playlist i went through a lot of those videos and a bunch of his other videos as well he has some good videos in the union find as well so i highly recommend those if you don't know what you need to find is all about um he has one a video on prince planning tree where he goes over the park p the priority q method of doing a prince and there's also one on cross carl's algorithm where it involves union fine so that's that um so here so prims and chris calls by michael symbol prime microscope abdulbar is good too and crimson will chris call by william and also geek for geeks also has two good videos where they walk through the code for doing something like this so i just recommend just watching that i don't want to redo that because it's already there also the discussion explains that as well so that's that um just check out all these videos um you'll get the answer right away uh they're really good um there's no point in me explaining it again one thing to keep in mind is um this where for prim's algorithm for sparse graphs there's two ways to do the probes algorithm one is the using the matrix way which i think um if i remember correctly lobari explains that way and then there's a lazy way to do it which is using the pq which is uh william fassett's way so for sparse for us the pq is faster and for dance graphs the naive implications faster because e is going to be equal to n squared if the graph is very dense and you'll understand how that works if you just understand the problems of prim's algorithm and chris calls that's basically the video for today not for today for this problem number 15 84 i've been called to connect all points i mean once you look through the videos and just looking at some of the discussions the answer will come just like that so i hope you guys liked enjoyed subscribe comment and let me know if a dislike if you actually wanted to see the solution sorry i mean i'm really a big proponent of making new videos not videos that are already there and just better content right not content that's already there just recreating i don't want to use someone else's content and not give them credit and just it's already there i'm just here to facilitate that information
Min Cost to Connect All Points
average-salary-excluding-the-minimum-and-maximum-salary
You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`. The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`. Return _the minimum cost to make all points connected._ All points are connected if there is **exactly one** simple path between any two points. **Example 1:** **Input:** points = \[\[0,0\],\[2,2\],\[3,10\],\[5,2\],\[7,0\]\] **Output:** 20 **Explanation:** We can connect the points as shown above to get the minimum cost of 20. Notice that there is a unique path between every pair of points. **Example 2:** **Input:** points = \[\[3,12\],\[-2,5\],\[-4,1\]\] **Output:** 18 **Constraints:** * `1 <= points.length <= 1000` * `-106 <= xi, yi <= 106` * All pairs `(xi, yi)` are distinct.
Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2.
Array,Sorting
Easy
null
532
hey everybody this is larry this is day three of the leeco daily challenge for october uh hit the like button to subscribe and join me on discord let me know what you think about today's farm and today's forum is k diff paris in and away so i'm solving this live let me know if it goes wrong or whatever uh let me know how you solve this uh okay so given an array of integers norms and k return the number of unique k's and nums okay so basically uh okay just so as i is now you go to j what is a is okay so that's a pair but they don't tell you what a unique pair is because unique pair could mean just unique index or something like that i don't know but uh one and three okay one and one oh that's weird uh three i guess that is okay uh okay so i think the technique that i'm thinking of is um similar to prefix some dynamic programming uh or something like that but it's just a lookup table right uh basically for example for three you may look for 1 and 5 for k02 and then you just kind of keep on looking backwards so the tricky thing about that is that you have to keep track of uh you have to keep talking about uniqueness right and there are a couple of ways to uh dedupe uh the way that i'm thinking of right now i was just thinking of is just keep track of the larger number and i think if you do that then you should be okay uh space complexity may be a little bit iffy it adds another linear uh thing but it should be the same either way right because it's gonna be linear if you use the hash table um and i think you could also do it another way where you sort and then do a two pointers algorithm uh that's n log n but with what all one space so you could choose either of those two things to do um and i'm gonna do it the lookup table way with the old and the linear time linear space way uh if you have time do practice there's n log n uh constants base one because i think that comes up in other problems or maybe even in this form if the uh the list is sorted or something like that but uh but yeah that's what i'm going to do basically for so basically i have um i'll have two sets one is a set of numbers that we've seen and then you uh higher unique pair higher number or something like that set um and we'll go over with those two things in scene it's just basically the set that i will use to represent in all the numbers that i've seen from the left of a given index and then higher unique number is just the number we're going to return um that are going to be uh that would give us the answer uh and it's just basically there to help us detube so let's get started on that so let's for number in nums okay so if uh so okay so current let's you know bring down the current numbers oh i guess numbers already current number oops so if uh i think i'm so what i'm struggling a little bit i'm just thinking through uh is either i need num minus k or k minus num um i think in this case we want either or both because going looking back you could go the other direction right so okay so if this is in scene or not in scene then we are not in um okay wait if this isn't seen that means that uh the smaller number my numbers minus k is seen right so that means that we want to put the higher number of uh in higher unique number and in this case this is going to be inferior numbers if it's positive because we have negative numbers now even if negative numbers will just be smaller right so that means that in this case we want to add i a unique number that and uh just numb right and then if num plus k is in scene then we just do higher unique number that add uh num plus k um and then after that so the reason why is because uh what we want is actually max of nums and num minus k but because num is always going to be bigger than num minus k and sk is negative and k is positive right so then you know we can reduce this to just numbs similar thing with numbers plus k right because we're just comparing nums or num and num plus k okay and then now after that we process it we could add it to scene okay and now at the end and we just return the length of the higher unique number and i think that should be good let's find this and also let's wow put in these test cases i say wow because this is annoying to do copy and paste pretend there's a montage pretend i'm playing music uh flying songs that would get me to introduce copyright but you know let's pretend i'm doing that and maybe skip forward like uh 15 seconds while i do some copy and paste i always say i usually do copy and paste but i guess in this case that's a little bit not what they mean um okay so let's run the code real quick so the bare minimum that i always do on testing is always at least tested inputs that they give you because at least you know the answers i think the other one is maybe something like that um i think this one's already given some variation of it but let's say one five something like that uh and then just can and be numb no okay so uh i guess just one that doesn't really matter or shouldn't matter so it looks okay let's submit it sweet uh yeah so this is um by itself this is uh a straight forward problem kind of it's not that easy but it's not that hard uh something that if uh you see again and need code so definitely practice a bit that's why i say that you should get used to it but um this idea of the cena way uh is something that um is the basis for what i call the prefix sum sometimes prefix sum but just a prefix uh dynamic programming where you have to look up something from a prefix either the sum or some function over the prefix right um and that comes up a lot in dynamic programming at least on neat code because i think it's in a meta or something i don't know but i've seen it more than i feel like i did say 10 years ago uh but it is what it is so definitely um practice familiarize yourself with and also if you have time like i said uh you could sort the nums and then do the two pointers uh of course i just gave you the algorithm so it's not that hard but sometimes you get off by one with implementation so definitely play around with that and let me know how you did let me know what you think uh again just to go with because i don't think i did explicitly i said it in the beginning this is linear time and linear space is these two and linear time is that it takes over one for each of these assuming hash tables or one dimension you want to ask but yeah that's what i have for today uh let me know what you think hit the like button hit the subscribe button join me on discord and i will see y'all tomorrow bye
K-diff Pairs in an Array
k-diff-pairs-in-an-array
Given an array of integers `nums` and an integer `k`, return _the number of **unique** k-diff pairs in the array_. A **k-diff** pair is an integer pair `(nums[i], nums[j])`, where the following are true: * `0 <= i, j < nums.length` * `i != j` * `nums[i] - nums[j] == k` **Notice** that `|val|` denotes the absolute value of `val`. **Example 1:** **Input:** nums = \[3,1,4,1,5\], k = 2 **Output:** 2 **Explanation:** There are two 2-diff pairs in the array, (1, 3) and (3, 5). Although we have two 1s in the input, we should only return the number of **unique** pairs. **Example 2:** **Input:** nums = \[1,2,3,4,5\], k = 1 **Output:** 4 **Explanation:** There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). **Example 3:** **Input:** nums = \[1,3,1,5,4\], k = 0 **Output:** 1 **Explanation:** There is one 0-diff pair in the array, (1, 1). **Constraints:** * `1 <= nums.length <= 104` * `-107 <= nums[i] <= 107` * `0 <= k <= 107`
null
Array,Hash Table,Two Pointers,Binary Search,Sorting
Medium
530,2116,2150
449
hello guys welcome to my youtube channel all right hey so today i have come up with a very interesting problem uh it's a medium level problem but uh it can get confusing and i want to do it like a two video kind of series so i'm gonna do uh so this is like this one is like serialized dc live bst and then another one i want to do probably in the next video is a serialized dc realize binary tree and this is bst so yeah i hope you know the difference is this the bst there is a rule that your left node is always less than or maybe equal to your parent and right is always greater than or maybe equal to in some cases again to your parent so with that said let's go take a look at this so serialize dc relies bst so here we have been given a tree node and the idea is to serialize that means to convert it into some kind of a string right so and then dc realize again to take that string and reconvert that tree so my idea over here is uh okay so what i'm gonna do is like in serialize i'm gonna iterate uh in like a pre-order fashion so i would check the a pre-order fashion so i would check the a pre-order fashion so i would check the left right and the parent and probably i would convert it into you know the value i would take it in an array and then at the end i would just convert the other into a string right so let's just go at it so all right uh let me say um so it's serialized so i would want to create a function called func and what should i name it uh in code right uh just a helper function i would use here just like that and my cellulite is gonna call this of course and this is gonna get called in a like a recursive fashion and this so it will accept a root tree note and the return of this guy i want to say it's an array and i would say i should just convert it into string right here right let me just keep it in for now see how it goes okay cool all right so that being said let's just call um you know encode from here root and um that result and over here what are we doing we are checking if um uh let's so what's the idea that if the root is nil you know the first thing we want to check here then what do we want to do like if the root is nil then just i guess just return an empty array right yeah so uh okay uh let's just how about let's just guard it's null so you just want to return an empty array otherwise uh return you want to process uh what's in the roots left so that's what we said in code then we're going to process the left and then right and then the value okay so we will say return in code root dot left and we have already optional binded it so we don't like need to do question mark over here again um plus so what i'm trying to do here is that you know i'm gonna add all the arrays so i'm converting uh you will know when i do this one second let me just finish up this real quick so we're gonna do process the left then we're gonna process the right and then finally okay we're gonna process uh the vowel which i will just put into an array and then i'm adding all the arrays to give it a uh you know the final array and here i can just say root dot val because again i have already option cascade so what i'm doing here is that uh you know i'm adding i'm appending so this the result of this will be like an array this will be array and this will this add the value i have put it inside and it's all that will be combined right and this will be called recursively and you will get your final array and over here i'm calling this and i'm saying what uh so again return and so here was the idea that idea is that to convert this array of integer into a string i guess i can use a join so result dot joint and what should i put here uh i get separated by and let's just use and space so now let's just see if this takes in directly um you know uh this integer to string conversion i'll have to do it manually i'm not 100 sure i'll just do null over here and try to see like compile it just to make sure okay uh referencing instant memory join uh yeah that's what i thought so that's what i thought basically this may need a string conversion so let's just do it here and change it to string i believe now it should work separated by x oh sorry yeah separator when you do components then you do separated by okay cool all right just wanted to check compilation errors so far so good our encoder is working uh well not working but clicks doesn't have a compiler uh let's just give it a look at these relay so what's the idea again so the idea is that from the in code we're gonna get this string and we're gonna take the string like element one at a time but one thing i wanna highlight is like you see first i'm pressing left then right and then that so we have to like reverse it because um imagine if you have like a um let's say you have like over here you know you have something like a tree like two and on the left of the tree um you know i should probably have something but anyway on the left of the tree yeah this way it should be i think not too bad to understand right on the left of the tree let's say you have one and on the right of the tree uh i mean sorry on the root node you have uh three right so root is two left is one and right is three so with joined you will get actually uh like in a string of one space two sorry three space two because that's what we are doing left right and the root right so once we get this back in the decode and we convert it uh you know into an array back our array will look like one two one three two so imagine this as a stack we'll have to take two first that would be root three which is the right and one which is the left that's why it said the order of dc lies would be root then right and left exact opposite of what i did in the encode okay with that again let's create our helper function real quick uh just guys so let's call it d chord and again this will take just a data of string and um i'm not sure what's the return it's going to be let's see um so what does the decode is going to do basically it's going gonna decode it right so all right so once we get the data formed which is a string um let's just real quick um let me think uh i guess i can just convert it into an array right here okay let's just do simple things over here i'll let a or r is equal to array um and since it's a string and i wanna like separate it so i guess i can do this data dot uh components separated by and here we hit separated by space we can do a quick sanity check if you guessed it that if data dot count is equal to zero then i guess you can just return no right you don't have anything to process the data count is zero so just return the time but if it has something then my array is gonna be component separated by space so i have this array which i was talking about up here and i guess once i have the array let's just pass our array over here so um i guess one thing i can try and be smart little smart over here is to do a compact map which basically what i'm trying to do is like converting it into uh you know from string to array from string to integer conversion so directly rather than tackling that over here maybe i can attempt to do it right over there so zero uh and we want it to return to end so dart so again dollar zero is basically the first element of general array which is what which is our one right uh so yeah one two three so i want we want to convert it into int right and difference between the map and compact map is that uh if you know something is nil like conversion didn't work then that value will be omitted and that's what we want right we don't want any junk value so what we said data are components operated by space that's going to give an array 1 3 2 and this compact mac should convert it back to int so array should be an arr should be an array of integer rather than strings so we can just over here take array which should be of type and right okay and this should return tree you know what i think okay cool all right and uh so we got that array um and i'm just debating maybe sanity checking over here we can just do over here so that right uh if the count is null then it's you know you don't have to double standard check just one should be fine all right so far so good i believe and let's just now think what do we want to do over here so in decode once we get an array what do we want to do um well we have already tested that if count is zero then let's just do that sine check one more time over here so if arr dot count um is equal to zero then basically return and i'll tell you why i'm doing this again because i am gonna remove items from this array and i want this recursion to stop once they come to zero that's why i'm doing it again in case you're wondering so just hold on one second so yeah so if ar dot com is a good return now if it's not nil then you want to take the last because we are tackling it as a stack so the very first element and remember we gonna tackle the node first like a parent node then we're gonna do right and then we're gonna do the left it's so exact same opposite order of this one so uh let's just get our you know last guy so what we gonna do is um if let val or last item is equal to array dot last and maybe we i don't need to if you let it because i know that this has something uh this has a you know this discount is not zero so maybe i can just force cast it so i got the last item here now it's very interesting thing which i'm forgetting here uh remember bst is uh you know a constraint on a tree on a regular binary tree that your which i said earlier the left and right constraint so in order to follow that constraint i'm gonna have a left which is an end and i am gonna have a right which is also an end right and here what are we trying to say is that this constraint which originally when i will call decode will be like array and i'm gonna say in dot min i believe it's small yeah and i am gonna say int dot max so it's just a minimum smallest boundary and the maximum boundary just to start off with so here we want to say that if last item doesn't fall within this boundary that means that we're gonna skip that uh so if last item is equal to again so just know what i'm talking about uh if we will say last item okay is smaller than uh left or last item is greater than right which basically and here you would be a little bit confused maybe because you think hey this is min and max how wide this will be ever be less than left or greater than right so uh just again bear with me uh we want to say return uh no this is not the right time and again i'll explain this thing just in just a bit and then what i want to say that if it passes this filter test and this is the right place for that value so get that value so what i'll say is that let val is equal to array dot remove last okay i grabbed the last element from here and i will say let root is equal to uh you know tree node and maybe i wanna say it's nullable you know question mark of type it's nullable and value is going to be val and so we have created this node whichever place this recursion is and if the last item is within this boundary then you are then it's the right item to extract so till here we didn't extract it right here at line 40 we extracted the element take it out from the stack created a node out of it uh and if you're confused with this root i mean we can just name it node you know because i usually get like hey is this root every time we are getting root no it's just a node uh ultimate the final stack uh you know the first thing will be the root node the first thing extracted because in this example you know whatever is the right most guy is your topmost root of the tree so let notice between our value and we want to say that node dot right or left if you guessed it correctly it's actually right because we're gonna exact opposite order of this so node.write is equal to decode node.write is equal to decode node.write is equal to decode and here is where i'm gonna explain you uh er and uh so we wanna capture the rights so we are saying the val is the parent and what is gonna be the right node so uh that would mean that it should be always greater than the value right so its left boundary will become what val and the right boundary will be right whatever it was and similar thing let's tackle the left of the node what will be the left so if it's the left child then the value of the parent the left is always going to be smaller than the valve so here it's going to be left and the right is going to be val and ultimately we can return the node gotcha and uh sorry so the very first time you're gonna call the right uh what it's gonna be called with uh you know so what are we saying here that our array is one and two this is our initial array right and we are saying uh so basically our tree is going to look like 2 is the root note and 1 is the left child and we are saying that first thing when the very first time it will be called we will grab 2 because the last element with the left into min and the right into max 2 of course is not less than intermittent and not of course greater than right into max so it will not fall under this and we'll remove 2 and we'll make it node right then we'll call node.right call node.right call node.right and we'll call it with um you know array will become one because we have removed two and val is gonna be um with your left which is gonna be two and your right is again max right so we're gonna call this and it will come over here and it will grab the last item which is one it will check hey last item is it less than left yes it's less than left because left is uh two so it's going to return and that's how it's going to know that hey this is not the right time then it's gonna go to left and it will call with again array one and uh the left will be uh basically min and uh right is gonna be your uh two right your valve and we're gonna check come over here and see the last item which is again one and is it less than left yes it's less than oh uh no it's not less than that because it's in dot min right hey or last item is it greater than right uh no it's not greater than right it's one and so one is not greater than two so it's not going to fall under and that's how we know that hey the valve is actually correct remove it and now this will be ultimately be returned to the left child of the node and not the right channel that's the logic that's why this will work so let's just give it a shot real quick first of all the code is gonna give us a tree node and we can just return this so let's try to run it and see if i've made any compiler yes i have done it uh i don't need if here let last item okay uh mutating member arr okay so i think the problem over here is that you know so let's say you have uh you know again two uh one and three right and the very first time three gets removed and you will be left with two and one you call right uh and sorry not two and three uh so very first time it's gonna be one um what is my stdr one three two that is what the decode is gonna get right so the very first time two will be removed and you will pass one and three to right now in the recursive call when right record right would call the decode it will also remove uh three now when it comes back to this call the earlier stack what would what's happening here is that the code is calling with the same array snapshot which was one and three and not with just one because the right call actually removed already three but this stack doesn't know that because each stack is maintaining its own variable so i think the problem over here what i did was the silly one that i should make it instead of you know like you know passing by value i should pass it by reference so let's just quickly try that so in out is how you do in swift uh just change this to your passing memory now and now we don't need that because once it's a memory reference you can actually change uh you know it's stuff so over here again pass it by memory uh pass it by memory and this may not work here because for memory you have to be aware not let and let's just give it a try let's see okay and as you can see and submit okay yeah as you can see i've already tried that yeah that was the issue over here all right cool thank you guys hope you enjoyed it uh and see you next time
Serialize and Deserialize BST
serialize-and-deserialize-bst
Serialization is 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 search tree**. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure. **The encoded string should be as compact as possible.** **Example 1:** **Input:** root = \[2,1,3\] **Output:** \[2,1,3\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The input tree is **guaranteed** to be a binary search tree.
null
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Search Tree,Binary Tree
Medium
297,652,765
1,065
hi so this question is index pairs of a string so you're giving the string text and a real string words so you are going to just find out if there is a word in the text and if you do then you just find out the index from the beginning to the end so for the story uh this list is going to be the story right so three seven so you could have a duplicate value you know uh probably store story arrival here or story rubber here right so you just have to list or even like this like ABA right and then APA is like this so it's going to be about zero to two and how about this ABA so it's going to be about two to four right so you can reuse the index so how do you actually do this is pretty straightforward so if you use a uh if you just know the headset so I'm going to convert list to the set and I'm going to use the two uh two pointer to Traverse but in this one I'm going to use the brutal force because I have really no idea what is the value after the touring this right so I'm going to Traverse J all the way up from beginning all the way to the end if you cannot find anything I move my eye pointer right by one right so I'm going to just erase so I'm going to say our eyes starting right here and Jay was starting at the same position and then keep going right for the J and then if you cannot find it then you move your eye by one again so just keep doing this until you find everything right on I mean until I reset the end right so uh let's just start coding so you want to return it into the array and yeah so what I will do is I'm going to push into the list and then since I don't know the size of the answer so I'm going to just use a list of an array then once I finish I'm going to convert what the insert equal to new end and so it's going to be size and then I'm basically this is how you convert right so I'm going to just uh say result.2 array just uh say result.2 array just uh say result.2 array and I'm going to put a pull it into the area which is the answer so I'm going to convert the result to array full of value then I'm going to assign it so just to get a document you cannot find I mean if you don't understand right so first thing is going to be convert the string array to the set string right so I'm going to say set and then using the stream so okay sorry I'm going to say array start screen followers dot collects and then collectors.2 set collectors.2 set collectors.2 set so this is how we convert right you from shooting array to let's say so it's going to be like one line so you can use the fold Loop doesn't matter right so uh now I use a brutal force in I equal to zero I listen takes a length now plus right I plus and then exactly going to be the same thing for J but it's not going to start from zero it's going to be soft from I and J lesson takes the length and then J plus so now I need to keep finding right so I'm going to say what is the current substring between I and J Index right so it's going to be substring sub string equal to what uh textile substring I comma J and then now I need to say if the Theta contains the substring right uh I need to what add the answer right so assume the result right so there is a I mean there's actually a trick I left behind so when you say something like you need to include the J in X Y so it's gonna be about J plus one right over here right so because option you definitely exclude the last Index right so if you say I comma J and then you are not including the J in this I mean J Char right so you want to include the J chart then you want to say J plus one because you're not including the J plus one character and then this is pretty much a solution so let me run it oh uh typo and yep here we go so submit all right so let's talk about the time and space this is gonna be what the space this is going to be a space and then for the set it's going to be all of w represent end of the words and this one is going to be representing the text right so I'm going to say if you keep finding so if a set so if a text if the text is actually a and then the words uh it's like this when you actually add you will actually add every single a into the text so I'm gonna say all of N and represent the text over array I mean the length of the texture the length of the text for the full space right level of time this is going to be a time so the time is going to be what elephant times elephant which is n square and inside the N Square you'll just substring so if you use a substring um what you would do is why you are taking the index right you're taking the two index and then get a current string so if you look at the documentation then this is actually what all of uh be honest so for the worst case it's only all of N squared on Cube but most people I mean probably I didn't actually remember that what is the algorithm behind the substring but um I'm going to say all of unq and if you're not looking this then you it's going to be about all of N squared right and then contains all of one as all of one and this is a space are the same right all of them so this is a solution so I'm going to use a debug mode and I use definitely look at it so I'm going to just pause right over here and then install the debug mode and then starting so I'm not going to explain when I debug debugging and then you just do this okay so don't get the left window foreign so I'm not going to stop right over here I'm going to stop when you add so story sweet little and stories on the list and then you finish right so you convert it again all right so if you have any question leave a comment below subscribe if you want it and I will see you later bye
Index Pairs of a String
binary-string-with-substrings-representing-1-to-n
Given a string `text` and an array of strings `words`, return _an array of all index pairs_ `[i, j]` _so that the substring_ `text[i...j]` _is in `words`_. Return the pairs `[i, j]` in sorted order (i.e., sort them by their first coordinate, and in case of ties sort them by their second coordinate). **Example 1:** **Input:** text = "thestoryofleetcodeandme ", words = \[ "story ", "fleet ", "leetcode "\] **Output:** \[\[3,7\],\[9,13\],\[10,17\]\] **Example 2:** **Input:** text = "ababa ", words = \[ "aba ", "ab "\] **Output:** \[\[0,1\],\[0,2\],\[2,3\],\[2,4\]\] **Explanation:** Notice that matches can overlap, see "aba " is found in \[0,2\] and \[2,4\]. **Constraints:** * `1 <= text.length <= 100` * `1 <= words.length <= 20` * `1 <= words[i].length <= 50` * `text` and `words[i]` consist of lowercase English letters. * All the strings of `words` are **unique**.
We only need to check substrings of length at most 30, because 10^9 has 30 bits.
String
Medium
null
1,022
okay cool 10:22 summer boot to leave okay cool 10:22 summer boot to leave okay cool 10:22 summer boot to leave binary numbers come in a binary tree each node has value zero one each boot to leave path we represent a binary number starting with the most significant bit for example the power 0 1 then this could represent 13 and binary what are the leaves in each we consider the numbers whoever signed up by the path from the tree but did I know we turn to some of those numbers okay I mean I said that bad I think I mean I have to just have to figure out PHP I think that's the hard way yeah because mm-hmm and I'm thinking either because mm-hmm and I'm thinking either because mm-hmm and I'm thinking either doing it cheesy right with like a Cuervo or just like be a little queen I want to do it on the plane I mean this is also optional parameters maybe I could take advantage of but it's I don't know go you know I mean PHP enough but yeah I think yeah that's just to the poor show where you have to push or some and then to the note so then in this case we'll just return and okay so then we just okay if you've no I guess this could be no and this is uh I actually don't know if this is too wide syntax for PHP it says how you check for now I think it's sad right I mean I think you can also check for no but we could check to see that this isn't value yeah I said then just return zero and then now well otherwise just return okay well so that's just to the curb so now we're just doing the prefix breathe I just got a new partial if you go to the partial sum x 2plus despy you I'll still do yeah this time right oh no that value right actually I guess we don't need that then well okay we've quit cursing so that's a just some typing so now we just return some of boot to actually the base case is actually a partial not zero because you're passing it down so now you're passing this to new partial no to the left plus some boot if I'm reading the wall function but its first part but also I got the syntax ball it should be this and this is why I do not do interviews and PHP help each HP let's give it a go I don't know how it would t pontus if I come to the about this oh noes is that it mmm still a good test typed me no it's not just oh this Illinois maybe that's a yeah I mean I'm not for me okay so maybe there's it oh no I didn't do it in the other point so it's been a complaint so there may be a better way to do this yeah okay I already typed it but yeah this is what happens when you don't know PHP or given language oh no see huh that is actualizing everything expecting something but uh okay that's this I just see we may be my is set as well I think that is stuff that at one time they were just to avoid dump I haven't done PHP in a few years so okay so we just do the recursion so I just get the wrong answer what well I could get the wrong answer which is very poor I fear I'm rolling this one and that in that it doesn't do a weaker acid to a recursion am I miss reading this it doesn't seem like it's doing any recursion I mean it just prints out the entire tree node which is fine but it doesn't do this week so maybe I don't know PHP I've never done recursion with PHP actually so okay so no to the love just giving me none maybe I'm just a bad syntax oh maybe I don't have this maybe mice in Texas one sorry friends yeah confusing languages in my head maybe I was returning to the class version of it okay that's not bad I mean problem okay qualms is that I shift on this and I don't this cuz I calculate the sum for this node okay fine because on leaves I calculate it here and it already got white shifted whoops so we need to do this I mean that's fine we could also have done some if statement here so this makes it slightly unclear maybe but uh that's okay we just do an extra shift for bonanzas oh maybe I'm wrong on that one what is this input why is that tweet my leg wait I got me once my Oh cuz for an incomplete tree okay so hmm I guess I do need you neither thing here so notice empty that means its parent don't like a do prefix them but yeah okay fine is have to add an esteem of if no so basically this means if this is I'm you know then we return new partial right yes that right mm-hmm right yes that right mm-hmm right yes that right mm-hmm you know off by one somewhere might tap that is odd right so I think I believe you think everyone just to be a leader for my if statement is wall in this case all right I guess I might as well be a little responsible and test a few more today I'm learning PHP I'll show some support not for PHP having haven't done any another baby what are you judging that's all very good and yeah 1,000 I think Nico is having issues that's my guess I think we flush this page maybe my Internet's having issues if you could hear me let me know okay cool I didn't have my test cases now PHP maybe this is why people use PHP for their coding interviews okay cool yeah I'm faster than a hundred percent of page I don't know how many people did in PHP so it was less impressive than I thought it would be okay cool when the issue was that uh this was with double counting for non-tree so we have double counting for non-tree so we have double counting for non-tree so we have to check to see where was the leave I would say oh yeah I might be the first person to turn in PHP I don't know why they even support the language though I had a real bug that was independent of PHP I just I was hoping that the edge case was okay I think I didn't Python I would have added it in a different place so quite um yeah that's no excuse but yeah but this is a way straightforward ish I said that as I got it incorrectly tree problem of recursion so is that me something I recommend studying because people love trees and pure love recursion on interviews for whatever reasons so yeah that's right
Sum of Root To Leaf Binary Numbers
unique-paths-iii
You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit. * For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`. For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_. The test cases are generated so that the answer fits in a **32-bits** integer. **Example 1:** **Input:** root = \[1,0,1,0,1,0,1\] **Output:** 22 **Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22 **Example 2:** **Input:** root = \[0\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val` is `0` or `1`.
null
Array,Backtracking,Bit Manipulation,Matrix
Hard
37,63,212
1,679
daily lead code challenge so today's question is maximum number of k sum pairs okay so you are given an integer error nums and an integer k in one operation you can pick two numbers from the array whose sum equals to the key and remove them from the array return the maximum number of operations you can perform on the array okay so basically so let us look at the examples like one two three and four and k equal to five and the output is one and four two and three okay two is two pairs are possible and here three one three four three k equal to six yeah here only one pair is possible that is three and three or either this three and this three or this three and this three so there is no other possibility for this so okay now so basically they're asking us we have to find the unique pairs whose sum equals to the given k value okay so of course there are many approaches to solve this question so uh so i am going through this uh two pointer approach okay so the basic idea is that first we have to sort the array okay after sorting the array then take the low pointer i mean two pointers low and high where the low will be pointing to the zeroth index and high will be pointing to the last index okay now let's come here so okay we have taken the low pointer and the high pointer which will be pointing to zero and the last index of the array and the c pointer i mean okay a variable c which counts the number of operations we are doing okay now what we'll do is while low less than high if numbers of high plus numbers of low equal to k that means the names of phi that is this one and names of flow this one the both the sum of the first and last index whenever it is equal to k we will increment the c value okay now we have already got the pair we have to discard them so what we'll do is we will move forward from the low pointer and move backward from the hypotenuse we move one step forward we will increment the lower pointer and will decrement the high pointer okay now if names of high plus numbers of low greater than k means what where what we this condition is that numbs of high plus numbs of low greater than k that means we got the value which is greater than the required then what we have to do is we have to discard the last value let me the last index value right so we will decrement the high pointer else means the remaining leftward cases numbers of i plus nums of low less than k that is so what the value which we got is less than the k value so what will then what we will do is we will increment the low point okay pretty much this while loop will be satisfied will uh this while loop is enough and we will return the c value okay now let us make a dry run for this okay let's take this example because it's already sorted let us take this example now 3 1 3 4 and three so after sorting now we have to sort this it becomes one three and four okay now first what happens is the low pointer will delete this the low pointer points to one high pointer points to four now the k value is six okay now num nums of low plus number five so one plus four is not equal to six which is less than 6 okay so what we'll do is we will increment the pointer now okay increment the low pointer now 3 plus 4 it is 7 is greater than 6 what we will do is we will decrement the pointer now here the uh keep track of the low and high values low is one and high is two okay high is three okay low is one and high is three the condition is valid three plus three six numbers of five plus numbers of flow equal to six okay now what we will do is we'll increment c now c becomes one increment low value uh low becomes uh two and high becomes two so this condition fails to execute and while loop will not be executed comes out of the while loop and the c value becomes one this is the solution for this problem okay
Max Number of K-Sum Pairs
shortest-subarray-to-be-removed-to-make-array-sorted
You are given an integer array `nums` and an integer `k`. In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array. Return _the maximum number of operations you can perform on the array_. **Example 1:** **Input:** nums = \[1,2,3,4\], k = 5 **Output:** 2 **Explanation:** Starting with nums = \[1,2,3,4\]: - Remove numbers 1 and 4, then nums = \[2,3\] - Remove numbers 2 and 3, then nums = \[\] There are no more pairs that sum up to 5, hence a total of 2 operations. **Example 2:** **Input:** nums = \[3,1,3,4,3\], k = 6 **Output:** 1 **Explanation:** Starting with nums = \[3,1,3,4,3\]: - Remove the first two 3's, then nums = \[1,4,3\] There are no more pairs that sum up to 6, hence a total of 1 operation. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 109` * `1 <= k <= 109`
The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix.
Array,Two Pointers,Binary Search,Stack,Monotonic Stack
Medium
null
67
hey everybody today we're solving lead code 67 which is called ad binary the question asks given two binary strings A and B return their sum as a binary string we'll go over a couple of different ways to solve this today and we'll go ahead and get started with method one our binary strings are A and B respectively of 101 and 1011 underneath each of these two binary strings I just have the bit place values our first step for this method is going to be to First convert these numbers to decimal and take the sum so uh 1010 is going to is just representing the decimal number of 10 if we just take the sum of these all these positions we'll take the 8 plus the two and then the four and one have zero so we don't use any value from that 8 + 2 is 10 and use any value from that 8 + 2 is 10 and use any value from that 8 + 2 is 10 and then for 101 we take 8 + 2 + 1 and then for 101 we take 8 + 2 + 1 and then for 101 we take 8 + 2 + 1 and that's representing 11 10 + 11 is 21 now that's representing 11 10 + 11 is 21 now that's representing 11 10 + 11 is 21 now all we need to do is convert that back to Binary and that's our final answer so 21 represented in binary is as following we just fill in the right bit place values of 16 4 and 1 16 + 4 is 20 + 1 values of 16 4 and 1 16 + 4 is 20 + 1 values of 16 4 and 1 16 + 4 is 20 + 1 is 21 and our final answer is 10101 so this method is very well works very well for smaller binary numbers but it's going to encounter Precision limitations for very large binary numbers due to javascript's number representation and I'm going to be using JavaScript to solve this um I actually ran this on code and it didn't pass all the test cases uh so we're going to need something more Compact and that's where method 2 comes in so for method 2 we're going to use the exact same two binary strings of 1010 and 1011 however right here I just want to make clear up that these are indexes underneath in green I just that's going to be important for later just to help us keep track of the position I know over here I had the bid place values this is completely different than these indexes this is just representing the position of every element in the string okay now that we have that cleared let's look at the variables we're going to use first of all I want to go over the carry variable carry is initialized to zero and this carry represents the value that is uh carried over from one digit position to the next when the sum of the current digits exceed the base of the number system the carry is important because it affects the sum of digits at the next position when you encounter a carry you need to account for it in the addition of the next digit so if the sum of two digits is two which is like just 1+ one you write down a zero like just 1+ one you write down a zero like just 1+ one you write down a zero for the current position and carry a one to the next position to the left I'll demonstrate that now in case it's not clear so I'm going to just do this exact same exam example um but I'll just do it directly like this 0 + 1 is going to be directly like this 0 + 1 is going to be directly like this 0 + 1 is going to be 1 that's very faint 0 + 1 is 1 and now 1 that's very faint 0 + 1 is 1 and now 1 that's very faint 0 + 1 is 1 and now we have 1 + 1 that's two as I mentioned we have 1 + 1 that's two as I mentioned we have 1 + 1 that's two as I mentioned if we have to we can't write two right because we can we're only dealing with zero and ones in binary so we're going to put a zero for the current position and we'll carry over the one to the next to the left hand side because we work right to left uh with binary I should have mentioned that so now we have the next position 0 + 0 and then we also have to uh consider + 0 and then we also have to uh consider + 0 and then we also have to uh consider the carryover which is one so 1 + 0 + 0 the carryover which is one so 1 + 0 + 0 the carryover which is one so 1 + 0 + 0 is 1 and now we have 1 and one again that's two we put a zero in this place and we put the carry over on the next column and since we have no more remaining numbers here we'll just use 0 and 0 1+ 0 plus 0 is 1 and our final and 0 1+ 0 plus 0 is 1 and our final and 0 1+ 0 plus 0 is 1 and our final answer should be 1 0 1 01 if you confirm that down here where I actually went through the entire process it's the same thing so I hope that carry is now uh clear to you the next thing is this result variable of initial as the string and this is going to uh store the final binary sum that we're going to return our I and J are just going to be uh pointers that are going to help us iterate through the input string from right to left I've initialized them at the as a do length minus one so we can start at the very end so just keep in mind that we subtract one because uh we're using zerob based indexing when we're operating on strings and uh arrays and whatnot so let's just jump right into it now with uh we're working right to left so at I equal 3 at J equals 3 and so far we have a carry of zero these are going to be the three important things we carry over we uh are keeping track of because all of this is happening inside of a while loop and our conditions are going to be so as long as a has a length as long as B has a length um and as long as there's no as long as uh there's carryover we're going to be uh carrying out these operations we want to make sure we're keeping track of the lengths or position of I and J and a and b uh separate respectively because these can be different lengths right now I've made it them convenient that they're the same length but if a was greater than b or if B was greater than a would want the loop to continue while either of them still have lengths all right now that we're all set let's start off with getting our number from a and our number from B those are just going to be the elements at that index position of three so for Num a we have zero for n B we have one moving on we're going to calculate the sum so that's going to be the sum of num a plus num B plus whatever the carry over is initially that's going to be set to zero as we did but remember from up here when we started adding them to uh the actual sum we're just going to account for that from the beginning so 0 + 1 plus 0 is just one and that's going + 1 plus 0 is just one and that's going + 1 plus 0 is just one and that's going to be our sum now for the result string we're going to be taking the modulo of su modulo 2 and we're going to add the rest of the result string to the right of that so one modul two well two goes into one zero times because it's greater than it so we're going to have a remainder of one and since we have an empty string initially that's going to be all that's in the string so that's the most rightmost element of our final answer finally we'll calculate the carryover and that's going to be a math Bel floor which just rounds it down of the sum divided by two our sum was 1 so 1 over 2 is 0.5 if we round that down it 1 over 2 is 0.5 if we round that down it 1 over 2 is 0.5 if we round that down it goes to zero okay now we can move on to the next position we'll decrement our pointers I inj so now they're the second index our last since our carry was Zero we calculated we're going to also have that so num A and B are one and one respectively at index two our sum is going to be the sum of these num a plus num B plus the carry and that's two to calculate the result variable we're going to be taking two modulo 2 as this was the equation earlier sorry sum modul 2 plus result so our sum is two we take that modulo 2 so there's no remainder remaining so we're going to have zero and then we're going to be adding whatever the result string is and we only have a one so that's that and two module 2 as I mentioned is zero there's zero remainder so we just have that and that's concatenated together finally we'll calculate the carry variable and that's the rounding down the sum over two the sum was two divide that by two which is one round one down is just one so our carryover is one I'll move over the next three pretty quickly now that we have a good grasp of this we'll decr the pointers we're at index one now our num a and num B are zero respectively our sum is going to be 0 + respectively our sum is going to be 0 + respectively our sum is going to be 0 + 0 which is just num a plus num B plus the carryover remember we calculated the carryover as one so we're going to keep track of that our sum is one our result is just one the sum modulo 2 which is one and append that to the left of the result string so we have one 1 now our carryover is zero you can do that on your own if you'd like using the formula next position we decrement so we're at I equal 0 J equals 0 and our carryover is zero positions that those index is one for both num a and num B we take the sum as 1 plus 0 because the carry over zero that's equal to two our result is equal to 0 1 0 once now and our carryover is one finally we get to the oneth position because we're decrementing right we'll have to create as I did here we'll have to just set these values to zero because there is no valid value for Num a or num B at that index it doesn't exist right so we're going to have to take that value of zero we'll calculate the sum as 0 + 0+ 1 we'll calculate the sum as 0 + 0+ 1 we'll calculate the sum as 0 + 0+ 1 because we had a carry over remember we're operating this whole Loop while either a has a length B has a length or we have carryover and we've actually exhausted the lengths of A and B there are no more elements remaining but we still do have carryover so this final iteration is still going to continue so we calculated our sum now the result is going to be that and it ends up just being one one01 finally we'll calculate the carryover that there's no carryover remaining and we can return our final result of one one01 which is the same as what I got using this method and that is the correct answer here is the code to our solution so first things first we're going to initialize all of our variables I've already gone through this on the Whiteboard so if there's any confusion surrounding this please rewind the video next we're going to enter our while loop that's going to continue until we've processed all digits in both input strings and there's no more carry left we're going to get we're going to obtain values for our num a and numb variables through this conditional operator we're going to check if the pointer as is at a valid position of greater than or equal to zero if so we're going to be calling pars int on the relevant string at that index remember these are binary strings that were given they're strings so we're going to have to convert them to an integer before doing any sort of AR arithmetic on them if the pointer isn't at a valid position then we're going to assign it a value of zero we'll then calculate the sum considering all of the num a num B and the carry we'll then calculate the result by taking the modulo sum mod 2 plus the rest of result we can then calculate the carry by rounding down the result of the sum divided two finally we'll decrement M the pointers I and J then we'll exit the loop after we've exhausted all the string lengths and carryovers and we'll finally return the result if I run this should T pass our test cases now I'm going to submit it wonderful final thing to discuss is the time complexity and space complexity so our time complexity is going to be Big O of the length of the longer input string n or M where n is the length of string A and M is the string length of string B in the worst case the loop will iterate through the longer of the two input strings or continue looping until the carry becomes zero our space complexity is the exact same o of uh the length of the longer input string nrm and the length of the result string can be at most uh the length of the longer input string plus one considering the possibility of a carry in left Mo position before I wrap up this video I just wanted to touch on the carry variable one more time I understand that the math. floor and dividing the sum by two isn't exactly intuitive so I wanted to make it a bit more clear or come up with a different way of uh finding the carry I'm going to go through the exact same process uh but this time I'm going to be using the number seven and that's the binary representation of that I have that set up here where I'm just uh taking the binary sum of seven and seven first thing I want to touch on is the list of possible sums since we're only dealing with zeros and ones in this binary the only possible results of this addition we can have is 0 1 2 or three because if those are the only possibilities that are going to arise of summing uh zeros and ones three times these aren't an exhaustive list of all the possible configurations in which you could but it is one of the possibilities so the first two numbers are representing the digits from string a and string B and the number in green is representing the carry cool uh also this table here is representing the uh these decimal numbers so these sums 0 1 2 and 3 in binary format now that we have that context let's get started with this so zero that's the carryover 0 + 1 + 1 is 2 zero that's the carryover 0 + 1 + 1 is 2 zero that's the carryover 0 + 1 + 1 is 2 two in binary is one and zero we read everything from right to left in binary so we'll put the zero down in place of this column and then in the next column that one that's going to be the carry so we'll take that to the next column and put it up there one is the new car now we're going to do 1+ 1+ 1 that's three we're going to do 1+ 1+ 1 that's three we're going to do 1+ 1+ 1 that's three represented binary is one and one we'll put this one's place down here and then reading from right to left the next column is the two's column that one is going to be the carryover and we'll throw that up there we have the exact same thing again so 1 + 1 + 1 is 3 same situation we'll put + 1 + 1 is 3 same situation we'll put + 1 + 1 is 3 same situation we'll put the first one here and then the two the one from the tw's column going to be the carryover and now we're in the last column and we have no more numbers for a or b so we'll just assign those the number zero we'll take the sum of 1 plus 0 + 0 that's one as you can see and 0 + 0 that's one as you can see and 0 + 0 that's one as you can see and that's our final answer so if I just do the sum of this real quick it should be 14 and I'll just confirm that for you that's 1 2 4 and 8 + 4 + + 2 is 14 so that's 1 2 4 and 8 + 4 + + 2 is 14 so that's 1 2 4 and 8 + 4 + + 2 is 14 so we're all good okay so if we take a deeper look at this table we can come up with the conclusion for our carry variable if the sum is zero or one there is no carry we'll just use this number directly the zero or one in place of the sum for that digit if however the sum is 2 or three then we're going to have more than one number and we'll have to have a carryover and in both of those cases is going to be one so if I just translate that to an if statement if the sum is equal to zero or if the sum is equal to one then our carry is going to be zero as we can see here otherwise if the sum is equal to two or if the sum is equal to three then we're going to have a carry of one I hope that provides a bit more clarity here's the code for what I just discussed on the Whiteboard with calculating carry using the if statement I've commented out the old way of calculating carry right here and you can see that the there's no difference in the code other than the Z statement so I'm just going to directly submit this and it passes all the test cases for lead code and it's a completely valid way so if this is more intuitive and clear to you than the math. floor and dividing the sum by two then more power to you
Add Binary
add-binary
Given two binary strings `a` and `b`, return _their sum as a binary string_. **Example 1:** **Input:** a = "11", b = "1" **Output:** "100" **Example 2:** **Input:** a = "1010", b = "1011" **Output:** "10101" **Constraints:** * `1 <= a.length, b.length <= 104` * `a` and `b` consist only of `'0'` or `'1'` characters. * Each string does not contain leading zeros except for the zero itself.
null
Math,String,Bit Manipulation,Simulation
Easy
2,43,66,1031
1,601
hey everyone welcome back today we are going to solve problem number 1601 maximum number of achievable transfer requests first we will see the explanation of the problem statement in the logic on the core now let's dive into the solution so in this problem we have a request input so these are the request from the employees who wants to transfer from one building to another building right so here one of the employees want to transfer from building 0 to building one and so on and we have another input which is n represents the total number of buildings we have right so we will be having 0 to n minus 1 buildings so assume we have two buildings here building one and building two and these two buildings are balanced with the employees which is zero right now assume if one employee transfers from building one to building two so here it will be negative 1 since one employee left and here we will add one since one employee moved to building two so in this problem this transfer is not considered as a balanced transfer right here it is not balanced between two buildings right in the building one we have negative one which means we need to balance by sending one employee from building 2 to building one to balance this negative one so now it becomes zero so here if I take difference of 1 it is going to be zero now there is a balance between two buildings so this particular concept should be maintained when we transfer employees based on the request given so we need to find maximum number of requests can be achieved so here we have six requests out of the six request how many requests can be achieved right that's the goal of the problem so now we will see how we are going to do this so initially we will be having a k variable where it will represent the maximum transfer that can be achieved in this given input so here we have six requests so maximum achievable request or six so we will be writing this K in a for Loop so we are going to keep decreasing this requests to get our maximum achievable request right so initially we are assuming the maximum request that can be my answer right so within this for Loop we are going to create a list that is ranging from 0 to total number of requests that is given so here we have six requests so we are going to create a list of values from 0 to 6. we won't include 6 here right so after creating this list we need to find different combination of elements which will contain six values that is the K values right so here we have only one combination that will be having six values that will be our list itself right so for this K this is fine after that we will be creating a degree list which will be having zeros based on the number of buildings so we are going to keep track of the number of Employees leaving and coming into the buildings right so this zeros are representing the buildings right so initially it is balanced so now we pick the first request right that is 0 that will be our I so we need to go to the first request that is zeroth index request we need to first pick the first building that is zero so we need to update the zeroth index in my degree that one person is leaving from zero right so we need to subtract 1 here so now there is an employee coming from 0 to 1 right that is an employee coming to the building one so we need to update the building one by adding one then we begin next request that is one right so I will be one now so we need to go to the first index request so here the index are 0 1 2 3 4 and 5. so here an employee is going from one to zero right so in the index one we need to reduce one this becomes zero and in the zeroth index there is an employee coming in right so we need to add one this is also going to be zero we go to the second index that is an employee going from 0 to 1 so in the zeroth index in the degree I will subtract 1 and I will add 1 in the first Index right similarly I need to do it for the next request that is one two so here from 1 there is an employee going to 2 so I will reduce 1 in my first building then I will add 1 in the second building then we have to check the next request that is an employee is going from 2 to 0 so I will add 1 here then we pick the next request that is an employee is going from 3 to 4. so I will reduce 1 in my third index and I will add 1 in the fourth index so here we have done with all the different combinations of subsets which has six elements so here in this case we have only one subset which will be having six elements now we need to check whether the degree is balanced or not so here it is not balanced we have negative one so we need to reduce our K so now we need to form subsets which will be having five elements right so we need to form different combinations here so what are the different combinations we can form which will be having five elements here so initially we can pick 0 1 2 3 and 4 this will be a subset then we can pick 0 1 2 3 and 5 right then we can form 0 1 2 4 and 5 then we can have 0 2 3 4 and 5 then there is another possibility one two three four and five right that should not be duplicate subsets we should only consider the unique subsets right so then we need to reset our degree then we need to use these subsets to update our degree right after finishing all the combinations we need to check whether all the elements are set to zero or not that is it is balanced or not so in this case for K is equal to 5 it will be balanced so we need to return K as my answer so we will do it for each and every subset so I will go to the zeroth index subset so I will update the degree by reducing one in the zeroth building and I will add 1 to the first building so we need to do each and every element in the subset so we need to do this for each and every subset right so for K is equal to Phi all the elements in the degree will be 0 right which means the maximum request that can be achieved is 5 that's how the logic is now we will see the code before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so initially we will be writing a for row where we will assume the maximum achievable request as my length of my request right and we will be keep on reducing by one then I will be writing another for row to pick these subsets so here I'm using combinations in build function so initially we will specify the range of the values using the length of the request then we will specify how many elements I should have in each and every subset that is K elements right then I will be creating a degree view list where it will be containing the list of zeros based on the number of buildings right then we will pick each and every request from the subsets that is from C and we will update the degree based on the employees going from one building to another building right then we need to check whether all the elements with the degrees list are balanced that is 0 or not if the all the elements are 0 we need to return K else if we can't find we have to return 0 that's all the quarters now we will run the code as you guys see it's pretty much efficient thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future not to check out my previous videos keep supporting happy learning cheers guys
Maximum Number of Achievable Transfer Requests
maximum-number-of-achievable-transfer-requests
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. **All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. Return _the maximum number of achievable requests_. **Example 1:** **Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\] **Output:** 5 **Explantion:** Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. **Example 2:** **Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\] **Output:** 3 **Explantion:** Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. **Example 3:** **Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\] **Output:** 4 **Constraints:** * `1 <= n <= 20` * `1 <= requests.length <= 16` * `requests[i].length == 2` * `0 <= fromi, toi < n`
null
null
Hard
null
201
hello guys welcome back to my YouTube channel today I'm going to solve day 21 problem of this month only Cod if you guys haven't subscribed my YouTube channel yet then please go ahead and subscribe it now without any delay Let's uh start with our today's problem so in this problem we have given two integers left and right that represent the range okay left and right so both are inclusive here closed brackets are there and we have to return on the bitwise end of all the numbers in this range inclusive okay so uh one basic approach that most of the new beginners will try here they are going to just uh perform the end operation for all the numbers between uh left and right so let's say they are going to perform the bitwise uh and operation between five and then uh 4 six and then seven okay so in this case you will get output okay you are just going to run one four loop from the left and till right and you are going to perform the end operation between all the numbers and storing the result one by one okay so this approach will work for example one example two but this approach will definitely fail for the example three because the number size is see here the left uh right is less than equal to 2 31 - 1 so you can't uh run equal to 2 31 - 1 so you can't uh run equal to 2 31 - 1 so you can't uh run the loop now for all the numbers okay so this approach is not efficient and definitely you will get like time limit exceeds errors like that okay so there is one more easy approach uh to solve this problem okay so let's say okay let me show you one examples here so I have copied all the examples here in this sheet so this is our first example left is five and right is uh 7 so here uh in the binary form I can represents a number like this okay so this is nothing but one okay let me change the pen one this is 2bit this is 4bit this is 8 bit 8 this is 16 position this is 32 okay 32 this is nothing but 64 and this is 128 okay so this is how uh bits are represented for a particular number okay so in this case a number is five given to us right so one is represented like this bit is set to one bit and this four fourth position this 1 2 3 position is set to one so this is how uh five is represented in the form of bits and this is how 7even is represented in the form of bits okay so I hope that you guys are clear so here let's say uh we have numbers uh let's say nine given to us okay nine is a number and we are going to let's write this nine in the form of bits okay so this is a form okay 1 2 4 8 16 so for 9ine I have to set this one with uh this to one and here at this position I need to set one other all other positions I have to just add zero so this is how we can represent nine in the form of bits right this is the way so I have set this position to one and this position to one so total I get the sum as N9 okay so this is nothing but two Z position two of one so I hope that you guys are clear with this uh s these things right 2^ 3 2^ 3 and this is 2 things right 2^ 3 2^ 3 and this is 2 things right 2^ 3 2^ 3 and this is 2 power 4 okay so this is how I am uh writing five in form of bits and seven in form of bits okay so here in this problem uh we have to find the common prefix so here see all the bits are matching 0 here all the bits are matching here all the M bits are matching here all the bits are matching here this bit is matching 0 this bit is matching 1 and after that these two last two bits are not matching right these last two bits are not matching right so these two and these two last two bits are not matching otherwise all the other prefix bits are matching okay so here what I did uh I have write uh here in the prefix I write all the bits so these prefix are matching till here and uh in the end I have added to0 because we don't need the these two bits okay we need uh till the common bit found so here this is the common bit one and after that uh bits are zero one so not matching okay so not matching so we don't need to add them so here uh what is the output this is nothing but one 2 4 okay fourth which is set to one okay fourth this one so here I am returning as four okay so this is a next example six is represented like this seven is represented like this so here all the bits are matching till here okay till here except last bit all the other bits are matching okay so here uh I have written uh like this 0 1 0 okay so here what is the output okay ignore this so here what is the output one this is two this is four okay 4 + 2 6 only these two this is four okay 4 + 2 6 only these two this is four okay 4 + 2 6 only these two uh are set to one right so output is six here uh in the last example so here uh I have converted this decimal value to the binary value so here binary value is represented like this and here from the left I started so this bit is matching yes after that uh from here this two bits are not matching so we need to cancel out everything okay so these two bits are matching 0 so output is going to be uh zero only for this case output is going to be zero only because there is no uh bit matching for this because 0 is here after that all the bits are mismatching so I have to write like 0 and in the end output I it is going to be 0 okay so this is the case okay so how uh we are going to solve this problem so let's say uh I have two numbers uh let's say uh left let's say left is equal to 9 and uh right is equal to 13 okay right is equal 13 okay so uh left uh so these are the bits format like 30 uh 64 32 16 8 4 2 1 so this is how we are going to represent bits right so here uh 9 nine uh I can write nine like this 0 1 uh this is N9 now let's write 10 so how I'm going to write 10 so 10 can be written like this 0 1 0 and how I'm going to write 11 so 11 will be written like this uh 0 1 and how I'm going to write 12 so 12 can be written like this 0o 0 1 0 okay and 13 can be written like this 0 1 okay in this way uh I'm going to write the numbers right so this is nothing but nine this is 10 this is 11 this is 12 and this is 13 right okay so now let's perform uh and operation between all the numbers first and operation okay and operation between all the numbers so all the bits are set to zero Z only all are zero all are one okay so let's write one so these are zeros okay if any bit is zero then I have to just return zero all at zero okay I have to done zero only because anyone bit is set to zero then I have to return zero so what is the output here only this one uh this is bit is set at position 8 Okay add this number eight so output is going to be eight in this case right because all the if I perform the and operation between all the numbers between 9 and 13 then only this bit is set in the result one okay all other bits are zero okay so how we are going to solve uh this uh using our code because we don't want to write for uh find for all the bits okay for all the numbers we are not want to perform the end operation between all the numbers because in that case time limit ex error will come for the larger numbers so here what I'm going to do I'm going to just take one left okay so can I write my left like this um okay so here uh these are the numbers 64 32 16 8 4 2 1 okay and uh I can write my 9 that is my left okay left like this 0 1 0 one and my 13 I'm just going to write my left and right so right is 13 now so I can write 13 like this 0 1 okay so now what I'm going to do here I'm going to use uh one more variable called shift okay in this I'm going to count how many times are I am performing the right shift okay so here see here what I'm going to do see okay so here uh what is the value of my left in the starting it is N9 and what is the value of my 13 my right that is 13 so I am going to run one while loop and in the while loop I'm going to check whether my left is not equal to right if this is the case in while loop if my left is not equal to right then I have to perform the right shift operation okay so I have to perform the right shift operation so what I'm going to do I'm going to write shift the bits of left by one okay right Shi uh left shift the bits of left y1 and right shift the bits of right y1 okay right y one and I'm also going to make a count how many times I am performing this shift operation until I get the result as left is equal to right okay so here what I'm going to do uh I am uh performing right shift okay for the left so this is left so I'm performing right shift okay so all my bits are going to move one position right okay all my Beats are going to move one position right for both left and right okay so this is the normal case so this is going to happen so what I'm going to do I'm going to delete this last I have deleted this one so now uh my numbers becomes like this is one this is two this is 4 this is 8 this is 16 this is 32 okay so now uh I have deleted this uh last I have reset the bit okay so now what is the my left so my now my left is four my left becomes four and my right becomes 1 2 4 6 so my left and right both are not equal to uh both are not equal so in the last operation my shift becomes one right in the last operation when I removed these two bits I have moved all the bits to right okay so that's the reason now my one becomes this two becomes this four becomes this eight is this 1622 okay so now I'm going again my left and right are not equal to uh left and right are not equal to each other right so I'm again going to perform the right shift operation and now this time I'm going to remove uh this these bits okay so I have removed this two bits so now uh this becomes my one this becomes two this becomes 4 this becomes 8 and this becomes 16 okay I have perform the right shift operation so now what is the output is for my left is nothing but two okay two bits is set and for my right the uh output is uh three okay 1 2 so total three so again my left and right are not matching okay so in the last operation I have already updated the shift to two right so now again I am going to move my shifts One Step more uh right shift I'm performing the right shift on my bits okay so now my uh left and right are going to look like this so this uh so here perform the right shift okay so now all the bits are moved to the right so now what's going to happen here okay so here one second okay so it's good like this only okay so here what is the output for the left is one what is the output of right is also one right so now both left and rights are matching okay both left and rights are matching and how many times we have performed the shift this is one time this is second time this is three times total three times we have performed the right shift okay so shift I'm making the count here so when this bit we have removed performing right shifts the Performing right shift on both left and right this second time performing uh right shift on by burn on left and right so tot three times okay total three time and now we get both left and right are equal now what I'm going to do uh I have go the number shift is three okay so I'm going to just pick any of these now new left or right I can pick anyone I can pick any number left or uh right because both are same now in the now so if both are same now I am going to perform left shift I am perform going to perform left shift previously I was performing right shift now I'm going to perform left shift on left or right by how many Times by this shift times so here shift I write shift okay so my left is nothing but uh one in last case so I can write uh one like this 0 1 okay now this is 1 this is 2 this is 4 and this is 8 okay now let's perform the left shift so when I'm going to perform the left shift so my numbers are going to look like this so I have deled this so now my number becomes like this 0 1 0 again I perform the left shift so now my numbers looks like this okay 0 so this is uh shift uh one time this is shift I perform second time now shift is three so I have to perform left shift by three so now last time I'm performing the shift so number my uh looks like this so this is going to be output right this is eight this is nothing but eight okay so I hope that you guys are clear with this approach okay so now uh code is of just two three lines so let's write the code like this first int initially set the shift to zero okay then I told you that I'm going to perform uh one while loop while my left is not equal to right in that case uh I am going to uh shift the bits of left to the right by one okay so left is nothing but left is equal to Left Right shift one right is nothing but right shift one and I am also going to make uh counting the shifts that I performing the number of shifts so here and in the end just return left and perform a left shift to the how many times shift times okay so now let's run it and see so all the test cases has been passed okay so now let's submit it so our solution is accepted and beats 100% of users with Java see so this is 100% of users with Java see so this is 100% of users with Java see so this is very simple right so I hope that you guys are clear with this uh explanation right if you guys still have any doubts related to this approach then please feel free to ask in comment section okay uh there is one more approach in which we can solve this problem okay so I'm just going to write that approach so here uh we don't need to do this okay this is also best approach so you can perform this okay so run time is also very less and see here just 3 milliseconds and this is the best solution this is also one of the best solution and you can also solve this problem like this okay so here uh while my right is greater than left okay if this is the case then in that case I am going to update my right as right performing the bitwise and operation between right and right minus one okay and that's it in the end in the return I have to just write and uh the original number left okay so now let's run it I think uh there is some uh yeah see here this I should write greater than I mark question mark okay so run so all the test cases has been passed so now let's submit and see the run time for this one as well so I think it's same only let's see yeah mostly it's same no but previous approaches okay let me submit it again let's see what happen if I sub resubmit it so now it is uh giving around time 3 milliseconds and it beats 100% of users milliseconds and it beats 100% of users milliseconds and it beats 100% of users with Java sometimes this happens in lead C I don't know why so here what I'm doing so here uh let's understand this with an example only okay so this is the my code and here let's take uh again left as nine and right as 13 okay so my right is greater than left yes so after that I'm updating my right as right and right can I write okay one okay let's 16 8 4 2 1 I can write my 13 like this right 8 4 this is the way I'm I can write 13 okay now uh write uh and right minus one so right minus one let's perform right minus 1 so what is my right is nothing but 13 - 1 12 so right is nothing but 13 - 1 12 so right is nothing but 13 - 1 12 so can I write my 12 like this 0 1 0 so here what is the output so my output is 0 1 0 okay this is my output so what happens here uh I reset my rightmost bit so now my new right becomes this 12 so this is my new right is nothing but 12 okay I reset my rightmost bit okay so here my right becomes this one and my right now 12 left is 9 so 12 is greater than 9 yes it is true then again I am going to perform uh this I mean while loop only so here right this is right minus one that is 11 so I can write 11 like this 0 1 okay so now what is my output this is zero this is 0 1 0 so this is nothing but 8 okay here I again uh reset my uh rightmost bits okay again I reset the rightmost bits so now my new right becomes eight right now 8 is greater than my left no in that case I have to just return my right and left is originally what nine so nine I can write nine like this right 8 this bit so what is the total output is 0 1 0 so this is nothing but 8 only this is nothing but eight only okay eight only so this is my output right so here also I'm just trying to find the common uh bit okay and that's the case we are just only find the common bit and then returning the result between the right and left okay so I hope that you guys are clear with this approach as well and yeah I have already told you if you guys still have any doubt then please feel free to ask in comment section till then keep coding and keep practicing meet you in the next video thank you bye-bye
Bitwise AND of Numbers Range
bitwise-and-of-numbers-range
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_. **Example 1:** **Input:** left = 5, right = 7 **Output:** 4 **Example 2:** **Input:** left = 0, right = 0 **Output:** 0 **Example 3:** **Input:** left = 1, right = 2147483647 **Output:** 0 **Constraints:** * `0 <= left <= right <= 231 - 1`
null
Bit Manipulation
Medium
null
1,041
hello everyone I'm Jack today let's take a look at this new problem 10:41 we're about bounded in a circle 10:41 we're about bounded in a circle 10:41 we're about bounded in a circle well it is actually marked as easy but I took some time to figure it by myself without looking at other materials so it should be easy uh if in it playing a robot initiative stands at zero the original point and a face is north and robot can receive one of the three instructions go straight one unit L turning left with ninety degrees right to ninety degrees the robot performs instructions given an order and repeats them forever okay so return true if and only if their existence circle in playing such as the robot never leave the circle to think about is that yeah to think about this that first the instructions could be coming in some random input it's like they will just go they have a right and left so just repeatedly maybe all the instruction may be long as so 100 so they just to go randomly so and actually the most important thing is about the last point so I finally figured out that we only need to take can't take care about glassed-in once in one iteration the glassed-in once in one iteration the glassed-in once in one iteration the last point the last coordinate is the most important one say that I would draw maybe out joists later okay first things I already draw this map that's or this graph I first handle the rotation because we have two commands which is Ln R which commands the walker robot to turn left or turn right so let's take a look let's create a function called rotate its receive direction and the order is oh man I Ronny will write typescript is through typescript no okay that's right type script anyway so direction is array is an array consists er consisting the horizontal axis and the vertical axis so we wrote hit it with our or our how can we rotate them so this leads me to remembering the matrix thing rotating the matrix but I actually I forgot man I really forgot so I haven't yeah I haven't touched to make trace like for like 10 years so I will try this map so to recall - recall the try this map so to recall - recall the try this map so to recall - recall the calculation so this is the dot XY with the product of Y and this is product Orlan I don't know so anyway the so this line is an ant at one suppose it's one unit so this x y or x y and so where we rotate it with theta okay mmm is weird sorry I'm using my taught pad touch pad and so this is a new or the new coordinate eggs what is this X nu y anyway X Phi mm-hmm anyway x1 and y1 let's say X Phi mm-hmm anyway x1 and y1 let's say X Phi mm-hmm anyway x1 and y1 let's say x1 and y1 we're going to get the x1 and y1 how can we get it so we draw this new dashed line to help us understand what is going on we draw it with red so actually and okay it is outlines also it's reread oh we need to draw it with light it's weird I'm drawing a line not something there's no feel sorry wait there should be no feel what man this is really I don't know what is it I don't know what this is anyway I'll draw a line here oh okay it's working okay and we draw a line here so this is also a line withdraw so this is the 90 degrees and we can see that sorry this is a disaster and so here it's also theta and this is theta so this is seta oh this is not seta it's uh it's something not theta let's say it's hmm what is it's let's say it's alpha okay this is alpha this is it's alpha okay this is alpha and this is alpha right so now we calculate this X 1 so X 1 is actually this is X 1 so actually this is ace part - this part so actually this is ace part - this part so actually this is ace part - this part so it's actually we can see that X 1 equals this part we first calculate this part so this part means this 1 and sine alpha actually because we're at the unit of 1 its Y so we know that this 1 this length is cosine theta so it's cosine forgive my bad handwriting and multiple by Y so this is this part okay - this one is this one okay - this one is this one okay - this one is this one actually so it's sine theta Wow sorry and sine theta is this one so this one and sine alpha so it's also why hmm wait a minute something is wrong it's actually ah oh sorry I made us make this is cosine theta is this one but it has to my so this area is not x y but to the proportion of theta cosine theta so actually it should be times X my bad okay this times X let's we do the same y1 equals this part plus this words right so this part means we can do the same so the portion proportion is cosine theta actually divided by 1 so it but it's the same and we multiply it by Y so this is this part okay plus cosine of cosine alpha means X so we actually X cosine means X yeah and this one is sine theta who ship Oh times X so we got this formula of calculating the rotation it's cosine theta for 90 degrees with zero sine theta is 1 and the cosine theta is 0 sine theta is 1 so actually we got this formula returned so new order a new direction is minus y so actually for this one is a 90 degree is 4 L turning left because it's a counter clock wise and so it should be Direction 1 and Y should be sine theta so X Direction 0 but this is the case of order equals L okay if not if it's to the right we say the same only say this one is same but this one is minus 1 so okay minus 1 so it should be directions one but minus direction is zero okay we got this rotating and now we need to calculate we need to find out the pattern of after a problem so wait a minute this is the egg misses the coordinates let's say it's start here so no matter we no matter how we move we can forget about everything no matter how we move if we take a last point into consideration we say nest okay last point yeah and so the original direction is like this right okay Japan Oh change its pencil this is the original direction if the end point is here and the last direction is like this if something is like this let's say and this is last boy it means that we first move this Buddhist move from the original origin directives point and rotate it by this angle now if we want to circle it with like this kind of a circle if we in July out of the saying out of this circle you can see that if we want to surround them to make it within this circle forever we need to at least right move our angle like for night from lining degrees say if this angle is like this it cannot be kept with any circle why let's take a look again because you only move it like this angle like this let's say 70 degrees and for these cases we will still move Manny's not 90 but 60 degrees okay like this and you were just to get further and further Yuri not about it within their circle I'm not sure I'm explain it well right but it's synced to my instinct that they should be the same it should be something like this if you want to draw a circle we say we make it this movie like the half radius first move half radius and then we just move we just to take the 90 degrees as the angle and draw a line and you if we follow this role and I like to repeat it for forever it will find it leads us or a circle for circle right if you want to keep it we need to a smaller degree smaller angle if not we will make we you format like we are like a larger angle we will not draw a line we're just that you are to align like I don't know what a main but it's something like the snail a share of snail right yeah you were not yeah it's free yeah oh yeah if it's 90 degrees we say it's a circle it's not it's some one another degrees it actually will be a reversed snail shell and finally yeah merge to one point so actually we were calculating the final angle versus the start angle the end angle and the first hang start angle to see whether a new angle the degrees that we need to rotate is smaller than ninety degrees or bigger than 90 degrees one thing is that one exception is that if we if this only it's only works when we have moved to a little bit if we stay that always stays at the origin no matter what the angle is we actually we can keep it in our circle because it's always in the dock in the origin we don't need to care about anything else so we actually we had need to take the origin as a special case so okay so for the instructions we get we first we need to get the final thought final coordinates and the final direction let's direction as we are told that the initial Direction is faith as is north so it should be zero one let core power position equals zero and the four that's I equals 0 to 3 equals instructions and s 1 and I plus if instruction equals instructions I if instruction equals G then we just say remove it we move it by Z plus 0 plus 1 oh I cannot do object assign oh so zero plus equals direction 0 plus 1 plus direction what if it's not goal we need to rotate the direction so Direction equals rotate Direction rotate instruction actually I found a problem that we are returning new array which is not performing we actually don't need to keep the history the direction histories when you kept the current so I'll just say the reaction cost 10 wait a minute I'll say direction one direction equals I'm not sure with this is working its let me try in this in a console Const a equals one to a 0 a 1 equals a 1 a 0 now a and ok we can reverse it so equals this we're not creating a new by this we're not creating a new array I'm not sure this is right but maybe not okay we just forgot forget about it okay and then finally check if we are still at the origin if pulse 0 equals 0 and plus 1 equals 0 return true else check if direction changes bigger than 90 degrees so how can we check it's bigger than our degrees well this is another formula it's cosine theta cosine alpha okay of cosine theta I need I like theta equals 24 two vectors we need to calculate the theta we just get the ah we remove the graph actually I'll just memorize it so it should be a vector a B divided by a the value of a value of B this is at least why I remember maybe it's wrong maybe it's right it should be right okay we calculated the cosine and check if it's bigger than 90 degrees if it's much bigger than that agreed it should be a minus so return cosine is smarter than smaller or equal it's not yeah if it is not a positive number so a times B means direction so here we are calculating a direction e01 because this is the initial direction so a times B equals the first one is calm and to one x Direction one so Direction one actually the direction is one so hmm wait a minute I'm working in this right because mm-hmm yeah because this one is act mm-hmm yeah because this one is act mm-hmm yeah because this one is act absolutely bigger than zero so this should be easy and we're down we run the code there's a title here it's true yeah let's submit it ooh wrong answer we got g/l it's means y wrong answer we got g/l it's means y wrong answer we got g/l it's means y let's check if direction thing police gl yeah ah my bad should be or equals that equal to zero wrong answer I like debugging into console.log I like debugging into console.log I like debugging into console.log direction okay finally right fire direction so ll okay it's down and then move one a ride and L so actually the final direction is not oh there's a problem we made a way we have a problem we lock the rotation mm okay the first we right laughs oh it's right and then down right and then we are moving right so it should be oh we made me see here so actually ah ha my bad oh my bad so quit again accepted yay we got faster than 85% of the submission not bad than 85% of the submission not bad than 85% of the submission not bad it's to take a look at the other solutions wow they are really fast rotation zero bubble of instructions with G Chris what Big Poppa mm-hmm we turn 0 or uh-huh we turn 0 or uh-huh we turn 0 or uh-huh so you're actually we're doing the same but it seems as we are losing some time with by calling function if we in Ronnie's function any help okay if instruction L or just to say because this else ate like this we can remove this rotate submit something weird happened doesn't hmm sorry man Network seems down no the service down oh okay I don't know actually this does not this seems know not helping anyway we are not doing that mad I'll stop today hope this video helps you a little and the see you next time we're working on this one flowering planting with no adjacent ok have a good night bye Oh peace is not working what
Robot Bounded In Circle
available-captures-for-rook
On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that: * The **north direction** is the positive direction of the y-axis. * The **south direction** is the negative direction of the y-axis. * The **east direction** is the positive direction of the x-axis. * The **west direction** is the negative direction of the x-axis. The robot can receive one of three instructions: * `"G "`: go straight 1 unit. * `"L "`: turn 90 degrees to the left (i.e., anti-clockwise direction). * `"R "`: turn 90 degrees to the right (i.e., clockwise direction). The robot performs the `instructions` given in order, and repeats them forever. Return `true` if and only if there exists a circle in the plane such that the robot never leaves the circle. **Example 1:** **Input:** instructions = "GGLLGG " **Output:** true **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "G ": move one step. Position: (0, 2). Direction: North. "L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West. "L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South. "G ": move one step. Position: (0, 1). Direction: South. "G ": move one step. Position: (0, 0). Direction: South. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0). Based on that, we return true. **Example 2:** **Input:** instructions = "GG " **Output:** false **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "G ": move one step. Position: (0, 2). Direction: North. Repeating the instructions, keeps advancing in the north direction and does not go into cycles. Based on that, we return false. **Example 3:** **Input:** instructions = "GL " **Output:** true **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "L ": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West. "G ": move one step. Position: (-1, 1). Direction: West. "L ": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South. "G ": move one step. Position: (-1, 0). Direction: South. "L ": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East. "G ": move one step. Position: (0, 0). Direction: East. "L ": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0). Based on that, we return true. **Constraints:** * `1 <= instructions.length <= 100` * `instructions[i]` is `'G'`, `'L'` or, `'R'`.
null
Array,Matrix,Simulation
Easy
null
138
hey everybody this is Larry this is day five of the leg go Del challenge H the like button the Subscribe but Jo me on Discord let me know what you think about today's PR 138 copy list with random pointer let's check real quick ah check real quick because I uh on the upper left there's an unbox surprise you click on it you get 10 lead coins guess it adds up over time I don't know anyway uh all I think we done this problem not that long ago uh also first of all whoever's having a great Labor Day or had a great Labor Day and I did a very long hike uh without sleeping enough so I'm just like kind of drained to be honest but I did take a quick nap on the bus so maybe that's good enough was how that goes okay so link list is of length and I feel like we did this prom recently like maybe not super recently but still like recently enough that probably my previous video is not that bad uh so if you don't like this video you could definitely look at look up that one um yeah I mean the way that I like to solve this is kind of with just like a getter um yeah with a getter and then with that getter you can almost like a memorized version of the together that doesn't have the random or without the next order random but and you could hash it on actually the node that they give you so uh so let's do that maybe the one I'm thinking of is a tree or something I don't know uh yeah oops cannot type today so while current is not none current is zero current. next so this is just writing the iterator wish there's a cener way to write this I feel like I mean I think maybe you have to write like some kind of H next for the no Cass or something I don't know that much by F so who knows but in any case so then now we um maybe one you know new current is equal to none oh actually we don't really new curent we what we want is new head right yeah so this is the thing that we're going to return is youal to let make get brighter I don't know why it's so dim on my laptop uh let's just say get uh node of curent or just the head right and we could just write a get node class here um that would kind of take care basically what we want to do is do two things right or uh one is kind of construct the memory for we want to construct a memory uh a copy of the memory oh what am I saying sorry friends you want to construct the memory you want to man I'm finding tough to find the words basically you're trying to allocate the memory for a copy for each of the um the existing notes and then the second is to actually have pointers to them right and actually like set the pointers up to a good way and this is the way that I feel like I've been doing it for a little bit so uh so yeah so basically get Noe copy get a copy of the note and basically we can um we can say return uh a new node of or maybe like um you know copy is equal to new node with only the x or the value uh mattering so no that value and then we could avoid the other pointers for now and then we return copy right and how do we assure that uh sub um subsequence what am I doing a subsequent um C to node of the same node how do we re sure that we return the same pointer well we just a memorization or just like a lookup really right so here is a if node is in lookup then we return look up of node otherwise and look up of node is equal to copy and I've gotten question about why this works in the past and the reason is because what happens is if um by default no the idea of node get is the hash thing so um for an object which means that um the memory address not quite what IDE is but it's a good approximation if you know what that means is that the memory address of the object gets hashed and because actually in this case this is actually what we want because we uh um because we want because the memory of the original node doesn't change right so yeah so basically that's basically the idea and then yeah so now we can just write uh right new head yeah and then maybe current is equal to new head right or not I reused this but uh current or new current maybe oops and that new current. next is equal to uh get node copy of current. next H maybe I'll write this a little bit differently I feel the way that I wrote this is a little bit awkward that's why because the way that I like it is actually with a sentino and I skipped using a sentino this one because I thought it would be I don't know I was just lazy to be frank um but it seems clear to me that actually made it a little bit um yeah unfortunate so here let's instead of doing this new head is equal some node right and new current is equal to new head and then here so we want actually new current is equal to so this makes it a little bit harder to or a little bit confusing but let just say sent no is equal to node and then we sent to node to the next uh maybe just negative one and then the next will point to head and then current is equal new Sentinel right then now we can do stuff from all the next so um yeah new current. next is equal to this new current do I think random but then it's it should be none in the first case so uh yeah maybe we just write something like if node is none we return none just to keep it consistent uh yeah random is that Noe copy current. random and that's pretty much all we have to do oh and well new current is equal to new. next and then we just we new head. next I think I have to do a negative one here because we need a Valu as a requirement Maybe oh yeah so that looks good let's give a quick submit and we're Gucci oh only three times H if FS a little a bit more um yeah this is linear time linear space uh everything is over of one right uh except for the W Loop which obviously we have to do any because we have to look at every copy once uh yeah the core idea is to separate the allocating the allocation of memory and the getting or the setting the pointers um yeah and this thing only allocates memory the first time you see a note no matter whether is from the next or the random so um so then the next time you get it you just look uh it goes back to the same um memory allocation so yeah um that's all I have for this one let me know what you think yeah stay good stay healthy to good mental health I'll see you the rest of the week um bye-bye
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
7
Hello Everyone, our question today is Reverse Integer, it is a very easy question, like first of all we understand what is given to us in it and what we have to do, so first of all we feel from its name that whatever we have to do. We must have given an integer and we have to reverse it. Now inside this we have to reverse the question and what is the constraint given and what have we to do. We have been given a 32 bit integer x in the input and we have to reverse its digits. Okay and if But if the value of x we ​​are getting goes x we ​​are getting goes out of this range then we have to return zero otherwise we have to return its reverse. Keep in mind that as we have given 123, its input should be 321. After that, if we have given -123, then it should be - 321. given -123, then it should be - 321. given -123, then it should be - 321. Okay, we have to keep this in mind. Okay, so now first of all let us see how we will solve it like 1 2 So here we take the example of 1 2 3 and let's see how we will solve the question. Okay, so first of all, here we write 1 2 3 1 2 and three. Okay, we have this first digit. Using the first example, we You will understand that now we have 1 2 3, after that we have to reverse it, so how can we reverse it mathematically, we can reverse it in such a way that we declare a new integer variable, right, we name it, the answer is correct, A. Now we have to do something like this, first of all we put its last element here, then its second element, second last element and then the first element, meaning if there are three elements, then it means start from the reverse, we start from the back, we move like this here. Move from here and we keep adding such elements in it. Right, this is what we want. Now how can we find out the last digit of any big number. If we remember it with 10, then we can find out that means 123. If we divide by 10, what will be its reminder? 3 right means 123. If we divide any number, any digit, any whole number, by 10, then the reminder that remains is our last digit, exactly the last digit. Okay, so we can do this thing, now that we see it here, okay, now we can do this thing inside this that how do we find the last digit? First of all, we will define the help integer. What will we store in help integer every time whatever is ours like y we have been given So that is the module operator, so what this operator does is that it brings out a reminder, like when we divide x by 10, what reminder will come, then this module operator means 10 on Meaning, whatever reminder needs to be saved, by dividing this number by this number, whatever reminder needs to be saved will be stored in our help. Okay, now by doing this, we can do this, now we have taken three here, now we are in help. So what we did is we stored here inside the answer, first of all we put the value 3 inside the answer, okay, after that what we did is we changed If we want to find out, then we can do this so that the last element of 12.3 will come but if We 12.3 will come but if We need to write 'P' instead of next element, so now need to write 'P' instead of next element, so now need to write 'P' instead of next element, so now what will we do with it, we will apply it again with something like this, we will store it in help, x will be 10, which will be 2, then we will add 't' x will be 10, which will be 2, then we will add 't' x will be 10, which will be 2, then we will add 't' at this position of answer, now we will answer How to add in this position, we can do this like we have the answer, the value of the answer is now, so if we do 3 * 10, then here it will become 30 on the we do 3 * 10, then here it will become 30 on the we do 3 * 10, then here it will become 30 on the right and 30 and whatever digit we have got in it. If we do plus then it means two, then it will become 32, so we can do this that first of all we took out its percentage reminder, that is, we took out the last element, it is okay to take out the reminder, then after that we added it in the answer, how will we add it in the answer? We will add through the formula, now we will do that, we will do the answer equals to answer in 10 plus help, it is okay, answer * 10 plus is okay, answer * 10 plus is okay, answer * 10 plus help, this will become our formula, okay, so now we have used it once. Let's try to write the code. I explained all this to you. Now let's code it. Okay, now how will we code it? First of all, we will define a variable here named answer which will store all our elements. We have defined a long integer named answer which is currently storing zero right and we have to keep moving wk in it until the value of x becomes zero, then while this x is not equal to zero, it becomes sorry. Yes, x is not 0. Right, this loop will continue till x is not 0. As soon as After this, we wrote here answer equal to answer * 10 plus wrote here answer equal to answer * 10 plus wrote here answer equal to answer * 10 plus help, we are doing the same formula which we had derived here, why did we write answer * 10 answer * 10 we are doing the same formula which we had derived here, why did we write answer * 10 answer * 10 we are doing the same formula which we had derived here, why did we write answer * 10 answer * 10 so that the number we add on this space is here. Now when we have 32 in our answer, then we will do 32 * 10, it will become 320 and do 32 * 10, it will become 320 and do 32 * 10, it will become 320 and what will be in the last help, our one will become 321, then that is why it will be reversed, then like this, now we have answer equal to answer. Well, 10 plus helped, okay, what did we do after this, we made x = x divided by 10, we divided If x = x divided by 10, we divided If we put it, then we want the next element from it, so we changed x to 10. Okay, so x = to 10. Okay, so x = If we do reverse If it goes out of this range then it means it goes out of this range then we have to return zero so before we calculate this we have to check that if then our answer * 10 is greater than our answer * 10 is greater than our answer * 10 is greater than int and max meaning From the maximum value of int or it is smaller or the answer which is ours is * 10, or the answer which is ours is * 10, or the answer which is ours is * 10, our answer is smaller because the number can also be negative, so if we make the negative number * 10, then make the negative number * 10, then make the negative number * 10, then it will be a bigger number in the negative, otherwise it will be less than the minimum. If the answer is * less than the minimum. If the answer is * less than the minimum. If the answer is * 10 minimum is int min means whatever is the minimum value in int jr then what we have to return is we know sorry what we have to return in this is return zero ok now let us run it once and check this run Once done, let's submit. Thank you everyone. I hope you all have understood this question and answer it easily.
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
1,913
Hi friends welcome back to another video and in this we will see the maximum product difference between two pairs so this is an easy level problem so let us understand directly from the example and then if we do it then basically we have to select four numbers or you can say two pairs. Suppose the first pair is of A &amp; B and the second pair of lettuce is of A &amp; B and the second pair of lettuce is of A &amp; B and the second pair of lettuce is of C &amp; D. Right then we have to select some numbers that is of C &amp; D. Right then we have to select some numbers that is of C &amp; D. Right then we have to select some numbers that multiply A &amp; B and multiply A &amp; B and multiply A &amp; B and also multiply C &amp; D also multiply C &amp; D also multiply C &amp; D and take their difference. Right then this Should be maximum, so as you can understand that brother, if this difference is to be maximum then a should be the biggest, a right, this pair should be the biggest and this should be small, right, for this pair to be big, a and b should be big and And for this pair to be small, c and d should be small, so basically select two big numbers from the array given to us, first largest or second largest, then a could be first largest and b could be second largest, right similarly. C First Smollet say, right and D also assume Second Smollet Right, what is the easiest way, you sort it, you suggest, suppose I sort this array, then two will come first. Four then four then five then 7 8 9 let's count how many 0 1 2 3 4 5 6 There are seven elements 0 1 2 3 4 5 6 Okay so we have covered all the elements so two and four can be minimum and 8 and nine can be maximum then first largest if we consider a then a will be 9 b will be 8 c will be 2 and d will be 4 now if we multiply it then 88 9 what will be 72 my 8 then it will be 64 So you can also see the output here, what is coming 64 So simply what we can do is we can sort the data and after sorting we will pick the first second element, obviously we are sorting in ascending order and the last two We will pick which will be big numbers, right, as long as we can solve the complex of n, right, it will be a little cent, it will be a little fast, it will be a little comparative slow, first let's try this slow method, then we will move to the I have come to the Faster Way coding screen, so you can do it in any of your favorite languages, I am doing it in Java, right, for Java, the data is sorted with array dot sort and in this I have passed the names, now we have two big If I want to select a number then first I take its length n = numbers dat length I take the length as I take its length n = numbers dat length I take the length as I take its length n = numbers dat length I take the length as minus so that we can represent the last index by this, okay now I select the last element which will be the largest then I write numbers n Okay, this is the last element, for the second last, I write numbers n - 1, then for the second last, I write numbers n - 1, then for the second last, I write numbers n - 1, then I write here, then numbers 0 which will be the first element and numbers one which will be the second element, we can just return this, here we write return. I think we have sorted, if we run it and see, sample test cases are getting accepted, if friends submit, then great, we got the gold coin, so we can see, it is beating people at 75, okay, this is the top 5. But why is it not coming in because it can be the same region. We try to complicate log of n into n, so first let's discuss a little about how we can approach the concept. Let's make four boxes basically. First large one, second large two, third small one and fourth small to right and put zero in it because here it is given that the number will be at least one and if it is bigger than that then I am considering zero as the largest and there is no big value integer in it. I will take the largest value of jar as smollet, so now I write 99 here but in the code I will take the max value of integer jar. Ok and start traversing from here. Suppose we will take a variable named nam in which one If we keep entering these numbers, then what will come on the first case, four, so we are assuming that large one will be the biggest, large two can be smaller than large one or it can be equal, right? If we are given two numbers like in this case 4 If two repeated numbers are on the right, it means there can be repeated numbers, so here we will give a condition, if the number coming is bigger or equal to large one, instead of large one, we are writing l1, then we write l1 only, then l1. If it is bigger than l1 then what will we do? Will we first put the data from l1 in l2 because it is possible that brother we have got the big data but now the a is no longer the first largest but has become the second largest right so we will put the data of A1 in A2. We will copy it and in AV we will copy the new largest one, okay if it does not come then we will check whether the data is bigger than A2, if not bigger than L2 then our rights are of no use because we are looking for large data. So if it is bigger than l2 then we will write l2 equal to nam then this is the first condition for largest. Similarly we write for smollet also if nam is smaller than equal to s1 then what will we do with the data of s1 in s2. And we will keep the new data coming in s1 right, but it may happen that it is not smaller than s1 but it is smaller than s2, then we check that nam is &lt; s2, smaller than s2, then we check that nam is &lt; s2, smaller than s2, then we check that nam is &lt; s2, then we do s2 = nam, then we do s2 = nam, then we do s2 = nam, then traverse it. Now let's see that four is bigger than l1, right because 4 is always bigger than 0, so what will we do, keep the data of l1 in l2 and replace four here, then the same will work for s1 also, then four will be smaller than the bigger number. That's right, if we keep its data here then 99 basically here too will be 99 and what will happen after cutting it will become four then it will go to the next number 2 Is 2 greater than l1 No no we already have four in l1 then this Please check whether 2 is bigger than l2, yes because l2 is still a row, brother, 2 is bigger, so 2 is written here, then we will do the same thing for s1, then is 2 smaller than s1, yes is smaller than s1, so first. We will keep the value of four here, we will keep it in s2, four will be here and what will happen here is two, then five will move to the next, five will check whether it is greater than l1, yes then what will we do, we will first keep this value of fur in l2 and copy 5 here. Will do this then this will be compared for s1 then if 5 is less than s1 then s1 has 2 and five so it is not small then false then check whether s2 is less than s2 or not smaller than s2 because s2 has four and five So if the number is bigger then it will move forward then we will get nine then nine we will check from l1 so whether 9 is greater than l1 yes then first we will keep the data of l1 in l2 and will keep it here five and will keep it here then It will be compared with s1 and s2, it is not smaller than both, nothing will happen, then we will move ahead, if sen comes, is sen bigger than l1, no, is it bigger than l2, yes then what will we keep in l2, sen, then you can see that till If you assume seven then the array ends here, then we have the largest in l1 and the second largest in l2. Right, from here the concept we are using is also being verified that yes, brother is getting it right. Let's move again four and 4 is neither bigger than l1 nor bigger than l2 nor is it smaller than s1 than s2 so this is also useless. If we move ahead then 8 is bigger than l1 no bigger than l2 If yes then what will come in l2 8 So if here we do l1 * l2 - s1 * s2 l1 is we do l1 * l2 - s1 * s2 l1 is we do l1 * l2 - s1 * s2 l1 is 9 l2 is 8 minus s1 is 2 s2 is 4 ya aga 72 ya aaya 8 subcut gate 64 answer right so this Following the concept, let us remove all the codes and then write I NT large equal to 0 then take small one equal to integer dot max as we had discussed we had kept 199 in our For understanding and but here we will take the largest value of integer and write here integer dot max value now one by one we will take out the numbers from nam so this is a very nice loop we have extended loop in java we will write nam calculus nums This is similar to the for loop but we do not need to take I. One data will be taken out from the numbers and will be kept in the number and here we will check if the number is bigger or equal to that of the large one. So what did we do earlier, the data of the large one is transferred to the large two. If we put it in , of the large one. So what did we do earlier, the data of the large one is transferred to the large two. If we put it in , of the large one. So what did we do earlier, the data of the large one is transferred to the large two. If we put it in , then we will write large two equal to large one and now we will replace the data of large one with the new number. If it is not so, then we will check whether nam is bigger than large two. If so, then only replace large two. You will replace large to ba similarly we will do it for small but we will not use greater than sign there, we will use less equal to av, if it is like this then we will replace the data of A2 with av and then av will be updated with the new one. Similarly to the number, if it is not smaller than A1, we will check if you are smaller than A2, if so, then at is equal to nam and after doing all the traversing, we will do large one into large, the spelling of large is wrong, let's correct large one. In large to mine s1 in s2 so I think we are sorted now let's run and see I have made a spelling mistake on line number 10 here write large let's run so sample test cases are getting accepted submit so you can see this time Friends, our percentage is better, isn't it? We are in the top 3, so this is the better solution, so that's it for this video. Friends, thank you so much for watching. See you in the next video.
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
141
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you have 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 linked list cycle um i have already created a prop uh a video on linkedlist cycle 2. so i will highly recommend just watch that video first because this problem is same absolutely same as this problem just there will be a small score change so just come back and let's just watch this video first link will be in the description and it will also come in the i button so just watch that video and then uh you can start watching uh like from this uh this video right so i hope you have watched that video so let's see in this problem what you need to do is you have to you are given a link list and you need to check whether linked list has a cycle or not so you have to just return true if there is a cycle you have to return true and if there is no cycle then you need to return false cycle means a loop in the linked list so here this is a loop right this is a cycle that's a loop in this linked list cycle 2 we have to return the head of the cycle so it was confirmed that they have given that we have to if there is no cycle we have to return null but if there is a cycle we need to return the node where the cycle begins so here the cycle is beginning from 2 node 2 0 minus 4 and then again it comes to 2 so 2 is the starting of the cycle here we have to in this linkedly cycle 2 we have to return the head or you can say return the starting node of the cycle but here just in this linked list cycle problem you just need to check whether there is a cycle or not that simple so see this linked list is given right this linked list is given it's connected like this and minus 4 is connected to 2. so uh in this code uh the previous code which we had we will just make few changes uh what we are doing earlier was that in the previous code uh if you have seen this video you will understand what i am trying to say here that earlier in linked list cycle 2 we were when slow was equal to fast so this means that when slow is equal to fast means there is a cycle so it's confirmed that when slow is becoming equal to fast it means there is a cycle there is a loop in the linked list so then you will just simply return true because we found a cycle and we will return true when slow is equal to first but if after finishing this loop still the slow is not equal to fast it means there is no cycle so you may return false at the end that simple this problem was so you will be able to understand if you have watched the previous video this linked list cycle 2 video you can submit it java solution and python solution link will be in the description let's quickly dry iron also so that you it's absolutely clear so we are taking slow and we are taking fast right we have taken two pointers head of the linked list is given to us head is pointing to three head of the linked list initially what we are doing we have taken slow pointer and fast pointer and initializing both them both of them with head that is slow is also at head and fast is also at head fine now what we do right we do we move slow by one position and fast by two positions fine so slow will come here and fast will go to one two here then slow will move one position and fast will go one two so it will go from zero to minus four and then from minus four it will go to two so fast will come at here now slow will go again forward and fast will move to this here so here see slow and fast are becoming equal right so when slow and fast becomes equal means there will be a loop right there will be a loop so uh it's this will events low and fast are equal so there is a loop and hence what we can do when slow and fast equal becomes equal we can just simply return true so i hope you understood this problem let me know in the comments if you have any doubt uh and if you like the video please like it subscribe to my channel and i'll see you in the next video thank you
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
113
foreign daily problem part sum so in this question what the question is asking is we are given a buying treatment right we are given the binary tree and in that binary tree we have to find the path from root to the leaf node so we have to find the path from the root to the leaf node whose node values which sum up to the Target sum so for example in this binary tree we have the binary tree now we have to find the parts that will whose node values will sum up to 32 so in this tree we can say that 5 4 11 2. okay five for eleven two they sum up to 22 then 5 8 4 5. they sum up to 22. so in the answers we will have this to the vector which will have the arrays which are which is nothing but the path from root to the link log Okay so you might now be guessing that what can be the approach how can we solve this question so given a binary tree now listening hearing this name binary tree we can say that we have to iterate to its nodes right and to iterate a tree we have two things either we can do DFS or we can do BFS so in BFS we go through the depths and in VFS we go through the breads right and now in the question it is directly saying that we have to find a part from the root to the leaf node so it's pretty much clear that we have to use DFS so our first thing is clear we will use DFS now to solve any DFS question like we generally use recursion okay so for recursion what is the first thing we need a base case right so what can be a base case in this binary tree a base skills can be if this node is none so we can't perform any operation on the null node so we'll just a base case will be nothing but if the root is null we will simply return okay we'll perform not a no operation now what's next thing also in DFS first thing first we will go through the left side then we will go through the right chart so first thing is the base case if root equals to null then we will return and secondly if we have root left then we will go to the left child so let's say our function is solved okay and we will go to root and then after traversing the left side will go to the right side if root write exist will solve the root now what is that so our solve function whatever it is called function is pretty much uh structure is done what you have to do we just have to fill in the blanks right no let's come back to our question let's dive deep into what the question is asking so I'll just erase this part for now okay so let's take a deep dive into our problem segment so a problem statement is saying that from traversing from 5 to 4 to 11 to 7 we have to keep count of whether this sum from root 2 to leave float whether we are getting the sum 22 whatever our Target service whether we are getting the targets or not so let's say for five let's say we don't have this uh tree we just have five so is a so first thing we can say is if we have only five then we'll check is it the child node so it is a root note as well as childhood because it is a root note so we will check is it a leaf node so we will uh so Phi is basically write down it is the root note also and it is a child node also next what we have to the left of four to the left of 5 we have 4 and to the right we have or let's say we'll just perform both whatever is a BFS so what we have so to the left of five we have four now the left of 11 to the left of 4 we have 11. and to the left of a level we will have seven I guess this will work the same way like the DFS will go from here then here and then it will go back to 11. and then to two from two it will go back to 11 10 to 5 into 8 13 8 4 5 4 1 then again back to four again back to eight again back to five and then we will return whatever is our answer now what I can say is if at point five is 5 a leaf node so no it's not a leaf node okay we will go to its child so seven is a leaf node now what we need next we need that is the sum of all these nodes equal to 22. so what for seven what can I have is if I somehow managed to get whatever my previous sum is whatever the previous up so the previous summon the fighters 4 plus 11 it will be paid now for seven if I somehow manage to get the previous sum baby and then I'll add this Roots value and sorry I'll add this notes value so 20 plus 7 will get 80. so is it equals to A Target sum no it's not equal so we will simply return back to 11. okay now at 11 we have a right child so the right child is 22. okay not also for two what will be the previous sum will be 20 take some of 5 4 11 20. n also previous sum plus this notes value 2 H equals to 20. right net 22 is equal to our Target sum so what I can do is I will have to add this to some array or to some vector or list that will have all the previous notes as well so apart from previous I can also have a temporary array let's say temporary array okay and then this temporary array I will push back to is this clear so for each node we will maintain a previous whatever the previous sum of its sisters are there and also for every node we will have a temporary array and we will push back whatever the notes value is there in that temporary activity now we need this temporary array so add to the temporary array will become 5 4 11. now this temporary array is part of a answer array so let's say the answer added okay and in this answer array we will do nothing but we will push the temporary array so we will push back the temporary we will push like the February I think this solution is pretty much clear so let's go on for the food uh okay so uh this is a code whatever code is written so having this is a prewritten uh a function that was given in the lead code so what I'm doing is this is our answer to the array and then this is a temporary answer that I told you about this is a previous and then we'll pass all these variables in the solve function now in the soil function what I am doing is okay the BCA status the root equals to null then I'll return it simply and then also okay so if a node is the leaf node ah so we'll just check if root left equals equal should now and root light right acoustic personal and also Roots Value Plus the previous value equals to temperature then in the temporary answer will push back the roots value whatever the roots value is there and that temporary answer we can push back in the answer also we have this T temporary answer dot pop back why is it so that is because 2 if I have inserted 2 in the temporary answer then what will happen in the DFS traversal 2 will go to 11. and now Act 11 we don't have any two because when we are coming back from 2 to 11 we won't consider 7 and 2 we'll just consider 5 for 11 and then from 11 we'll go back to 4 okay so like I'll just explain you the quote so what happens that if we have the root to a leaf node and the root value tells the previous some equals to Temporary sum then we'll push back a temporary answer in the answer else what we are going to do is uh in the previous we will update the previous every time with the roots value okay then in the temporary answer we'll push back the root value and this is just for and on debugging now what uh this is a DFS code like if root left exists and will solve for left part l so uh then we'll solve for the right part and once I come back from the right child what I'll do I'll decrement the previous from the uh I'll decrement the root value from the previous and also I'll pop back I'll remove that element from the temporary answer and so I'll just run this code yes so it the sample test case is accepted also our solution is also accepted thank you
Path Sum II
path-sum-ii
Given the `root` of a binary tree and an integer `targetSum`, return _all **root-to-leaf** paths where the sum of the node values in the path equals_ `targetSum`_. Each path should be returned as a list of the node **values**, not node references_. A **root-to-leaf** path is a path starting from the root and ending at any leaf node. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22 **Output:** \[\[5,4,11,2\],\[5,8,4,5\]\] **Explanation:** There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 **Example 2:** **Input:** root = \[1,2,3\], targetSum = 5 **Output:** \[\] **Example 3:** **Input:** root = \[1,2\], targetSum = 0 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-1000 <= Node.val <= 1000` * `-1000 <= targetSum <= 1000`
null
Backtracking,Tree,Depth-First Search,Binary Tree
Medium
112,257,437,666,2217
110
what is up youtube today we are going to be going over by balanced binary tree it's an easy problem on the code i know i said i wasn't going to do easy but um this one can be kind of tricky um because you're using recursion i know a lot of people don't find recursion easily and i'm definitely not the best with trees so i've been doing a lot of cheap problems anyways i created a slack channel where we i post these problems and a lot of us discuss them and just talk about fang stuff or interview type stuff i remember recommend you guys join the description or the link is in the description below lastly subscribe to my channel um if you guys haven't checked me out already check me out i'm posting videos every week while i prepare for interviews and you guys get to see my journey and now let's get to it all right so balanced binary tree it's exactly what it sounds like um we just have to see if it's balanced we don't have to balance it so that's easier than if we had to balance it which i'm sure is another problem but anyways for this problem um a bi a balanced binary tree is a binary tree in which the left and right sub trees of every node different height by no more than one so the height here is uh just um from nine to three it's one or yeah and um so the max is two so two and one are not greater than uh the difference isn't greater than two so here we have the height is three nodes up um the max is three nodes up and the min is uh one node so um that's greater than three minus one is two so that's greater than or it's not less than two it's greater than one that's what it is so that one's false so i drew that on my whiteboard um i'm this so this is a recursive problem most um tree problems are recursive so i'm kind of gonna like go over in the whiteboard while i explain it um so the first thing let's do is create a height function where we return the height so we're going to pass in the node this is where we calculate the height obviously so i'm just going to write return height for the end and up here so this is our main function let's have our base case if the root is null that just means we have an empty tree so yes it's balanced and my video is getting in the way i need to move it up actually there we go okay so um now we just need to return our cursive function so um when we're doing the height we got to do absolute value because we're going to we don't know which um sub tree is going to be higher so when we subtract them to get the difference we got to make sure it's a positive number because we're comparing it to two so that's why we use absolute so let's do height of root.left so this is the of root.left so this is the of root.left so this is the left subtree minus height root dot right and that's almost off the screen and let's do less than two okay cool so let's write this function now so if root equals null we're going to say it has a height of negative one um if it were just one it'd have a height of zero so um when it's null it's negative one um oh well we got to return negative one and so now let's um you think what do we have to do oh in type we gotta calculate the height sorry i felt something on my watch um so in tight is going to be um the max of so we're calculating the max because we want to subtract the two maxes um and because we're going to recursively go through the whole thing this will make sense i'm going to debug it and everything we're already at three minutes okay so max height of root.left of root.left of root.left and height of root.right and height of root.right and height of root.right okay so what is this doing this is basically saying um so we're going to call this function so we're going to go root.left height so we're going to go root.left height so we're going to go root.left height root out left so we're going to go here and we're in the height so root is not null so then we're going to calculate the height it's going to be the math.max of root.left well that's the math.max of root.left well that's the math.max of root.left well that's the first one we call so it's going to go to the i'm going to start circling so it's going to go to 3 because we just called root.left and now it's going to call root.left and now it's going to call root.left and now it's going to call height again roots still not null in tight we actually so something i forgot is we're never going to get the right answer if we don't add a one um because uh i mean it's never gonna return a number if we don't um add one to it um so this is going to if it's null it has negative one but if there's zero it'll just make sense so we're at three it's called height and then we do meth.max of height root.left so we're at meth.max of height root.left so we're at meth.max of height root.left so we're at um four so what is this going to return um it's also going to call root.left um it's also going to call root.left um it's also going to call root.left again and the root is finally null so it's on the stack it's going to return negative one but now it's going to kick out at four um the height of root.right out at four um the height of root.right out at four um the height of root.right at four so let's write out four is negative one as well um so it's going to kick out now we're at three on the stack i should have created a stack so i'm gonna this is terrible i'm sorry i guess recursion is so hard to um like visualize draw out in my opinion so now we're going to be at three so now i'm going like backwards upside down um and so the root dot left um well the root dot left is uh we're not four we got zero so we're adding one so four is zero so now we have um the root dot left is zero and the right is going to be the same thing it's going to be zero um so though now we're going to add one to that so what i'm trying to say is these return to zero as their height obviously because negative one plus one and um so this is going to the up sorry guys and the height of the root.left and the height of the root.left and the height of the root.left and root.right of three root.right of three root.right of three is these two which we already solved recursively in the stack and now we're just adding one to it so it's gonna be one flakka cut it out i'm gonna change the color and then we just go all the way up so two so we have two and uh we already found this one so it's one and um then we got a call height root that right so and then this height dot root.right height dot root.right height dot root.right gonna recursively call find that it's negative one so this is a height of zero is going to have a height of 0 so we're doing the max so it's 1 plus 1 is 2 and that's how it works so yeah that's how it's going to work the thing with this is it only checks the um it's the this call only checks the max um so in this case it's actually going to return false it's going to do this right one as well over here hopefully that made sense recursion is kind of tricky so let's run this do you guys think this is going to work let's find out so it's actually not going to work um well that's not why it's not going to work i wanted to see if you guys would maybe like catch something okay well that one did um but if i submit it that test case worked it's not gonna work um the reason this worked is because this just returns false but we need to check the other sub trees um so we only checked the max of the root we need to check the max of all of these because these this could be um this could go like this and uh i mean you just have to like be able to check every subtree and we're not checking every sub tree we just checked from the root so now we need to go check this subtree and this subtree i should erase the old ones so how do we do that um we just add more recursion so um let's do exactly that so we're gonna have our and so everything has to return true now and we're just going to do is balanced root dot left and obviously we have to do the same thing for um roots out right so now there's like tons of recursion occurring um because it's balanced is calling itself and inside in is balanced we're calling height and inside height we're calling height over and over it's just like tons of recursion it's checking everything um i don't want to go through like the whole recursive stack because it's just so much but hopefully you guys understand the concept um if you do a few of these problems i really think like a few tree problems you use recursion in all of them so i think you guys can understand it i hope this explanation helps so it's just um i believe it's o of n for um complexity and of h for um or did that running time of n for running time and of h for uh space complexity no it's not o of h oh because of in case it's unbalanced that's why so it's o of n actually so yeah that makes sense it's only o h if it's um balanced which in this case we're checking if it's balanced anyways i'm you know i'm rambling i hope you guys found this video helpful um if you haven't already subscribe check out my channel hit that like button if you guys have any questions let me know i love responding to your questions and i'll see you in the next video
Balanced Binary Tree
balanced-binary-tree
Given a binary tree, determine if it is **height-balanced**. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,3,3,null,null,4,4\] **Output:** false **Example 3:** **Input:** root = \[\] **Output:** true **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-104 <= Node.val <= 104`
null
Tree,Depth-First Search,Binary Tree
Easy
104
974
um hello so today we are going to do this problem which is part of Fleet code daily challenge January Dairy challenge um Subaru is some divisible by K so we get basically an array and we get um an integer K and we want to return the number of non-empty sub to return the number of non-empty sub to return the number of non-empty sub arrays that have a sum that is divisible by k um and sub arrays of course just a condition a contiguous portion of the array so if we take a look at this example with k equal to 5 the entire array itself is the sum of it is divisible by k um because we have 5 here and then we have 10 here so it's 15 is divisible by 5. here five alone with just this subarray is divisible by um five and then also this entire one with five and zero is divisible by five because the sum is five um also here is divisible by five because the sum is um five uh minus five right so overall zero and zero is divisible by five right um and same thing with this one is -5 which is divisible by five this is -5 which is divisible by five this is -5 which is divisible by five this one is minus five also divisible by five right so that's the idea and the goal is just to return the total count okay um and you can see here the length of the array can be 10 to the power of four so this tells us that um basically an oven squared algorithm would not work um because then it would be 10 to the power of 4 by 10 to the power of 4 and that's that will always get time limit exceeded only it could um but if it wasn't um if it was possible to do it in oven squared then we can just try every possible sub array right but that's not possible with this constraint here um so let's see how we can solve it um so first to solve this problem I think um one concept that is good to understand is prefix sum and actually this comes up a lot when you have any problems that have the notion of finding the number of sub-arrays that equal some the number of sub-arrays that equal some the number of sub-arrays that equal some sum or divisible by sum or whatever anything related to um to Counting sub arrays that have certain some property right often the prefix sum helps right but first I want to explain how it helps and first I want to explain the concept of prefix sum itself so I have an array here um right this is my array and I have the prefix sums computed here the prefix sum is just basically for each element you take the previous prefix sum from the previous index and you add the element so here before we had zero so the prefix sum is just three for five the previous prefix sum three plus five that's eight and this represents basically just the sum of the of this sub array right and then we for we add one and so nine and so this value here represents the uh sorry actually this value here represents the prefix sum for this sub array right um and then again six we had six to nine that's 15 and this represents the prefix sum for this subarray and you get the idea all the way to till the end but the nice property about prefix sum is that you can easily with it you can easily find the prefix sum of a range in the array itself that is not from the start so that what that means basically is that let's say we want the prefix sum of this sub array here from 1 162. let's say you want the sum of just that sub array we can do it in of one operation let's say if it was a long one we don't need to we can do it in a way where we don't need to count the sum of calculating each element adding it together how because what you can do is just take this prefix sum here at the end of your sub array and the prefix sum just before your range which in our case here is this one so the prefix sum just before the first element and at the last element and you can just take the difference in this case um it's 17-8 um it's 17-8 um it's 17-8 right and so that's nine and actually if we do this one plus six plus two is nine right and so that's actually that's the where prefix sum is useful then there is another additional thing where it's even more powerful you know and that's if you combine that with a map so let's say um let's say you um you want the prefix sum that is equal to some K value okay so you want subarray that is that has a sum equal to K um yeah so this concept becomes even more powerful if you combine it with a map let's say for example we Define our problem a little bit and let's say we were looking for the sum uh sub array of sum equal to K instead of divisible by K Okay so how do we represent a subarray in our case here in a general one that can both encapsulate an inner sub-array and an encapsulate an inner sub-array and an encapsulate an inner sub-array and an array starting from the end well what we said is let's just have it with the last one minus the one before and for these that are starting from here we can just consider that before is equal to zero because before it doesn't add anything to the sum and right and so let's call this index J and the starting position just before the starting position let's call that index I okay so what is the sum of this portion here it's just s of J the sum of the prefix sum um ending at J minus the prefix sum ending at I right and so what we are looking for is a sub array that has this sum right equal to K that's what we are looking for okay so for a prefix sum let's call prefix sum just P of ga and prefix sum ending at I is equal to I for this to be equal to K what do we need um so this basically means that P of J minus K right if we do put K to the other side and put I to the other side here and put K here this would mean p of J minus k um equal to P of I right okay um is equal to of P of I um so what that what does this tell us um right peer by definition here P of I is before P of J right so what does this tell us this tells us basically that if we are at position J right and we want to know if we had a sub array that has a sum equal to K all we need to check is if there was a value that we've seen before that is equal to this because that would mean we've seen a pi value which would mean with this formula here ours we have a sub array sum that is equal to K right so that's the clever part and so basically what this would mean is that if there was a sum a prefix sum uh before uh J that is equal to P of J minus k then that means there is that means sub array um I plus 1 to J has sum equal to K right just by using the formula that we did here right and this is easy to check for we can just as we do the prefix sum we can just keep track of the um of all the sums we've seen so far and that way um let's say if even if we had multiple let's say we had um let's say maybe we had some like this and we had another sum like this so let's say I was here and for both we would have um for both the same sum this is just taking an example actually this let me just do an example that works um let's say we have two sub arrays like one and then zero one right and then some prefix sum here um right then what we need is we do want to count both this one and this one so we need to actually we have as many sub arrays that have some equal to K as the count of the this value that we can find okay and so that's why we need a map of the sum in the count that we've seen so far and then we would know how many sub arrays equal to K that we have right okay so now let's run it on this example um so a little bit and from there we can apply this to the modulo K so let's have a map here and so first we have the sum 3 we have only one and then we have some eight we have only one and so how do we check now we check just the prefix sum which is we just check if we've seen um 8 minus let's say our K is equal to 7 we just check if we've seen eight minus seven which is equal to one we haven't seen it so we proceed we have we don't have us we don't have um we don't have a sub array of sum seven yet and so we add eight and then we'd add nine have we seen nine um minus seven which is 2 8 9 right we haven't and so we don't have a sub array of sum seven yet um so we add fifteen have we seen a sub-array that is have we seen a sub-array that is have we seen a sub-array that is um so 15 is one have we seen a sub array of 15-7 so that's um three plus five of 15-7 so that's um three plus five of 15-7 so that's um three plus five eight yes we do have it here right so that means or and how many counts just one so that means we have a sub array of some uh seven because and what is that subarray ends at this position right and it starts just after the one at eight so it starts just after this one so that's actually um six plus seven right this is the sub array of sum 7. and that's exactly what our solution told us right and so you can see it works for some equal to K now the challenge becomes how do we apply it to the modular case um let's take a look then um so the modular case is actually pretty similar so we know that we need to calculate the prefix sum we will need to do the same thing with the prefix map the only thing we need to change is how do we apply this formula because it's not the same thing it's not that it's equal to K um this what the problem says for us in this case is divisible by K right so basically what it tells us is that um P of J minus P of I needs to be modulo K needs to be equal to zero that's exactly what divisible by K is so the sub array sum needs to be which is equal to this so this is the subarray sum needs to be divisible by K and divisible by K means modulo K it's equal to zero and so um and so what this would mean is let's apply our modulo and so this means that PJ let's just enter it module okay minus P of i modulo k so just mathematically needs to be equal to zero um okay so this is what it what this formula tells us now this is here let's just give this a name this is the reminder of the division by K and so let's call it r j and let's call it this R of I so what we have here is that they are equal um so what this would mean is that basically exactly the same thing we did here where we watched except we were searching for PG minus K what we need here is actually for etj let's look for the same if we've seen the same reminder before because if we've seen the same reminder that means there is an eye position that has this valid because we just did the formula and we got mathematic mathematically that this is equal to this and so if we find the that we've seen an index I before that is smaller than J right such that it's the same reminder that means we do have a sub array that has this formula right because this formula the last one is the direct result of this one of the first one okay so if we find an error IE that we've seen already from our map then that means we have sub array so this is the same logic applied here for the sum equal to K and again for the same reasons I mentioned here for the sum equal to K where we need to um we if we've seen it twice or three times or four times we need to count that many of them right because that means it's multi is different sub arrays like here it's this sub array the other one is the sub array and so for each eye basically what this would mean is that for each prefix sum in our prefix map what we will need to change is for each prefix sum we will for each index we will save the reminder and we will add that we've seen it and so if you've seen it multiple times we would have a count of three or four and so for next J if we find a reminder that is equal we will add we will count that we've seen a sub array that has that is it has a sum that is divisible by K um yeah so that's pretty much the idea here I hope that was clear um just start from the idea of the prefix sum and the pre in that idea allowing you to find the quickly the sum of a range and then from there that idea allowing you to see um by looking at if you've seen Samsung before um it tells you if there is some property for that range um and from there we could just do this formula and calculate our and calculate uh our case with sub array some divisible by k um yeah so that's pretty much it that's pretty much the idea and I'll just implement it and make sure it passes out these cases um okay so let's do the implementation here so what we need first is the length of the array and we need to have a prefix map for our that we've mentioned that will store the values for us and there is only one caveat is that what if the sub array sum that we are looking for is actually starting from the initial position right what if let's say maybe we K is equal to 5 and we have this and then we have something like this an array like this right so in this case this is actually a valid prefix sum and this also is valid prefix sum that is divisible by K but the problem is we only will measure if we find a previous index where the reminder of that is equal to the reminder of either reminder of the sum the prefix sum is equal to the reminder of the previous sum at J is equal to the reminder of the prefix sum at I but since there was no prefix sum before we won't find the solution and so how do we fix that well let's just Mark that zero which is actually almost as if we had a prefix sum before equal to zero and that's sort of right because when you have an empty the sum of empty is zero right and so let's just Mark that we've seen a counter in our prefix map we've seen a counter of zero equal to one so that we can these cases that start from zero can work okay so that's the only thing to remember here and this also by the way applies to all the cases where all the similar problems while we are doing a prefix sum um and you are doing a count for how many sums you've seen so far right um and so here we will go through the array for each index we just need to keep track of the current sum and keep track of how many sub array sums that are divisible by K um and so for the current sum we just need to add the number at I and now what is rfj um out of at I right um so maybe let's call this JS just so that it's um similar to how we were thinking so RJ is actually just current module okay right and what is RI that we are looking for um our I should be the same thing so we are looking for some value that is equal that we've seen before that is equal that has the same reminder this is actually whatever so if this exists that means there is an r i so that means there is a prefix sum at position I um that tells us that the sum between I and J um the sub array sum between I plus 1 and J is divisible by K right that's what we've seen in the formula and so that means we need to count just how many we have so if we have multiple at different eye positions then we want to count as many of them because each of them means a different sub array has a sum that is divisible by K right um and so that's exactly what we have here and we need to say that we've seen this value once at position at this position J so that for future J we can use this right and then at the end we want a return count now just one slight modification I want to make here is that we so that this current value doesn't grow we don't need it um to grow we just need to know module okay what's the value so instead of doing this we can just say current modulo equal to K and actually use that current here okay and sorry this is J because we changed the index and this is current because we changed it current right and so that should be it now let's just um run this and make sure it passes looks good let's submit and that passes test cases right um now yeah now in terms of time complexity what is the time complexity for this um I hope this solution was clear just run it on more examples and you will see um so it's oven time in terms of space we are using this extra map so it's uh also open um is it oven space or of K that's a good question right um and in reality here let's see how many what's what are the values possible for this current here we can only have um module okay right we can only have um current is always we always do much okay that means current is always smaller than k okay that means the number of entries in prefix maps are always small or equal to K that means actually the space is of K space right so that's why also you can use an array here of K entries um yeah so that's the idea here I hope this makes sense please like And subscribe and see you on the next one bye
Subarray Sums Divisible by K
reorder-data-in-log-files
Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`. A **subarray** is a **contiguous** part of an array. **Example 1:** **Input:** nums = \[4,5,0,-2,-3,1\], k = 5 **Output:** 7 **Explanation:** There are 7 subarrays with a sum divisible by k = 5: \[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\] **Example 2:** **Input:** nums = \[5\], k = 9 **Output:** 0 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `2 <= k <= 104`
null
Array,String,Sorting
Easy
null
1,961
foreign and today we guys are going to solve a new lead code question that is check if a string is a prefix of array so let's read out the question C is given a string s and an array of string words determine whether s is a prefix string of words our string as a prefix string of Words If s can be made by concatenating the first K string in words for some positive k no longer than first dot length so now uh return true if s is a prefix of words or a false otherwise so guys we have written a Boolean value in this question and what cases we have to just check here is that if s here this thing as a prefix of words I words uh so we have to check if s is a perfect string of words so if it's there then we have to return true or return false so what prefix is the prefix means the starting word if it's starting from words then we have to return if s is starting from uh words then we can see it's true otherwise you have to return false so guys yes you can see that it's starting definitely it's starting because words I and this I is matching and love lead code all of them are matching so we can see that it's starting however apple is excluded from this so we can ignore it because we have to just check if first word is matching in this first word of s a first word of word I is matching from s uh first word so we can see that it's true otherwise you have to return false so likewise you can see example number two I love lead quote words I because it's not matching here you can see that starting from apples and starting from I so we say that it's not starting it's not a prefix so we say that's uh it's a fault condition so guys let's start to solve this question and just before starting to solve this question guys do subscribe to the channel hit the like button press the Bell icon button and book Marti playlist so that you can get the updates from the channel so guys what we are gonna do here first of all we will create answer variable here which will be our empty string and in this we will be concatenating the words I and checking if it's true or not let me show it to you what exactly I mean here is uh let I is equals to 0 I will Loop through it I is less than uh word start length and I plus so I will be starting from 0 till Awards I dot let's just like they have said in this question that it should be no longer than would start length so we are going through we are iterating it through word sort length and I will be just concatenating uh answer plus words I in my answer string that I have created and now once I have created this I will just check if ours is equals to S return me true return true if this is true return true else written false return false for all the condition which are not following the condition inside the loop so in this Loop here we are just checking that if answer variable has this as first of all what we will be doing here we will be just concatenating the words I uh so it will just starting concatenating till here so for it will have first word of words I uh here and if it's not matching with the words is if answer is not matching with it return true otherwise written false so this is the logic we have applied here and I hope that you guys have understood this question so uh if you guys have not interested in question yet ask me in the comment section I will try to sort it out thank you guys for watching this video and let me run this code before we just wind up yeah it's working and this was all in the question guys I hope that you guys have understood this question thank you guys for watching this video and see you next time
Check If String Is a Prefix of Array
maximum-ice-cream-bars
Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`. A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`. Return `true` _if_ `s` _is a **prefix string** of_ `words`_, or_ `false` _otherwise_. **Example 1:** **Input:** s = "iloveleetcode ", words = \[ "i ", "love ", "leetcode ", "apples "\] **Output:** true **Explanation:** s can be made by concatenating "i ", "love ", and "leetcode " together. **Example 2:** **Input:** s = "iloveleetcode ", words = \[ "apples ", "i ", "love ", "leetcode "\] **Output:** false **Explanation:** It is impossible to make s using a prefix of arr. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 20` * `1 <= s.length <= 1000` * `words[i]` and `s` consist of only lowercase English letters.
It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first.
Array,Greedy,Sorting
Medium
null
735
Integers representing steroids in n road ok and this test salut value represent with size absolute value you know without any sign and d sign represent its direction ok positive mens right direction negative mens left direction basically moving forward and moving backward these two options You have h moves aate di se speed is ok speed is never a pea find out d state of d extraoids after which colleges are ok telling you the final stage of storage when all the collisions are there Jain water pollution now we will see if you are asteroids Meet D Smaller One Bill Exploited Ok IF Both Are Of Se Size Both Bills Exploit Ok These Are Very Important Points Moving In D Se Direction Bill Never Meet Me Understand Cars Like You Don't Drive On One Side Of The Road Only One Direction If I am going then face to face - we will never come, okay then face to face - we will never come, okay then face to face - we will never come, okay then that position will not be there, when does collision happen, when any color comes in contact, then here in the question also, did they understand how are these asteroids 510 15 Okay, so you see 5 more 10 if these are two positive numbers then the positive one will always move to the right and -5 if positive one will always move to the right and -5 if positive one will always move to the right and -5 if you have a negative number then where will the negative number move or will it move to the left side then some collision is happening here like now which one will you collide with first? 10 and If it is between 5 then 10 and 5 if 10 is your big value then what will happen to the smaller one will get explored then what is my -5 will get explored then what is my -5 will get explored then what is my -5 will get fat then finally what is my answer child why 5 and 10 because in the direction from five maintenance he They will never collide with each other. Okay, so let's take a better example because this is a very small example, with this you will not understand what algorithm, what data we should do here, so I am taken late, the first value I have is 10. Ok second one is 12 so now my line is ok you are ok next A goes to me - is ok you are ok next A goes to me - is ok you are ok next A goes to me - 5 now minus five A is in the opposite direction i.e. who will collide i.e. who will collide i.e. who will collide with you first ok now you and minus five which is the bigger value Now you will say, you are big, okay, agree, but here they have said that its value should be absolute value, that is, without sign, what is the actual value of -5? Five is what is the actual value of -5? Five is what is the actual value of -5? Five is okay, which is the value at the time of your explosion. It will go well, that is its absolute value because - Sun is only representing the direction, value because - Sun is only representing the direction, value because - Sun is only representing the direction, let's five and tu mein five aapka bada hai to what will be exploited, this tu will happen, give - 5 again will collide with your 10, this time but give - 5 again will collide with your 10, this time but give - 5 again will collide with your 10, this time but 10 here pe kya hai 10 is a big number, by five it means this time it will be 5x. Okay, so how is your state now? 10 So you saw, first it attacked the ISP, then it attacked this. Okay, that means this serial is tagging it. Moving on to the next. I have got four, what is this positive number is ok so 10 and 4 will go in the same direction no problem next got minus 10 now -10 again if it is upside down then what will it do now -10 again if it is upside down then what will it do now -10 again if it is upside down then what will it do first it will hit four then it will explode it will hit -10 Now see, the hit -10 Now see, the hit -10 Now see, the value of both is exactly 10 and one is positive and one is negative and we have just read in the question that if the value of both is equal to then both will be explored, so whatever answer I was maintaining. Thoughts over no there is nothing here next value came I have -40 again a negative number I have -40 again a negative number I have -40 again a negative number from 30 someone will light and 30 explorer because of teacher number when I say mines 40 give date mins salut value which is 40 correct again mines 40 It will end after colliding with 448. No elements are left, so I am left with -40. No elements are left, so I am left with -40. No elements are left, so I am left with -40. Okay, again a 40 came. Now tell me, what will 40 do? It will become zero after colliding with 448. Right, no, question. You are not understanding, friend, what are you guys doing, don't you listen? Look - 40 is here, where is 40. Look - 40 is here, where is 40. Look - 40 is here, where is 40. Positive number in this direction. Negative number in this direction. If it is fine then it will never collide with each other, that is, minus 14. Bill be your final state. It is moving here, it is moving here. There is no relation between each other, okay, so this is the question, no, bill you solve this question, okay, look, what is important here is to analyze, when a negative number is moving, it is causing an explosion, positive numbers are moving. There will be no problem, as in the example, I had all the positive numbers in the line and one negative number came which is bigger than this but smaller than this, so who will explode first, it is ok i.e. who is finishing first and who is i.e. who is finishing first and who is i.e. who is finishing first and who is last. A is right and what data structure does this property give you? Don't want too much gold. Stock is ok. Last in first out is the concept here that this one came in last and will be out first. This one came after that and will be out after that. Okay so this order is okay this order is maintain by stock data structure so now we clean it and do our stack to that okay to solve I have kept a step data structure there is a variable i by which I can create this driver Now first element I get is 10 date this is a positive number whether it is positive or negative if the stock is empty there is no element then what to do then ok then insert it if the pack is empty now look at the stock What's on top is a positive number and you have a is a positive number. If we understand this in another way, if the incoming number is a positive number, let's say here if it was -10 and the incoming number here if it was -10 and the incoming number here if it was -10 and the incoming number is a positive number like we have here. I saw that there was a negative number but a positive number came, so there bill should be no collision right, if the positive number is on the top and there is a negative number, then you will add it. Okay, now they are gone right, their direction is opposite but this Now you have taken out each other but you understand that this person was going inside this road too and when he passed from here then this 40 came here ok so brother in law this is no collision right ok so from back. Let's make it positive ten basically if you have positive number then debt bill b also now blind infection so in our two kaise we have blind inserts one is positive number and one is empty ok there are two blind inserts nothing can be done there minus five one Negative number comes. Now see what are the conditions divided here. I have to write your incoming number here. Okay, what is this incoming number? It is negative and there were two possibilities on the tractor top, else it can be positive which is here IF - 5 is negative tu is which is here IF - 5 is negative tu is which is here IF - 5 is negative tu is n positive opposite direction then what do I have to do Absolute value of this incoming number bill b five Now I will check if it is correct in 5*2 five Now I will check if it is correct in 5*2 five Now I will check if it is correct in 5*2 What have you read then if five is bigger then five will be your Once it gets popped, I will pop the tu and compare it with the stalking element. Next, I have 10 and 5. What is bigger? 10 is bigger, that is, this time it will be explored and I will not do anything with this text. Okay, let's go. Next, I have 4, so let's insert 4. Okay, positive number, one negative number, 10. Okay, now look at this is 10 and this time is from exactly, that is, if two values ​​are going to be time is from exactly, that is, if two values ​​are going to be time is from exactly, that is, if two values ​​are going to be exactly then what will I have to do to both. I have to pop it, there is no life in the question, so what did I do, I popped it too and I will not insult her, this is where I will break, because you, I have no element, brother, both of them collided with each other, both of them got exploded. It's over, okay, no, I am the statue MP, okay, here's another condition, very sweet, from late, here instead of 10, it was -16, okay, then again here instead of 10, it was -16, okay, then again here instead of 10, it was -16, okay, then again your -10 comes, it pops the four, your -10 comes, it pops the four, your -10 comes, it pops the four, next I saw -60, that is. Two negative numbers, that is, there will next I saw -60, that is. Two negative numbers, that is, there will next I saw -60, that is. Two negative numbers, that is, there will never be a collision one above the other, how do I insert this -10, I insert this -10, I insert this -10, okay how is the number three also, you can see here, it is possible that there would have been an empty four and if nothing had happened, then -10. I have given the example of 4, now there nothing had happened, then -10. I have given the example of 4, now there nothing had happened, then -10. I have given the example of 4, now there is no stock, so what do I do - I is no stock, so what do I do - I is no stock, so what do I do - I insert 10, okay, then these three will teach you how to handle them here, so tired for now, let's come back to my question - tired for now, let's come back to my question - tired for now, let's come back to my question - when 60 is reached, then we will see these 10 also. This is gone, this -10 is also gone, next element This is gone, this -10 is also gone, next element This is gone, this -10 is also gone, next element number, what to do, blind insertion, also empty, next value, 30 line, answer seat, next value - 40, negative, again small, eg two, now see the same condition which I was telling you, the stack is empty. You have the number minus 40 i.e. is empty. You have the number minus 40 i.e. is empty. You have the number minus 40 i.e. insert it next is 40 is a positive number but these two will obviously not collide because the negative is already gone when 40 something like this has happened here so anyway this is never going to plate. What will be the state of my state 40 N - What will be the state of my state 40 N - What will be the state of my state 40 N - 40 ok so this bill be me answer but you know how the stock reduces if you pop it then the answer will come 40 - 40 ok this is this pop it then the answer will come 40 - 40 ok this is this pop it then the answer will come 40 - 40 ok this is this color this should not come answer what Yours should be -40 Comma 40 Correct what Yours should be -40 Comma 40 Correct what Yours should be -40 Comma 40 Correct This should be it brother, whatever I will write first, I will do a trick, I will create my own answer, okay, what size number, the track here is the first element, there are two elements, now what will I do, start inserting from here. If I do, then first pop the value and put it behind, okay, pop the next value minus 40 and put it on the next value, you have to do the same and the tags are also finished because it is due to their size, okay, so I hope you have understood today's question. Now let's code this quickly so I first make a stock let's stock wait tag is equal you new tag ints okay let's do it okay and asteroids of I give it greater zero okay so it makes max sense because book this If you go in direction then IF it is greater give zero give they have you question okay so I just checked right so IF talk okay because both negative okay push be happy okay next is about absolute value so what I do it calculate It's absolute value so I can do mode well okay i = math dot i this is basically if you have a negative sign then it will make it positive also okay so I turn it up a little bit okay so know what I have you check this these two If it is from is okay then mode well equals your top is okay then how will this one happen what will be the direction if it is from both of them okay then I will not inset this one, for now I will also pop the top which is there along with it so stock dot P Okay and let's break the bill again else if right now there can be only two cases here which is your incoming mode value it will either be big or small okay so what way can it be this value mall okay so I can make it well, take it from your top, so in this, we will not insert anything, we will not pop anything, okay this is basic, do n't do anything, help last, what is yours, brother, the model that is coming is big. That is, if the pop operation will be performed here then let's say simply stock dot com and I can say that if you have stock, it is okay, if it is, do not tag it, give it empty, what you need to do, land inserts are okay, so I hope this is complete. That's it, I don't think we need to handle anything else here. Anyway, this will finish the look. No, I have you created me, answer is equal to cycle, new in size is equal, you are okay, this top band is done. Okay fantastic and a very good solution is going on okay it was typical to visualize it a little so I dry ironed it beforehand okay which direction is it if it is positive then what is happening if it is negative then what is happening then blindly never court Don't do this, always try to write down all the cases first. It's okay and you may miss some things too. Like, when I coded this dead two years ago, there was a problem in it that I did not mention this one here. I did it ok so because of that I was thinking ok I am getting blind and area what is the problem then I asked him which is the test which is giving me problem then I came to know ok I had not done this Ok and you guys are new then you might have problem in send mode valve also, you guys might not have done this, that's why in the question, this is the easiest condition to miss brother, if it is from both then do n't insert that small one as it is not written. It is a relief that the subject of mutual funds is market rest, it is written in a hidden manner that if it is from the size of the brother, then it has to be explained, okay, then the problem setters leave all these clever tricks for you, so you just have to read the questions carefully and like the video. Code easily, it is done, okay, so that was all in today's video, and complexity is time complexity, what will be its time complexity, then space complexity, now coming to me, there can be most n elements, all in one direction, go, see your time, you are single. You are picking the element but you are also going back Correct like I have 10 positive 10 negative numbers and breaking all the negative numbers by three I am breaking the positive numbers now butter wire explain with the help of diagram so it should be clear Okay so your green with me date this is positive number okay so it will pop like this will pop plus time I did de pop operation 10 times okay which is this again 2n okay but late se n this note 5 now We see more numbers, sixth number D was the seventh number, minus number was 80, give it 100, okay, this is how we understand, okay - give it 100, okay, this is how we understand, okay - give it 100, okay, this is how we understand, okay - 13 has reduced its value, this insert is okay, when minus 70 will come, see, it is a negative number, big of one operation is okay. That will also be inserted. Let your 100 come, that will also be inserted. Okay, so you who are never seeing the Bob D element again, so go, I agree, how many times should this run, your 10 11 12 13 14 Times 123456789 You have 9 elements. This difference is five times more than this, okay, so it is again and multiple like this is n + it is again and multiple like this is n + it is again and multiple like this is n + 5 and you can avoid const, it is not like you are doing n² time, n people are doing more time, okay so this You will have to understand this Likely more give these okay but definitely if you have watched time complexity video, my video is good then you know this is again solution, this was all in today's video, I hope you have understood today's video and it is quite interesting. This problem has been asked in many interviews so practice well and this was it in today's video, see you in the next video till then bye and tech.
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
328
all right so let's talk about all your linked lists so you are given a link list and then you just have to swap the order so if the number comes for the node you just have to connect together even count of the node you just can't activate it and then at the end uh at the end of the all number comes from the linked list you have to connect to the beginning of the even number of the inputs so this is pretty straightforward but uh you have to use in the older firm full of time all one for the space so you are now allowed to create a list of three nodes all this node and then you collect every single all number of the node and then put that if you are even number of nodes and then you come that name at the end like this is not at all so basically this is super straightforward so i'm going to just connect start from here this is going to be my r this is going to be my even right this is better to just change my color to here even and then in the beginning i'm going to traverse my all so all is going to jump to union every single time right and then this is going to be my at the end of traversal and for the so this is almost finished but the problem is well you have to connect the end of the r to uh to the beginning of the event so since we are swapping while we are changing our even pointer so we need to keep the value for the beginning of the event so i'm going to go even hand just point right over here so at the end of the r i will just say out of next equal to even uh this is pretty much it so i'm going to just stop coding and you'll be able to follow along so here is it sorry for the hand is actually equal to no you're written no right and i'm going to create two i mean three r equal to head right even equal to what another one even hand this is the beginning of the even uh even though right i'm going to just temporarily sort it and then i need to traverse my necklace and then this is going to be one this is going to be based on my condition here even condition so if even it's not equal to node and also even the next is 9.0 even the next is 9.0 even the next is 9.0 so you'll jump to union every single time right so uh why this is even not all this is because even it's always one union after the r right so we will keep track of the furthest one right so all the next is i change my pointer the next pointer from my r to uh next on the next right so all the next how about even keeper is going to be exactly the same thing for even on this to even the next one and then since we are changing our pointer for the next pointer we can actually uh reallocate our order even to all the next even the next right and this is pretty much it right so at the end i need to change my alternate at the end of the uh olympus to uh to the beginning of the event in english so this is pretty much the solution so since i'm not changing my head i just return my head and then here we go all right so i made a mistake with you otd all right so submit all right so let's talk about timing space this is going to be a time all right this is going to be a space is going to be constant again uh this is all of one for the space constantly all of them for the time right and this is the solution so it does practice your linkless structure so i will see you next time and bye
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
529
hello everyone today we are gonna talk about um problem 529 my sweeper so uh this one is kind of um can be done both in dfs and the bfs but i today i'm gonna talk about the bfs solution so you are given basically a charm a matrix char matrix which is a board so if you have played a minesweeper um when you are a kid so it's like uh try to identify or induce which cell in the matrix is a mind and try to avoid the mind so here and represents and reviewed mine and the e represents and review the empty square um but if uh does a cell or empty or square shows the empathy that means there might be some um mines across that adjacent area or there might be a blank square that has no adjacent mice so if it has adjacent minds then we can uh count how many mice it has in the adjacent area so if uh for instance here i have one empty cell and then i count how many mines across this the adjacent area so i have one so here is set to be one and x represent a reviewed mine so once the mine is reviewed the game is over so this is the basic rule for my sweeper and this can be done both in bfs which means breakfast search or depth for search so here i'm gonna use the breakfast search first and then maybe tomorrow i'll talk about the depth first search so there are uh actually um one uh two elements in the breath breakfast search actually so the first one is a queue so the queue used to keep a record of what other elements to that needs to be visit in the future so in order to keep record of what other elements that need to be visit visited in the future we also need to have a um kind of keep record of what elements have been visited or not here we use a variable called sin it can be here i use a set to save some space otherwise if i create another uh board which means it's a n times n us uh square that can cause uh some memory so here i use syn as a set to keep record of all the elements that have i have been visited so once the element has been visited it won't be added to the queue again so this can uh help to save a lot of time and avoid the infinitive loop so okay so q is a data structure in python we can create a queue as a list or we can use the queue dq library in the collection package so here i use queue in a collection collections dot dq and then first i get the value from click and assign the value to x and y here so first i use q to append x and the y first and then i use a direction to represent our adjacent uh our json neighbors given a certain cell so direction uh here i also use a set uh it can has eight elements across one cell so it can be minus one times uh minus 1 0 -1 -1 -1 plus 1 0 and then 0 minus one and then zero plus one zero plus 1 and 1 minus 1 and then uh minus one and then finally we have a last um one so these are the eight directions given a certain style all adjacent directions are here so we need to iterate over the outer direction to first identify how many mice in the adjacent cells and then second try to identify if for the adjacent cell we need to add to the queue or not so these are the direction we will use later on and then uh for the scene it is a set and then the first element we have seen so far will be the x and the y we add to the scene okay so this is the initialization phase before we start the problem so we will use a queue to keep a record of all the elements we need to visit until the queue becomes a becomes empty that means we finish our element we need to um we need to uncheck so we use a q as a loop invert invariant so um first we pop from the queue x and y equals to um m that means it's a already a mine that means the game is over right so beyond board uh x and y are equals to um x right so that means game is over and we need to break the q we don't need to continue the game anymore and else if lf or x and y are equals to uh here it means a empty element then that can be divided into two um branch so first it has um we need to count how many um how many uh mines across that uh cell and the second if we didn't find any um mines across it we need to assign the b value to the empty um square and then we need to decide uh what are the adjacent elements that need to be further um explore okay uh so here if um if it is e then we need to set a um variable here i called it n to keep record of all the mines across this um across the x and y so for i and j in the direction if x is less than x uh sorry 0 is less than x plus i and the less than is keep checking the boundary 4 and 0 is less than or equal to y plus j less than dance board zero um that means um we are still within the boundary of the board so if word x plus i and y plus j equals to mine then we will add and to add one to the number of n after that we will check if n is larger than zero if that is the case then we need to convert the end to hr chart or to string and then assign the value to the board so here i will change the value of n to a string and then do this chart assignment else if word x y equals to b else if x uh y otherwise x y will be assigned the value um of um b so for uh i and the j in direction we need to this we need to decide whether this element can be added to the queue so in order to be added to the queue it has to be satisfy two um condition so the first one is it has to be within the range and the second one is um the x plus i and y plus j cannot be in the syn set x plus i and the y plus j cannot be in the syn set only in this case i will ask the queue an element of x plus i and y plus j okay and then finally we will return no need to return the board we need to return the board okay now it passed okay thank you for watching
Minesweeper
minesweeper
Let's play the minesweeper game ([Wikipedia](https://en.wikipedia.org/wiki/Minesweeper_(video_game)), [online game](http://minesweeperonline.com))! You are given an `m x n` char matrix `board` representing the game board where: * `'M'` represents an unrevealed mine, * `'E'` represents an unrevealed empty square, * `'B'` represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals), * digit (`'1'` to `'8'`) represents how many mines are adjacent to this revealed square, and * `'X'` represents a revealed mine. You are also given an integer array `click` where `click = [clickr, clickc]` represents the next click position among all the unrevealed squares (`'M'` or `'E'`). Return _the board after revealing this position according to the following rules_: 1. If a mine `'M'` is revealed, then the game is over. You should change it to `'X'`. 2. If an empty square `'E'` with no adjacent mines is revealed, then change it to a revealed blank `'B'` and all of its adjacent unrevealed squares should be revealed recursively. 3. If an empty square `'E'` with at least one adjacent mine is revealed, then change it to a digit (`'1'` to `'8'`) representing the number of adjacent mines. 4. Return the board when no more squares will be revealed. **Example 1:** **Input:** board = \[\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "M ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\],\[ "E ", "E ", "E ", "E ", "E "\]\], click = \[3,0\] **Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\] **Example 2:** **Input:** board = \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "M ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\], click = \[1,2\] **Output:** \[\[ "B ", "1 ", "E ", "1 ", "B "\],\[ "B ", "1 ", "X ", "1 ", "B "\],\[ "B ", "1 ", "1 ", "1 ", "B "\],\[ "B ", "B ", "B ", "B ", "B "\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 50` * `board[i][j]` is either `'M'`, `'E'`, `'B'`, or a digit from `'1'` to `'8'`. * `click.length == 2` * `0 <= clickr < m` * `0 <= clickc < n` * `board[clickr][clickc]` is either `'M'` or `'E'`.
null
Array,Depth-First Search,Breadth-First Search,Matrix
Medium
2206
1,561
Hello everyone welcome to my channel Quote Sorry with Mike So today we are going to do video number 23 of our Grady playlist today's question is going to be very easy lead code number is 1561 maximum number of coins you can get okay and let's watch the question is quite easy It is simple, it says that three times a piles of coins have been given to you, okay, 3n piles of coins have been given, you and your friends will take piles of coins as follows, see how it says, Main Jo Hoon, you will choose any three piles meaning Suppose you have many piles given to you, look here, there are 2 4178, so you pick any three piles, once now anything can happen and suppose you have randomly picked this and this, okay of your choice, which three piles You will pick the next pile with the maximum number of coins, meaning I will pick the second largest pile and The last pile will be taken by Bob and we have to keep repeating this operation until all the piles are finished. Okay, return the maximum number of coins that you can have. Okay, if we look at this example, the answer is What is one, what is the answer, why is Nan, the answer to this is, what do you do once, the first time you pick up the pile, you pick up these two, pick up these three, two to sen, 8, then the largest one will be taken by Alice every time. So this Alice took the second largest, I will take it, okay and gave the last one to Bob, so look how much I got seven, okay, this is done with three piles, okay, now let's see who are on these three piles. Let's see, two is four is one, then like every time Alice will always take the largest and I will take the second largest, the last one will take that of Bob, then how much should I get, if I get then 7 P 2, the answer is right, okay, so if we see So what is the best way to do this? You need maximum number of coins. Right, you need maximum number of coins and you can lift three piles at a time, so yes, you will want to lift only the biggest one. This is where Greedy comes in. You will want to pick the biggest one, or will you pick such a pile in which the largest is fine, let's say the largest will be taken by Alice, but the second largest should also be big, okay, but the third largest number of the pile should be taken in such a way that Bob will be taken from the smallest. So that Bob does not take any bigger number, did you understand what I am saying, since you want the largest coin, you want the largest sum, you do not want the maximum number of coins, so what am I saying, pick the biggest numbers. Take it every time. Let's assume that when you had the first chance, you picked up the biggest number. Look where T is visible. One Y is visible. After that, the second largest number is visible. This is the number you picked. After that, remember that look at the first largest number. So Alice will always be picked, you will never be able to get Alice, because that prisoner will take the largest number every time. Okay, so what can we do best with this, brother, the second largest number is also very good. If you choose then look at the second largest number, I have chosen seven, okay, I will take this and I would like Bob to take the smaller one so that the bigger one does not get lost. Because of Bob, I am saying that if we assume that I have chosen four. Had it been taken, then Bob would have got four, but it would have been a mess. Look later, now there is one left, two are left, so it is an obvious thing, give Bob the smaller one so that the bigger one- The big numbers are four or two, so that the bigger one- The big numbers are four or two, so that the bigger one- The big numbers are four or two, so that you can get them in the future, so that your chances can increase, what will I do? It is okay for Alice, she will pick the largest number, I will pick the largest number for her, even the second largest one, I will pick the biggest one. I mean, I will take the second largest number for myself, okay, so seven is taken and for Bob, take the smallest number, okay, sen is taken, 8 is taken, which is the smallest number visible for Bob? One is visible, okay, so let's take one, here Bob will get one, okay, so these three numbers are used, after that we will do the same, which is the largest number, four is the second largest, two is the second largest, after that there is only one. The number left is two, okay, that Bob will take this Alice, this is me, this Bob is okay, so since you want the largest and second largest, then it is obvious that you must have come to your mind that what do you have to do, what will happen by sorting. You will also be able to find out the largest and second largest element and the smallest element. Let us see this example to see how our process will run. 2 41 278 Is it ok 2 4 1 2 7 8 First of all let's sort it 1 2 There is another two 2 4 7 8 We have sorted it, now see what will be the benefit, what will I do, I have to lift three piles at a time, it is right every time, so what I did, I picked up the largest one and picked up the second largest one, why? Because if I pick the largest, she will take Alice but second largest is also good. Look, if I pick seven, then I will get it. Okay, this is Alice's and to pick Bob, I will pick the smallest number. Look, I will keep the pointer here so Bob. I will give one to, this is Bob's okay, so if you see, then you just have to sort and use three pointers, this is Bob's pointer, this seven is my pointer and the one at eight is Alice's pointer, okay so I got seven. So I added seven to the result ok now look pay attention the largest number after this is four and the second largest is two ok so pay attention I will get the second largest number no see the largest number is four and the second largest is two Two is okay so I will get the second largest so A will come over here and Alice will come over here Okay this time so look A comes from here to here and Alice comes from here to here Okay that means Joe pointer This is Joe pointer m minus = 2 Joe pointer This is Joe pointer m minus = 2 Joe pointer This is Joe pointer m minus = 2 and Alice minus e becomes 2, meaning I write the index 0 1 2 3 4 5 Alice comes directly from Pa to three i.e. m = A Alice comes directly from Pa to three i.e. m = A Alice comes directly from Pa to three i.e. m = A my 2 5 minus two t is ti hai na sorry pa three aa So Alice and I were here right at four so 4 minus two will do so I came to two Okay great and what will happen to Bob's bob Bob here will move one just okay Bob here so just move one pointer for b Okay, now see M is pointing to these three, A and B. Okay, so what will happen to us, who is the largest, who is pointing to Alice, the one to whom the four M is pointing will be the second largest and the one left in the last will be Third Largest Bob Okay so I got this Alice got this Bob got this plus what I got two got that Okay after that look now then I will try to go further to the left side but see if I can get Bob If I cross it then it is obvious that my process should stop there itself, so my answer is nine, okay, so as soon as it means, I will do the same again, m which is m = m - 2 m is the pointer which is mine. Meaning, a m = m - 2 m is the pointer which is mine. Meaning, a m = m - 2 m is the pointer which is mine. Meaning, a jump will hit here and Alice will jump here, but it is obvious, look at m, which has crossed b, which means we have exhausted all the elements, so I will stop there, okay, it is quite simple, one more example run. Let's try it, the more dry run you do, the better, okay, let's go by the values, we have 987 6 51 2 3 4, let's sort it first t 3 4 5 6 789 Okay, we will do the same again, we will take three pointers because once I have to pick three elements, so I will give the largest to Alice, I will take the second largest and I will give the smallest to Bob, okay so the one the m pointer is pointing to is my number, so I made eight plus okay m now come here. It will go from here to here, it has come to six, because this second largest number is now eight and neither has been used, so now the second largest number is m. Sorry, it is six and the largest number is seven. Okay, so m = m-2. largest number is seven. Okay, so m = m-2. largest number is seven. Okay, so m = m-2. a = a- 2 here and there c and bob will go one step ahead a = a- 2 here and there c and bob will go one step ahead a = a- 2 here and there c and bob will go one step ahead okay great now let's see what is the second largest number which is six so plus s I did okay we will do the same again m will come over here Alice will come over here because Both of these are used and Bob who is there will come here because it is used, okay still look at the largest number, Alice, take the second largest, the four one is okay, plus 4 is okay, how much is it becomes 18, after this if A will go ahead. So it will cross the BUP, meaning all the elements have been exhausted so we will stop here. Okay, it is quite simple. If you have to take a three pointer, look, pay attention, always remember, it is given in the question that what is the length of our piles or not? The length will be a multiple of three, okay, the length of the piles will be this, the size of our pile will be a multiple of three, so we don't have to take that tension, okay, and it will be three or bigger than three, its size will not be smaller than that. Because you had to lift only three piles at a time, so at least three will be given. Okay, so now look, let's pay attention here. I will start from n myve, remember from n-2 I will start from n myve, remember from n-2 I will start from n myve, remember from n-2 this is the largest, this is the second largest after sorting and Bob will start from index number zero, right here is Bob, he started from here, okay and for how long will I run this till which I am greater than Bob. As soon as I cross Bob, our for loop should stop there. Okay, so now in the result, we have zero in the starting. Result plus e is equal to two piles of the value of the pointer on which I am standing. I will get it, okay Bob will get Bob's one and Alice will get her Alice one, okay so I told you right, Bob plus will be plus because Bob's look was going one step ahead right and Alice which is minus. It will be and I am minus it will be 2, okay, I also showed you why I am doing this, isn't it great, then what to do in the end, return the result and is the end of the story, that was it was a very easy question, it is okay Now pay attention to one thing here, no, you don't care, there is no use of using the Alice statement. Look, m and b are working in the while loop also, this is just the Alice type, I have written it like this only. Given for completeness because I had used Alice pointer while explaining here, you can ignore it also, look at the pro without it too, there is no problem, the whole problem is fine because I am what I am, whatever pointer I am in, that is me. Look, I am running two alternatives, I am doing minus e 2, so it is obvious that if in the beginning, what was here was 8 and Nan, if I am M here is Alice, then even if I do not keep Alice, then there is a difference. No need, M took 8, then A will come here at six, then A will come here at four, because this is the largest, this one is the largest, this largest will take all the Alice, so there is no need of pointer to Alice, I just Alternatively, I will keep adding my own one, okay, I am doing the same here and will have to take Bob's one because look here, it is helping in comparison in the while loop, so we will manage with both Bob's pointer and mine, Alice. There is no need of a pointer, okay, here a my = 2 is not needed, it is a here a my = 2 is not needed, it is a here a my = 2 is not needed, it is a very simple code, okay, look, you must have noticed that we solved it by using three pointers or in other words only two. Solved it by using pointer, it's okay because look, I am removing elements from one side here also because Bob is moving forward slowly and also removing elements from the back because look, I am taking elements from behind here. So there is one more way to make it, which is such a data structure in which you can do operations from the front as well as from the back also in constant time, that is ours. There is no need to take extra data structure, right? Why would you need an extra data structure when your work can be done with a normal pointer? Okay, I found this approach more simple. Okay, now let's come to our approach number two, which is a more simplified approach. Okay, approach number two, which is more. This is also over simplified, by the way, remember that you must do sorting in approach one because without sorting how will you be able to find the largest second largest, then you must do sorting due to which the time complexity has become off-kilter. time complexity has become off-kilter. time complexity has become off-kilter. Ours is clear till now. Now let's come to our Look at approach two, let us understand from this example that I have already sorted the input, I am doing indexing 0 1 2 3 4 5 6 7 8 Okay, now pay attention to one thing, what we were doing above, you must have noticed that Every time we used to give Bob the Smollett element, right, I used to start from here, I took an A, then after hitting a skip, I took a six, then after hitting a skip, I took a four, meanwhile Alice would have taken this This must have been taken and Bob must have taken these three small elements from the beginning. Okay, this is clear so far, you are noticing one thing that Bob will take so many small elements from the beginning, right, Bob will take this small element from the beginning. And after that I will take this by hitting alternate, I will take this, then I will take this by hitting a skip, okay, so now pay attention to one thing, see its size, how much is the total, how many number of piles is there, total is nine piles, okay and you think for yourself. If I pick up three piles on the bar, how many turns will I be able to take? 9/3 Total n / 3 i.e. turns will I be able to take? 9/3 Total n / 3 i.e. turns will I be able to take? 9/3 Total n / 3 i.e. 9/3 i.e. total three chances, I can move. 9/3 i.e. total three chances, I can move. Okay, I will move in three chances, so the first three Smollett numbers are Bub. Okay, and the three largest numbers are 7 and f, Alice will take them. Okay, and I will take the three second largest numbers, so what's the point here, if you focus on Bob, that. The first three Smollett numbers will be taken, only after that I will start my take, look here, I took this, hit skip, this, I took, skip, hit this, I took, why are you skipping, because they are Alice Le League, every time is fine, so why? Now let's simplify it a bit so why don't I instead of not paying that much attention I know what I will do 4 5 6 7 8 9 Look how many chances we have to get How many chances we have to get three chances so the first three are taken by Bob If I go, I ca n't get it, so do you know what I will do? Look at the first three, till which index n is up to the middle index, how many chances can I take, total three chances can be taken because the value of n is n and these three. Where did I get it from n ba 3 because I can walk in total three chances, so three chances if I walk, then the first three are gone from my hands, they will go to Bob only because I am giving the Smollett element to him only. Where should I start from n-1, it's okay, there are three chances, so start from n-1, it's okay, there are three chances, so start from n-1, it's okay, there are three chances, so skip the first three, okay, 0 1 2 n - 1, not from 3, that is, from n, right, 0 1 2 n - 1, not from 3, that is, from n, right, 0 1 2 n - 1, not from 3, that is, from n, right, I can start from 3rd. This is me, after that I will not take it because she will take Alice, then I will take it, Ch is ok, then I will not take this, I will take this, so you see, 4 + 6 this, so you see, 4 + 6 this, so you see, 4 + 6 + 8, right, the answer has come, it is still ours, so + 8, right, the answer has come, it is still ours, so + 8, right, the answer has come, it is still ours, so we don't have anything. What I have to do is I will take a simple I pointer and where will I start from n to n then I will start from 3 ok the total number of turns which were mine i take n will be ok and i ps e see what is happening why do I am here so that I can skip. Look, I was here, I skipped this and then I came here. Okay, and why did I skip the first three because look, the total number of turns was three, no three, how? Take out 9 from n / 3. It is obvious that 9 from n / 3. It is obvious that 9 from n / 3. It is obvious that Bob will take the first three Smollett numbers, so I will start from n, right, I started from n. Look, ok, n, no, sorry, I am starting from n / 3. / 3 Okay, the starting from n / 3. / 3 Okay, the starting from n / 3. / 3 Okay, the total number of turns was three, so the first three went from my hand and I started from n / 3, so look three went from my hand and I started from n / 3, so look three went from my hand and I started from n / 3, so look here I have written the same that I will get it only from n / 3, right, written the same that I will get it only from n / 3, right, written the same that I will get it only from n / 3, right, I have replaced i here. But I write m is a pointer, it is fine and I don't have to do anything, result = piles of m, result = piles of m, result = piles of m, just return the result in the last, see, neither I needed Alice's pointer nor Bob's pointer, just one. It is done with the same pointer, my that is m is fine, there was a more simplified solution, it is fine with both the approaches, the time complexity is the same, here n is also used here because we have done sorting, space complexity has not taken space, quick code. Let's do this and finish it, so let's quickly code and finish it, let's do it with the first approach, first int n equals two piles dot size int result equals 0 and first of all you have to sort, right you You are solving Greedy, Beginning of Piles and End of Piles, OK, sorting is done, now I had said that I will take three pointers, the first pointer will be for Bob, which will start from zero, the second pointer will be for me, whichever will start from zero, and the third one will be for Bob. It will be for Alice which will start from zero, sorry not from zero, I will start from n-2 and Alice from n-1 to the start from n-2 and Alice from n-1 to the start from n-2 and Alice from n-1 to the last one because the last one will be the largest element, second largest element right and what will this guy be, Smollett, okay How long will I and I last? Remember, I told you that as long as I am there and ahead of Bob, if I cross Bob, that means all the elements have been finished, then it is okay, then the result plus is equal to two piles of which I am standing on the pointer and I will do minus it. Okay, Bob plus will become plus and whatever Alice is will also become minus it. Why is that also? I told you in the last what we have to do is to return the result. Run it and see. Let's take it and I had also told you that if you notice that you don't need the Alice pointer, you should have written Bob. Okay, you don't need the Alice pointer. Even if you remove the Alice pointer, then look at it. There is no work here, okay, so I remove it. Removed the S pointer from here. Removed it from here as well. Okay, let's submit and see. Let's CV should be able to pass all the dis cases. After that, do your second approach. Yes, we have solved this question. Now let's come to our second approach, it is also very simple. What did I say that this time we will remove it, so many points are not needed. 4 int m is the same. Remember, n / 3. We will are not needed. 4 int m is the same. Remember, n / 3. We will are not needed. 4 int m is the same. Remember, n / 3. We will start because starting with zero th index, first index second index means element of index up to n/3 -1 will be means element of index up to n/3 -1 will be means element of index up to n/3 -1 will be taken by Smollett element bob, after that I will go from n/3 onwards, alternatively go from n/3 onwards, alternatively go from n/3 onwards, alternatively those will be my elements, ok m e &lt; n m those will be my elements, ok m e &lt; n m those will be my elements, ok m e &lt; n m + = 2, here it is okay, pay attention, + = 2, here it is okay, pay attention, + = 2, here it is okay, pay attention, why are you doing m + = 2, because you are why are you doing m + = 2, because you are why are you doing m + = 2, because you are taking it as an alternative, Alice also has to give the largest number, okay, so the result is plus equal to two piles of A, okay, return the result in the last. By submitting this let's see hope fully we should be able to pass all the test cases indeed yes any doubt raise in the comment section come here to help you see you in next video thank you
Maximum Number of Coins You Can Get
rearrange-words-in-a-sentence
There are `3n` piles of coins of varying size, you and your friends will take piles of coins as follows: * In each step, you will choose **any** `3` piles of coins (not necessarily consecutive). * Of your choice, Alice will pick the pile with the maximum number of coins. * You will pick the next pile with the maximum number of coins. * Your friend Bob will pick the last pile. * Repeat until there are no more piles of coins. Given an array of integers `piles` where `piles[i]` is the number of coins in the `ith` pile. Return the maximum number of coins that you can have. **Example 1:** **Input:** piles = \[2,4,1,2,7,8\] **Output:** 9 **Explanation:** Choose the triplet (2, 7, 8), Alice Pick the pile with 8 coins, you the pile with **7** coins and Bob the last one. Choose the triplet (1, 2, 4), Alice Pick the pile with 4 coins, you the pile with **2** coins and Bob the last one. The maximum number of coins which you can have are: 7 + 2 = 9. On the other hand if we choose this arrangement (1, **2**, 8), (2, **4**, 7) you only get 2 + 4 = 6 coins which is not optimal. **Example 2:** **Input:** piles = \[2,4,5\] **Output:** 4 **Example 3:** **Input:** piles = \[9,8,7,6,5,1,2,3,4\] **Output:** 18 **Constraints:** * `3 <= piles.length <= 105` * `piles.length % 3 == 0` * `1 <= piles[i] <= 104`
Store each word and their relative position. Then, sort them by length of words in case of tie by their original order.
String,Sorting
Medium
null
394
string encoding and decoding are widely used in encryption problems well sometimes they make up good programming problems as well i am talking about the problem decode string on lead code a big hint to solve this problem is to use the stack data structure let us see how we can go about doing that hello friends welcome back to my channel first i will explain you the problem statement and we will look at some sample test cases next we will see how you can logically approach this problem and what are its limitations going forward we will try to find an optimal solution to the problem and then we will look at the pseudo code of this problem so that you understand how all of this actually works without further ado let's get started let us quickly make sure that we are understanding the problem statement correctly you are given an encoded string and you have to return me its decoded version right now there are certain rules about how this string is actually encoded so for example i would have a number k outside and inside the bracket i would have my encoded string when this opens up your output will be the encoded string and that will be repeated a k number of times that means if i have the number 2 outside and in my brackets i have bc then the decoded string would be b c so on that logic this encoding and decoding is working so for our first test case i have this string right so when i apply this formula first of all i see 3a so that will expand as a and then i have bc and a number 2 outside correct so this will expand as b c so for test case number one this string will be your answer now surely since there are brackets you can have brackets inside of bracket right and that is shown in our test case number two you have a outside bracket and you have an inside bracket so to solve this what we are going to do is we will first for the inner bracket so i get 3 and then a so i get 2 c's and this time i will solve the outer bracket so i will repeat this in a string three times so i get acc a total of three times so for a test case number two this string will be ultimately your answer now if you have understood the problem of treatment correctly feel free to try it out once more on your own otherwise let us dive into the solution okay so let us try to first generalize how you can solve this problem how you can approach it in a most logical way so let us say i have this string with me this is pretty generic right it has so many brackets and you even have nested brackets correct for a very difficult test case you could have a lot of nifted brackets right so first of all you need to define a particular way in which you are expecting to solve the problem right so when i have to solve problems or mathematical expressions that involve brackets what is the first thing that you do not solve the outer brackets first right what you will do is you will try to find out where you have the innermost brackets right so in this expression my innermost bracket is this right so this should be the first string that you are decoding right so how do we do that first of all i know that okay this is my string and how many times do i have to repeat it what is the value of k if 2 right so this means you have to repeat this string two number of times correct as soon as you decode this you will get a new string right once again what you're going to do is you will look at the innermost bracket right when you look at this bracket you will apply the same principle first of all identify the string this is the string right cxx and how many times do you have to repeat it a total of three times correct so as soon as you decode this you get a new string now look closely this why was getting carried over right and now this y has become a part of your innermost string right so this time this entire string will be my string that i have to work upon and the value of k will be 2 so what i'm gonna do is i will repeat this entire string two times as soon as i do it i get my final decoded string as the output so for this particular case this string will be your answer now if you try to approach the problem in the same way that you are thinking it so what you're going to do you will first iterate through the string find the innermost bracket and then find the expression then you're going to replace the string to find a new string once again you will traverse the string find the innermost bracket and then you will try to replace the string with a new string right so this is taking up a lot of time and if your string is very large you will spend a lot of time just iterating through the string again and again so definitely we need to find an optimal solution over here what can we do about it let us take up our sample string once again right and when we were approaching this problem logically how did we know which bracket is the innermost bracket you are starting to read the string from the beginning right so you see three brackets but how do you know which one is the innermost bracket the approach that we do in our mind is we keep on traversing the string and then as soon as we see a closing bracket we will go back right and we will go back to find the first opening bracket that we saw right so this is how i know that this will be my innermost string and that is the one i have to solve first correct think about it even when you are reading some piece of code so when you're reading this code how do you know which is the innermost block so you keep on reading through your code and then as soon as you see a closing bracket how do you identify what code block is contained in this bracket you will go back and try to find the first opening bracket so now you know that this code block lies in one logic right so this should give you some kind of a hint right you are traversing a string and then you want to go back and look at which elements that you encounter right that tells you that a stacked data structure can be really handy because in a stack what you can do is you can keep elements on top of each other and when you have to go back you can start popping out elements to look back at the previous element that you saw right so let us try to create a stack in which we will store all of our elements right but at the same time you know that you have to multiply some numbers right so what i'm gonna do is i will create two stacks one of the stack will store all of the integers and one of the stack will store all the rest of the elements that i have and what we're gonna do is we will start traversing this string from the beginning as soon as i start i get a number right so this number will go into my number stack and i will put this number 2 in my stack over here moving on i get a opening parenthesis correct i will put this into my string stack next i get a character again so just put it into the string stack next i see a number so put it into the number stack i have a opening parenthesis again put it into the string stack keep on moving now i get c so i will put c into my string stack then i get the number 2 so i will put 2 into my number stack then i get a opening bracket so i will put this opening bracket in my string stack then i get a x so i will again put this x into my string stack and now as soon as we move ahead you get a closing bracket this is where things get interesting when you are approaching this problem as soon as you got a closing bracket you had to identify that okay now i know my innermost bracket right so you have to solve for something so what can we do we can look into our string stack now because this is storing all the elements in a reverse order right so what i'm going to do is i will keep on popping elements from the stack until i get a opening parenthesis because this opening parenthesis is defining the inner block right so what is the character that i get the character x right so i am just going to take this character and pop it out of my stack and then i see a opening bracket so i will remove this from my stack once i got my character now i need to know how many times do i have to repeat it so i look in my number stack and i get 2. this means i have to repeat this character two times so what i'm going to do is i will repeat this character two times and now since i have solved this innermost bracket what i will do is i will take this character back and put it into my stack once again right you will eventually understand what is happening move ahead now you see a closing bracket again right this means we have to calculate things again i will take up elements from the stack i take out xx then i take the next element that is c and then i see a opening bracket right so as soon as i see opening bracket i would remove it so now i know that i have to work upon this string and how many times do i have to repeat it so pop your number stack so this tells me i have to repeat it three times cool so as soon as this is repeated three times you have solved it and you are gonna put it back into your stack right now move ahead again i get the character y right so y will go into my string stack move ahead again i get my closing parenthesis means that you have to solve right so what you are going to do so try doing this as an exercise now what you will do is you will remove all of these elements pop out the opening parenthesis get the number of times you have to repeat it and then simply repeat it so you see we have traversed our entire string and we got a final output so for this case this string will be your eventual output now let us quickly look at the pseudocode and see how all of this actually works in action on the left side of your screen you have the pseudo code to implement the solution and on the right i have a sample string which we will try to iterate through right oh and by the way if you want the complete code and its test cases you can find the link in the description below to my github profile so let us start with our pseudocode what is the first thing that we do first of all we create a number stack and we create a string stack so this number stack is going to store all of my numbers that i encounter and this string stack will store all of the other strings that i get right now i trade through the string in this loop what do we do first of all if we get a number just push this number in your number stack so as soon as i get a number three what i'm gonna just do is i will push this number three in my stack over here now you move ahead what do you do if you get anything other than a closing bracket we were pushing all of that in our string stack right so what will happen is the opening bracket will go in a string stack then i will get a in here next i get the element 2 so 2 will get into your number stack you get a opening bracket again so this opening bracket goes in your string stack then you get a c and then ultimately you are at a closing bracket right as soon as you get a closing bracket what do you start popping from the string stack until you get a opening bracket right so what this will do is it will pop this element c out and then it sees a opening bracket right so this opening bracket will be removed from the stack and then i get the number c and how many times do you have to repeat it you pop a number from the number stack and then you will repeat this string two number of times correct so i get a cc once you have repeated this just push this repeated string back in your string stack so this cc will go back in your string stack right this is how the loop will continue on and it will iterate through each of the character right once it is completed what you are going to do is you will go through your string stack again and you will create the final output string the time complexity of this solution is order of n that is because we are only iterating through the string once and the space complexity of this solution is also order of n that is because you are using up stack spaces to store all of your intermediate strings i hope i was able to simplify the problem and its solution for you as per my final thoughts i just want to say that whenever you see problems around brackets stack data structure is your best friend that is because a stack not only maintains the order in which your elements are appearing but it also allows you to use the latest element that you just got so think about that all of the mathematical problems which have parentheses all of them can be solved using the stack data structure which other problems did you find where you could use this stack data structure so handy what problems did you face did you have any concerns with the solutions that i just offered you tell me everything in the comment section below and i would love to discuss all of them with you would be also glad to know that a text explanation to this problem is also available on the website a pretty handy a pretty handy a pretty handy website to help you out with your programming needs you can find the link in the description below as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where i can simplify programming for you also let me know what you want to learn next i'll be glad to help you out until then see ya
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
518
hello guys welcome to our test learnings today we are going to locate the problem number of 518 which is a coin change - number of 518 which is a coin change - number of 518 which is a coin change - there are two types of problems in the coin change so this is the second one okay so you're given a you're given different denominations of coins and you should make you should see a write a function to compute the number of combinations that make up that amount you may assume that have infinite number of each of kind so you are given a number of coins that these are the denominator so the total sum amount is 5 so what you have to check by using these coins can you make some up to this one or not like how many ways you can make up to this sum so let's say if you take one right you can pick this coin five times which will make some equals to five one that is one way and two twos one that is another way and three ones one two that is another way and one leaf either so there are total five waves as it is shown here so what you can do if we if you think about the brute force approach right so it you have to check all the combinations with one with two with one with five with 1 2 with 1 5 with 1 2 5 all the combinations check whether the sum is equals to 5 or not so first we will implement the brute force algorithm so we will check what we will do first we will pick one to the solution and without picking the 1 so total we sum up both the result set and check whether the sum is equals to 5 or not so let's do that let me write one recursive solution which is DFS coins let's see the brute force algorithm first and after that we will see how to do the same thing in the dynamic programming okay coins and so this will return an integer we can get in helper function here this is an array of coins and a day of going let me put a set and this is the length and this is the total sum amount so if what I am doing whatever I pick right then whatever the coin I'll pick I will remove that coin amount from that sum of amount so one that means whenever it becomes 0 then I 1 I want to return so I am equal to 0 then return 1 if that is one condition and youth if n is less than zero which means let's say you pick amount five and you're subtracting five which is zero and again if you subtract zero minus 2 which is minus two so that condition I am checking if it is 0 then return 0 then don't calculate that as and the boundary condition if M less than or equal to 0 and then also return 0 because we cannot go beyond the zero right that's down so now return include sum up when it is include when it is not include when it is included means M minus when it is not included M minus 1 which means the length will be reduced to 1 we are not including and if you are not including some will not be change right so let's say you are not including 1 some will be remain same now the other case if you are including this one right so if you are including me the length will be same and here from the Sun let's say if you're including one once it should be removed from the total amount 5 so the total amount yes of M minus 1 guys so if you understand right when we are counting when it is included which means let's say 1 is in it is accepted burnt when I submit let's try submitting it's a time limit exceeded the reason being this is a tree right like when you are taking all possible scenarios all possible cases so in that case what is happening the time complexity is going to be the order of 2 power n which is exponential you are unnecessarily checking what you are checking is let's say you have a set right you are taking it for like 1 to 5 you check for all the cases of 1 without including two and five with including to one side all the cases so let's look at the dynamic programming solution now so let me explain in the excel I have already drawn something here ok so the dynamic approach dynamic programming approach is here assume this is the amount total amount 0 1 2 3 4 5 and these are the coins that it's given in the example 1 2 5 right so when you include this 2 to sum up to 0 what will be the value when you include 1 if the sum is 1 then what will be the value if you include 1 if you want to sum up to 2 then what is the value so that if we fill this table then we can easily achieve without order of 2 to power and like with order of M into n we can easily hu the thing you understand here why we are doing it here if you look at that the previous solution it is a tree right so exponential tree so there you are unnecessarily processing though for one of the combination you processed already but still again you are going to process in and just scenario in another combination but here if you have already processed something that result you can store it here in the table and get that result back and then populated to calculate the another set of combination right so here let's see here I'll take I and this is Z and these are the ammo these are the coins denominations and these are the ones that total amount so now see to get some 0 do you have to include you don't have to dependent on one right do you choose or not you don't have to dependent and 1/2 sum of 0 no let's fill all these are 1/2 sum of 0 no let's fill all these are 1/2 sum of 0 no let's fill all these are one because some is already 0 whether you're choosing or not choosing that doesn't matter at all so this is one no so to this one when you pick one and to make someone to make to sum up to one what you have to do you have to yeah by looking at these by picking up one you can easily tell that ok with one I can make up some 1 and 2 1 3 1 4 1 which means yes you can make up with one coil 1 2 coins you can make 2 3 1 coins you can make 3 but the formula here what you need to understand the problem of the formula here the way we discussed earlier right if pick is picked if it's big then we have to remove from the Sun right the pig Delmond should be removed when it is not picked if it is not paid just take the trivial solution so right yeah so if you look at here when one is picked then what you have to do you have to remove from the Sun that one minus 1 which is zero so coins of zero is what this is one so like when you are processing the one when you want to pick the one this is the first element you don't have anything else in your hand so that's why is zero when it is not picked zero and when it is paid pick this and remove it from the some one minus one zero so coins of zero is what 1 so 0 plus 1 is 1 this is the 1 here so now you are picking one so remove it from the some 2 minus 1 it is 1 so coins of 1 is 1 0 plus 1 that's again one it's the same for all because we know it is 1 it is always 1 so coming to this one right so 2 to 0 it's already calculated 1 right so can you make sum up to 1 with coin fittings up to know right but how do you calculate it so let's say you are picking one before that you already have coin 1 you should also process that also right yes alone with 2 you cannot make some one but other coin is already picked up the other coin is already there in our solution set which is 1 so which means we again have to follow the formula if it is picked and if it is not picked if it is not paid just simply take the previous value this one because we have already processed if you are not picking what else is left one is left when one is left can you make some up to one yes which says yes then you do that right one this simple whenever the sum is less than the Bitcoin then you take the previous value why we are taking the previous value because if you are if you're not if you're picking or not picking but you already processed the coin one so that's the reason so here also the same now look at here so now you are trying to pick up coin too right when you are picking up coin too you have to remove it from this one two minus two zero and coins of zero is what one and when if you are not picking up what is left one left and when you have only one coin can you make up some - yes so what is the value the up some - yes so what is the value the up some - yes so what is the value the previous value that is one which is equals to 2 the same - 3 - 2 1 points of equals to 2 the same - 3 - 2 1 points of equals to 2 the same - 3 - 2 1 points of 1 plus the previous value 1 2 4 minus 2 coins of 2 - 2 plus the minus 2 coins of 2 - 2 plus the minus 2 coins of 2 - 2 plus the previous value train right now 5 minus 2 3 right the coins of 3 value 2 plus previous value 1 train right so now 5 minus 1 minus 5 here since the sum is lesser than this one you don't have to pick this one if you don't pick this one what is left till here whatever you picked up that you have to put here 1 now game the sum is lesser than the coin then you have to pick whatever you picked so far here like coins one and two together to make up some - is what - two together to make up some - is what - two together to make up some - is what - then put that here and here five is also a less than is greater than three simply pick up the previous value and five is again greater than the four simply pick up the last engine now five is not greater than it is equal so if you pick this one you have to deduct from the some 5 - 5 0 right the coins of 0 is some 5 - 5 0 right the coins of 0 is some 5 - 5 0 right the coins of 0 is what which means what then you're subtracting 5 - 5 which will then you're subtracting 5 - 5 which will then you're subtracting 5 - 5 which will become 0 to make 0 some what is the value it is 1 so 1 plus the previous value 3 4 so when we write that formula you will understand if you don't understand that's ok when we write that formula then you will understand easily so let's write that here all right ok so we need one result set we call it as DP two-dimensional set we call it as DP two-dimensional set we call it as DP two-dimensional array which is of M and n the total if you look at here this is and this is M why this is n because if we have the amount is 15 we will have 15 columns here the total number of coins so int TP equals 2 constant and here the amount we will take one extra because we will start from one to four loops right so this is four one four loop and this is for another four loop so let's I equal to zero Alice type also coins to event I plus place it's now another for loop int J equal to 0 J less than or equal to among this time its amount I plus press sorry J press place right so what we have to do as we discussed here if whenever the J equals to 0 filled with ones if J equals to 0 J equal to 0 V P of I J equal to 1 else won't we have to do yells else what we have to do if the condition what we've discussed if you look at here let's say 5 whenever the sum is greater than sorry the coin value is greater than this one then simply pick the previous one if J right in this case J is the amount here if J is greater than 2 sorry if coins of J is greater than today right like this if v is than zero then simply pick the previous value which is of coins of I minus one comma J so let's program DP of I to J is equal to points of I minus 1 the previous value right J here we need to actually what we have to do is this is fine but one condition we need to check whenever if it is if I minus 1 less than 0 right and else is what this case let's say 2 is greater than this one is not so if it is not that less than then what we have to do pick you are picking subtract it from the some value to minus 2 0 and what is the her processed already processed value of this row of 0 1 right so let's take the same thing controls what we have to do this value plus pick value right when it is picked when it is not pick when it is speak you have to - not pick when it is speak you have to - not pick when it is speak you have to - it from this value and store it and when it is not picked then you take the previous value is the same I minus J plus coins here I will be the same one and j- you here I will be the same one and j- you here I will be the same one and j- you have two data points of some - it's have two data points of some - it's have two data points of some - it's actually beeping coins of I right so this is again DP result type in DP so if it equals if I less than equal to zero that's it now DP don't coins lengths amount so yeah I just made it this one if you look at here if the coin the value the coin value is greater than the amount then we are simply taking the previous value this value we are taking right if it is greater than we are simply taking yells what we are doing if it is not greater than then previous value which means it is not picked and when it is picked you subtract from the sum amount and whatever it is processed before and pick that value right so this is the let's try the moon yes it's working let me show you like how to put it here controls how that is being shown here yeah so this is how it is being calculated exactly if you look at mine this one exactly this is the table which is calculated you understand when it is peak then it is not paid if it is picked and then if it is picked then remove that picked coin from the sum of amount so the value you must have already processed before and picked that value that's it okay so on time complexity for this one order of
Coin Change II
coin-change-2
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`. You may assume that you have an infinite number of each kind of coin. The answer is **guaranteed** to fit into a signed **32-bit** integer. **Example 1:** **Input:** amount = 5, coins = \[1,2,5\] **Output:** 4 **Explanation:** there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 **Example 2:** **Input:** amount = 3, coins = \[2\] **Output:** 0 **Explanation:** the amount of 3 cannot be made up just with coins of 2. **Example 3:** **Input:** amount = 10, coins = \[10\] **Output:** 1 **Constraints:** * `1 <= coins.length <= 300` * `1 <= coins[i] <= 5000` * All the values of `coins` are **unique**. * `0 <= amount <= 5000`
null
Array,Dynamic Programming
Medium
1393
6
in this video we'll be going over zig-zag conversion so the string zig-zag conversion so the string zig-zag conversion so the string is written in a zigzag pattern on a given number of rows so in this case we're given three rows and then we are trying to write this string into a zigzag pattern so we have p a y and a p a and then l i s h i r i n g which is the input string and then we're trying to concatenate them together five rows and then we have p a h which is the first row and then we have a-p-l-s-i-i-g a-p-l-s-i-i-g a-p-l-s-i-i-g which is the next row and then the last row y-i-r the last three characters y-i-r the last three characters y-i-r the last three characters so let's go over the process we will need a way to store the characters associated with each row we can create an array of string builders to keep track of the characters in each row then the indices of the array will determine the row we are currently on we will need a way to indicate our current location or our current row inside the input string or our current row and also the current direction we are at when our current row where our current road is equal to the first row or the last row we will need to change directions we can indicate our direction as follows so if our direction is equal to one that means we're moving downward and if our direction is negative one that means we're moving upward so for example we have roll plus direction that means we're moving downward or we have roll minus direction that means we're moving upward now let's go over the pseudo code so let's validate the input parameter if num rows is equal to one then we do not need to form our zigzag pattern we're going to return the string itself and then we're going to create an array of string builders we're going to call sps string builders so the indices represents row the values represents the characters at a row then we're going to create two variables we're going to create r is our current row initially zero and also the direction our current direction initially zero initially we have just have a starting point and then we'll change our direction inside loop then we're gonna iterate do the character do the indices of s denoted as i then retrieve the current character c at index i we're going to increment row by direction that means moving towards the direction we can see that initially we do not move down so we're going to stay at the first character for now then we're going to up um append c to the string builder at the current row now we're going to start changing directions if row is equal to zero that means we need to change directions or row is at the last row we also need to change direction so it's equal to num rows minus one is one if row is equal to zero no not row if direction is equal to zero that means we need to move downward we need our directions to start moving downward so i'm going to set direction to 1. else we're going to set direction to negative direction basically we have we're currently moving downward so we're currently at one if we're moving down we want to switch our direction to moving upward so we should switch it to negative one or if we're currently moving upward we want to move downward again so we want to change it to positive one now we are going to convert the rate of string builders to a single string and we'll create a string builder results i'm going to iterate to the of radio stream builders and then append the string representation of the string builder to results and then we're going to return a the string representation result now let's go over to time and space complexity so the time complexity is equal to let's go to all n plus o n where n is the length of the input string actually we can do okay and k is the number of rows our first oven is visit each character once to allow them to put into the each row of string builders and of k is converting a ray of string builders to results to the resulting string space complexity is equal to of n plus of n it ends the line for input string and of n is the array of string builders because the characters inside the string builders matters and then we have of n is the resulting string slope string now let's go over the code we'll first validate our input parameter let's go to one then we return the string itself if there's only one row we don't need to convert it then we're going to create an array of string builders the scene number of the number of rows and then we'll keep track of current row and our current direction then we iterate through the indices of the input string actually one more thing we need to do is we need to iterate through our array to initialize each of them because we're going to get no pointer exception we do not initialize our string builders before we iterate through them now whenever iterate through the characters of the input string retrieve the current character index i and then move our row toward the direction that we're currently in and then we're going to append the current character to the string builder at the current row and then if row is equal to zero or row is at the last row we need to change our direction so if our direction is equal to zero then we want to change it to one we want to start moving downward elsewhere we just want to change the direction to the negative direction then we're going to return we're going to convert our stringbuilders to the resulting string iterate due to the strength builders of the at the individual rows append the string builder to the results and we will return the resulting string let me know if any questions in the comment section below you
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
237
hey everybody this is Larry this is day two of the June decode daily challenge hope everyone's thinks safe hope everyone's staying healthy and you know make sure you find a place to love someone in your life let's get to prom - someone in your life let's get to prom - someone in your life let's get to prom - delete node in the linked list write a function to delete a node except a tail in a singly linked list given only access to that node given like this which looks like this we will move five and then you can go okay so there might be a double there and now we turn anything they give and to another the tail okay I meant to think that I would think about in this case is it's what happens when you remove two head I think every other case it is probably mostly okay and Dad you just have to do some checking don't think this worried yet already have two elements but it doesn't seem like it does say anything about the head so yeah and we could kind of test them but only because we're cheating half and conquer but we're just here to learn so it's okay but let's just see what the expected answer is or whether that's even valid input mummy we turn we moved ahead and we moved ahead what should we return it so that is to expect it and so and that's okay oh I forgot to change to a second well at least that's the expected answer we just have to be really careful about what that means right because in that case this is a really weird problem setting because in that case we want to our head would still be our head node is stilled in the head node because we're giving the head that's called his head just to kind of make it clear but here we want to change the value so I think there are only two cases in that case that is wait well am I missing the input I mean we sat there sigh when I'm missing some understanding duh where's their head input am I missing something I'm just trying to right now it well the first thing I would say is that this is a very weird poor question in a sense that I don't know what so notice to note that we want to remove but we're not giving the head alright okay I see what it's saying kind of so this is a I kind of it would take a little bit time to understand you should they're a little bit clearer but maybe it is actually sufficiently clear it's just I text my head to wrap around what the problem is actually asking considering that it feels a little under specific high but it's actually enough to do what you need but it's just that it's a little bit weird but there might be a way I weight depends on how you want to call it delete because ideally for length less and link this nowadays has become more rich for your thing but because I don't know it just doesn't come up that much in real life but what we want if I said we're giving a deck then we could want to know dot we would do something like no dot previous done next is you go to note onyx something roughly like that so that the previous/next skips this way so that the previous/next skips this way so that the previous/next skips this way so now what we want to do and it's a little bit sketchy is what I would like to do is do something like we don't actually change the node we just shift everything from the right side up one so the way to do that in theory if we just know dot Rio is you go to know that next time while you but we do something like wow no dot next is not none then and that's pretty much it well notice you go to no time next maybe and now that no time Nexus none so we actually have to add some other additional gating but basically what we want to do is let's say we have just given linked lists that output in a wave phone and we're only giving them pointers here then what we want to do is just shift this by saying just to one we move the pointer set this to nine and that's way and just we move to that next way so that's basically what the striatum I'm going to do or I already started to load on but there are some edge cases so next is you go next time next kind of this is mostly maybe right but this is the thing where we now remove the last element right but that's for some visualization that's one just to kind of see and that's just cheap oh that's true that's an intelligent that won't be removing the last element I just remember that but here we don't what we have to do is we have to set to note that is before the last note to none right so we have to do something like if no dot next this is none and this is before we said it you know that nexus none then we've one is set okay so in this case note that next is not going to be none what we want is with no doubt next time Nexus none then no dot Nexus you go to none someone like that and then that should be good except for that this would give you an hour so they just do else yeah so that looks pretty good I think that's really most of the cases right what I was are there when you can't do the only other case would be the tail but which it tells you that it won't so let's give it a go let's try the two element case for us actually still should be okay but it is an edge case okay so that looks good too let's submit okay so that's pretty much it you can write this in a little bit in a couple of different ways obviously but you know but the idea is still just making sure you have your edge cases I don't think you can do better than this and what is the complexity it's just it's a little bit new ones you have to define your wearables markers L is so maybe it's just over L where L is the number of notes in the entire linked list maybe or like this kind of suffix of don't know that you pass in because recommend no contacts at their thickness but in the worst case I'll be O of n where n is the number of notes in the list if we do not use extra space other than the ones that are passed in and so it's all one extra space divided anyone define it again in place stuff is so tricky but with like this any thoughts more understandable because in general you want to do stuff that's in place though the way that we did this album isn't really a deletion so and it's not really a really unlink this operation because in general delete note should be O of one yeah I think that so I have listen I'm a good citizen it's an interview question as more of a brain teaser to review but probably not that much for comparative programming but still you know it's just about being careful of your edge cases is what this forum asks you to do all right I'm which it's actually double check the solution we've got here so then we can learn together in case that's not the case swap with next node okay so you came to the solve one by pointing you should delete up Nova is to modify the next Sunday yeah that's what I was thinking so since we don't do that Wow hmm okay I guess I accept that is cute I would not have done this one clearly this is the one solution but basically what is saying is that instead of so base a my strategy was just you know something like this and then you go from you want to be move to five so what is saying is we delete the we how do we say it hmm but yeah we said basically we shift one over and then we delete the one so then just gets deleted and the districts points there that's actually a more clever way than what I did it and that would also be or one complexity so that's way smaller and reason why you can do that is because one of the constraints saying that you cannot or you do not remove the tail so that's okay because otherwise that just strategy would not work um okay I mean I guess it is what it is sorry of my video today is not as uh whatever but there's a lot of things going on the well hope everyone said okay I won't say safe let me know what you think let me know if you find all of one solution I think for me maybe you could see in India but this is a lot of brain teasers allowed trivia I'm not a fan of it and it's just like hey here's this thing where like as an interviewer I probably would never give this problem just because this doesn't really test enough of what I would expect a candidate to demonstrate except for like random I don't know I guess there was some problem solving in some way in the novel way but I don't know maybe I'm just not a fan of it but yeah but that is definitely a clever solution so yeah cool that's right for this problem stay safe stay healthy and yeah bye everybody
Delete Node in a Linked List
delete-node-in-a-linked-list
There is a singly-linked list `head` and we want to delete a node `node` in it. You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`. All the values of the linked list are **unique**, and it is guaranteed that the given node `node` is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: * The value of the given node should not exist in the linked list. * The number of nodes in the linked list should decrease by one. * All the values before `node` should be in the same order. * All the values after `node` should be in the same order. **Custom testing:** * For the input, you should provide the entire linked list `head` and the node to be given `node`. `node` should not be the last node of the list and should be an actual node in the list. * We will build the linked list and pass the node to your function. * The output will be the entire list after calling your function. **Example 1:** **Input:** head = \[4,5,1,9\], node = 5 **Output:** \[4,1,9\] **Explanation:** You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. **Example 2:** **Input:** head = \[4,5,1,9\], node = 1 **Output:** \[4,5,9\] **Explanation:** You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. **Constraints:** * The number of the nodes in the given list is in the range `[2, 1000]`. * `-1000 <= Node.val <= 1000` * The value of each node in the list is **unique**. * The `node` to be deleted is **in the list** and is **not a tail** node.
null
Linked List
Easy
203
1,710
Hello Everyone Welcome back to my channel I am going to discuss the next problem in which the problem is maximum units and ginger ok so what we have to do in this problem is boxing and in this we have a particular type of boxes on the index. How many numbers are given and can be put in that type of box and it is of that size, so we can see which one to put in, then let's see how we will approach this problem of missing the first test match, so let's see first. What we have to do is, first of all, we have made it a person of liquid today, it is given in which there is a zero index, this is the zero index, on it we have the number of box in check in number option, as many of a particular type. How many units can be put in a box of this type on the quality index, that is correct and we have to tell what is the maximum units that we can put and given the truck size, we can put more boxes in it. We can put our trucks if we have tractors, then we can keep the maximum return, so let's see how we will solve the problem that if you think carefully, this is something that Sachin has done till now, it will seem like because look what we get in the end. In that we have given the weight and value and we have the total capacity and don't tell us what is the maximum value we can put. You are fixed on the side more than the total capacity. Increase 9 means rate in that. So wherever something similar is the right thing then total truck. The size is given to us here, the number of the box should be easy, here the units inside it are given, okay, it looks something like that, so we have seen that I am meeting you, okay, but now look at it like this. And one is I have unwanted and one is I have fractional app ok now post the video and think who is getting this question these days see let's make it what can we do Either we take the item or we don't take it, meaning if we take Puri then we can get the experience. Either we take Puri or we can't take Puri. So here we see whether it will be suitable for us. Okay, let's understand the example and then decide which one is suitable. If we are attracted then first of all we will do this according to the maximum first of all in which it will be like by keeping this total below only the total here, we will do this according to the person we have given this. We will gift according to the units of the person who is going to give the gift in this decreasing order from maximum to minimum. Okay, so it is already sorted here. Okay, so this will be set up first, what will we do about that and after that we will first We will start our look, we will come to this, we will see that our truck size is four right now and here how many boxes of this type are there, if only one can be returned, we can put it in a cotton truck, so if we put it in one box, on tricks. If you smoke cigarettes, now it will be degrading and our value, our total value, how expensive is it, did we put a box in it in which we could free them? 123 One, this has become the strategy of our valley, now we have taken it forward that now we here in this The type of copper in this is of this type and we can put it in this and we can put ours so this one and our total how many will we take, we are putting two boxes and how many minutes can come in one box two 123 After studying, first of all our per unit student off and these baniyas are fine, now after that we moved on to the next box from here till we reached 13 boxing patwari, so see that means our growth capacity is higher than the number of offices of this type given here. It is less, it is okay, that means we can put it in all the three meters, we can put some parts, carefully, we can put some text in both of them, that is, we can put in contact only once in these three boxings, that is, the activated one book key is okay, that is. That we will take one of these and how many quintals are fixed in one box, so the seventh was the first warning that sir, you can put it in our maximum unit that I have come here, so now you see, now you will know which one is here. The drama is liberation, we have three big rivers, unwanted and in the section, why is it looking obscene here, because we look here, we have found something here, we have talked to each other, who comes here, who raises the alarm, so first of all, what should we do, let us soften. Okay, if we want to fold, then this unit will be given because we will take only those offices first whose units can be put in a box to give us maximum sunlight, so see, first of all, this one will go from 10, okay, then after that, this one here will have nine. If you can add then this will come and then the intake one will go and then it will come that this one is a chicken in a fight so now here we decorate total how many of our units come initial total unit opposition okay we start from here What happened was that we saw that the current number of boxes of this type is final and less than the capacity on our side, that is, we could have put all the boxes in this truck, so we put all the boxes in this truck. If 25 are loyal then the truck will be reduced back. Time - half then the truck will be reduced back. Time - half then the truck will be reduced back. Time - half inch and our unit's became that universe mare became five put boxing and how many minutes are there in a box 10 top five entertain so this mare became unique holiday okay so put it in and what we did now Now look at the number of returns here and the three which are less than our progress capacity, we can enter all these return boxes, so if all these boxes are entered then the shifts of our factory units will become plus from before. How many boxes are poisonous and how many minutes can come in a box? North is so it became some 27th that is that our it became with consent is okay no total unison consumption is that now what has been done has moved forward is a pun is now Look, in this box, how many times can a person put 4 which are less than our breast size, that is, we can put all these and then what we did here we took the truck size, first we took 5 pockets, then here we went to 3, so we reduced here. Had to do it here, when I took boxing, then these trucks were parked, you are the Medical Minister, you are fine and now when we came here, what we saw was that for watching is fine but our progress was then such t-shirt came fine but our progress was then such t-shirt came fine but our progress was then such t-shirt came i.e. in charge only. If they could, then i.e. in charge only. If they could, then i.e. in charge only. If they could, then what did we do out of these four? What do we do when our current boxes exceed the capacity of our truck? We just wrote down the inboxes of the truck size, so how many boxes are there including the truck * How many units can come with it? If you want, are there including the truck * How many units can come with it? If you want, are there including the truck * How many units can come with it? If you want, then how much Fortnite was killed in 727 and it remained our zero because we have 2 boxes for it and here our right is 91st, so here when our people will be finished, our people were finished in two conditions, either Our Aai has become till the last i.e. Aai Mara will run till the Aai Mara will i.e. Aai Mara will run till the Aai Mara will i.e. Aai Mara will run till the Aai Mara will take us which is lighter brother or else as a condition that as long as our truck pile is greater than zero people keep driving. When they mean daily and then can enter the option whether to cut or not, both of them reach our collection and understand the algorithm and see it. It is very easy. So what we thought first of all in the chord is that we will do these flats first, this ballia toe tune which Amrit will do then took on a hybrid which we will type every box okay and then I called soft this bauxite face put compare function what are doing in the compare function two people will then take the argument because this vector will be typed and we What will we send, what will we take, see here we will send this compare function and this also this person will be in so this should be so you write how you wrote and it will fold and give us according to the units in decreasing order then what will we do We will apply the boil, we had seen two conditions, these two conditions are fine as long as the size is within the hero end, till the size of our I have lots of, take it like this, if our current boxes, which is fine, it is less than our truck side, that is, as it was here. When there was a five, it is on the size side of us and it is less than that, so we could take the whole five boxing, so we will take the whole face boxes and multiply them by the value of the total unit, we will add it to the total unit and the truck. We have to use the same number of boxes and the size as we have here, like ours here, our capacity on the fourth, our capacity is the only number that Aaj Tak channel has said that we will go to Chikni Chameli and what will we do. Hmm, how many can we take? Can cover it and return from the truck side - either I return from the truck side - either I return from the truck side - either I can take G-20 or I can write like this can take G-20 or I can write like this can take G-20 or I can write like this A total unit will have as many boxes so * whatever is the current units whatever so * whatever is the current units whatever so * whatever is the current units whatever is the point at which How much effort should we put into it, this will give our total unit head and will keep on giving us plus every time and lastly if we keep American in hotels then it is very simple with file optional subject is Giridih process and our time complexity of it will come how to append login by using shifting. There are 30 more, I don't think we have used this Tulsi by chance, this paste is the same as the conference. If you liked the previous video then please comment and like it for improvement. Please subscribe and in the next video.
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
147
hey everyone welcome back and today we'll be doing another lead code problem 147 insertion short list this is a medium one given the head of the single linked list we just have to perform an insertion sort to it and sort the list in a sending order and then return the head so that's straightforward so we will be having a dummy node which will be having value 0 and will be pointing to the Head a previous pointer and a current pointer so previous will be at head and current will be a one node ahead of previous so we can just say it like head dot next and while current is not null we will say if we have to do some pointer manipulation so we will check if the value at current if it is greater or equal to previous dot well then we know we do not have to do anything because the values are in place so we will just say continue but before that we have to update our pointer so previous and current will be updated so previous will be at the place of current and current will be current dot next okay so if it is not the case we will say we have to find our insertion point insertion will be starting from dummy because there can be a node where we have to insert It to the Head so we will say we have to find our insertion point so if the current dot well if it is greater than insert dot next dot well because we want to be one node behind the insertion node so we have to just update our insertion node so insert pointer so insert will be equal to insert dot next now if you find the insertion point we will say previous dot next should point to current dot next and current dot next should point to insert.next and insert.next and insert.next and should point to current should point to current should point to current and after that we have to update our current so current will be equal to previous dot next because the current dot next is going to be on the previous dot next and that's it after doing that we can just return dummy dot next because dummy dot next is going to be the head so that's it let's see if this works and then I will explain how this is going to work okay suppose we are going to have a link list like this 4 and then 383 will be pointing to null and we have we are going to have our previous to the head that is going to be 2 and is that is going to be 2 and is that is going to be 2 and is going to be the current so now we will check do we have to do some pointer manipulation uh this if statement will not be executed because the current dot value is not equal or greater than the previous dot valve so we will have an insert pointer which will be at dummy so the current dot well is greater than insert.next dot well this is not insert.next dot well this is not insert.next dot well this is not the case because current value is 1 and on the dot next of insert we are going to have two we have found the insertion point which was the first node obviously so we have to do it for uh remove this one and add it to the first node obviously we are going to add it to the head the previous dot next should point to current dot next 2 will be pointing to 4 and current dot next should point to so one will be pointing to so one will be pointing to so one will be pointing to two and should point to current D and should point to current D and should point to current D will be this I will be pointing to current and current will be updated to so previous dot next we so previous dot next we so previous dot next we know that it is going to be it was at 2 we already made the connection the link so current will be at 4 now we are going to the next iteration because current is not null we will see that value at current is greater than the previous value so we do not have to do anything we will continue to the next iteration now here we see that we have value at current less than previous so we will have our pointer again at insert will all will be again at dummy will find the insertion point so I will be at the first node we will see insert.next that value no it is greater insert.next that value no it is greater insert.next that value no it is greater so it's greater than 1 we will update it again it is greater than 2 we will update it again but here we are not going to update it why because the next dot well the insert is at 2 its next dot value is going to be 4 it is not greater than 3 is not greater than it so we will obviously find uh have found our insertion point so we will just repeat the process again previous dot next is equal to current dot next which will be just this and current dot next 3 will be pointing to 4 and now we have to just make this link between two and three so we will say should have current and should have current and should have current and current should be updated to previous dot next so previous dot next was going to be null and current is going to be null and then we can just return dummy dot next which will be the head so that's it
Insertion Sort List
insertion-sort-list
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_. The steps of the **insertion sort** algorithm: 1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list. 2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there. 3. It repeats until no input elements remain. The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration. **Example 1:** **Input:** head = \[4,2,1,3\] **Output:** \[1,2,3,4\] **Example 2:** **Input:** head = \[-1,5,3,4,0\] **Output:** \[-1,0,3,4,5\] **Constraints:** * The number of nodes in the list is in the range `[1, 5000]`. * `-5000 <= Node.val <= 5000`
null
Linked List,Sorting
Medium
148,850
111
hey everyone today we will be doing another lead for one minimum depth of the binary tree easy problem this is uh we have already done the maximum depth of the binary tree uh this is much easier than that was a bit complicated but in this problem given a binary tree find its minimum depth the minimum depth is the number of nodes along the shortest path from the node down to the nearest leaf path so in this condition and the leaf node is a node where there is no right or left no children so you can say in this condition uh example number one we have three and nine this will be our we can say closest path and the distance will be two that if what was it depth the depth will be two because the root note will be considering as one and at each level we will just add one we have done the maximum depth of the binary tree or something like that you can see that also if you want to but this in this we will just consider the base case yeah if the base case is nor if the if there is no root to begin with we will just return 0 because there is no root there is no height and when then we will check to the left and check to the right so on we have another case in which there is no left or right for example we in the case of nine we will just return one because this is our leaf node and on the other case in the case in which we do have our left and do have our right we will just take the minimum of these two like in this case you can see that we will be taking the minimum path so we will just use the minimum and also what if we have a root on the right left but not on the right so you can see if this nine has another children 10 or if this 15 was not there we will just be adding one because we do not care if it is our if there is any uh left node or right nodes simultaneously like one parent have a left node and the right node if there is one we will just add one because it means that it does have its own level and it's on in its own level and its level should be incremented by one uh when we are considering the whole left hole for the whole right i hope this makes sense for example i will try to give another example like if there was no 7 and 15 here or if there was a 15 here but not the 7 the depth is three regardless if there is seven or not and same goes for the five the depth is still uh three uh regardless if there is 15 and same with nine it did not care if there is nine in or not the depth will be three so that's it now we will check our base condition if there is no root to begin with we will just return zero and if there is no root left and not root right they both are null we have our leaf node so to leave node we will just return 5 and what if we have our root not root on the left but we have our we will check for the left first so if there is we have and a right there is no right route for to give an example uh we will be starting our base condition so what if we do not have something on the left but we do have something on the right so we will left we will go to the left and root left is still there we will just call recursively by adding one and calling the function itself again by and now this time passing it minimum depth e t h passing it the root left because we only have our root left and the root left is not there and if there is root right the same the opposite case if there is no left but there is right if there is no right but there is left i explained it earlier how will be incrementing them and because we do not care if there is a left but there is a right we will just increment it and pass it to the function again self dot minimum apd so now we'll passing it root and right after that we have our most common condition base not the base condition but what if we have a root to the left and root to the right we will just add one because the one will be our root condition because obviously if there is no root we will return zero but if it does not execute then obviously we have a root we will just increment it and uh self we will call the function again passing it our rule to the left and after that we will pass it our blue to the right and this is it so we will be taking the minimum because for example we have passed the route we have 9 and 29 has one to its depth and this whole tree has two to its whole depth so we'll be taking nine and adding one so it will give just give us one uh just give us two for example in the base case in our given example we have one here and the left on the left you can see there is nine so we will be returning nine and on the right we have two uh another subtree you can say so we'll take minimum and add it to the one and so we'll be getting 2 will be the minimum path as you can see and that's it that was our whole code now let's see if there are any errors there are no errors and that's 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
412
how's it going guys so today we're going to solve the one of the coolest question this question deserves like this is the easiest question so if you did not able to solve then don't worry i'm over here to help you guys to solve this question okay so what we're going to do in this question so basically uh we have given something like an um array okay we have to divide that like we have like oh no sorry my mistake my bad we have given our number we have to divide it and put into the area the result okay so for example like we get n equals to 15 okay so we have to divide it by using three and five so if this is divided by 3 and give us 0 then it means this is fizz as per the question this is phase okay and if this is divided by 5 and gives us 0 then it is buzz and if this is divided by both if it is able to divide by both then we just simply add this together like we will just put give the reason fizz buzz like that okay so if you look and the this one so after 14 15 is facebook so now you're saying like dude why 13 or 14 are like just uh getting those things so like which one is no none of the above conditions are true then we simply put that into our string okay just simply put into the strings so if we just do it with a very simple approach we don't have to do anything very uh in mindfully anything note like that so we simply do it so first of all what i will do i will create my result array list where i will store my result okay and this will be a of string one so that's a string and my result new array list okay and now i will return it my result as well because things will handle over here okay so now what i will do i will simply run and for loop from i equals to 1 till i less than equals to n i plus okay now here's the deal come i will say if i modulus 3 is 0 and i will say i more or less 5 is 0 then what i will do i'll simply say result don't add our uh facebook all right guys i hope this thing is straight later crystal here elsie let's say as if it is only divided by let's say three okay then i will say this is only face result n okay else if i will say it is only divided by let's say five never mind and is zero and i will simply say okay it's buzz only so i will put over here result add bus sorry about that so like my mom's come over here so like i just have to cut that part so all right anyways let's move further so okay now the final condition comes else what if i say uh as i will say like dude i will say like if they are not divisible i don't know where mine i said if they are not divisible then i will just simply result add i will say uh i have to convert into the string so i there is a inbuilt function integer dot to a string and we put i over here and we just did it into very few lines so let me just run this code yeah okay now let me just submit it you will see we done like 99.63 faster and our memory is done like 99.63 faster and our memory is done like 99.63 faster and our memory is 96.70 faster okay guys 96.70 faster okay guys 96.70 faster okay guys now you um time compresses him oh and oven okay we were like we are not using any extra space we are just running by the loop only one time okay now here the things come what if your interviewer say dude you don't have to use inbuilt function so how you gonna do like in the end one till over here everything is fine like you are not using any extra inbuilt functions this one is an inbuilt function what you will gonna do instead of this if you know then just do let me know like you figure it out but if it if you don't still then there is one another way we'll just simply say i plus empty spring so we are just concatenating the integer with string so that we're just adding them together okay this thing run similar but you will see a kind of time difference okay so you see the run time is six ms let me just submit it you will see so here we go so run time is five meter second faster and twenty five point three percent guys like i just don't know about this i don't know why there is a time difference between like using an inbuilt function and using this thing so by using the concatenation so just do let me know this thing in the comment section why is that so like i will later on figure it out but i want to know it from you guys so i hope this thing is clear so if you have still lying down then just do let me know in the comment section and i will see you in the next one till then take care bye and i love you guys
Fizz Buzz
fizz-buzz
Given an integer `n`, return _a string array_ `answer` _(**1-indexed**) where_: * `answer[i] == "FizzBuzz "` if `i` is divisible by `3` and `5`. * `answer[i] == "Fizz "` if `i` is divisible by `3`. * `answer[i] == "Buzz "` if `i` is divisible by `5`. * `answer[i] == i` (as a string) if none of the above conditions are true. **Example 1:** **Input:** n = 3 **Output:** \["1","2","Fizz"\] **Example 2:** **Input:** n = 5 **Output:** \["1","2","Fizz","4","Buzz"\] **Example 3:** **Input:** n = 15 **Output:** \["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"\] **Constraints:** * `1 <= n <= 104`
null
Math,String,Simulation
Easy
1316
93
hey guys next is a third Bob Bradley code restoring IP address given a string can't anyone reading it we sorted by returning all possible valid IP and gas companies for example given two by two five one two five we have two ways of people dancing days as a nice idea so we follow the brim and do it similar do you know every problem we have done before first to create a return variable now we have to check if s dot length is greater than 15 then return false gonna have our IP with more than 15 characters otherwise we'll have an int will have a string IP with equal to an empty string and then we have a helper function to which in pass the result the string s I see the start which should be 0 here and n this will be four words that seem enough return result factor then we'll have a void helper function we will define the signature these inside meter will be impossible swing as string IP in of in such and int and now if enmity will equal to zero then if a short length plus three is equal to IP dot length then and simply go to girl then add h2 of planet IP to it and return house I'll have a bottle but in ties it will be stock is less than that - full and highest smaller than that - full and highest smaller than that - full and highest smaller than s godmen one conclusion I guess the night is that if is valid s dot substring start comma hi - one would be sign up okay one over one more Beckett now select show a valid then if start is equal be equal to 0 then IB is equal to IC such simply IP is equal to s dot stop spring that comma zero so start fama what else we'll have IP equal to IP star dot and swing then I fall my helper function wizard ash will be change to ads or something now why would I do that I have the study index so this hellish past I plus 1 now I decide and I'll pass n minus 1 then I have a if condition as if IP dot length is greater or equal to start - oh my - that such one in case there's - oh my - that such one in case there's - oh my - that such one in case there's a decimal if this is a given - is equal a decimal if this is a given - is equal a decimal if this is a given - is equal to IP dot substring and I'm telling it to simply remove last I got minus one characters from this edge and this have IP is to do IP dot substring 0 dot I'm sorry nice length minus I plus dot that's it now let's create the is valid function boolean is valid h-here at the length equal to 0 or F dot M is greater than 3 and return false if s not connected at 0 is equal to 0 then return s dot equals 0 as return sign inferior dot pass and s is greater than zero and indeed that pass and actually smaller than filling 56 let's run the code please explain and fire okay expected strength okay let's run the code again in comparable size sign for okay result okay guys let's submit the code okay thanks for watching guys
Restore IP Addresses
restore-ip-addresses
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros. * For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"192.168@1.1 "` are **invalid** IP addresses. Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order. **Example 1:** **Input:** s = "25525511135 " **Output:** \[ "255.255.11.135 ", "255.255.111.35 "\] **Example 2:** **Input:** s = "0000 " **Output:** \[ "0.0.0.0 "\] **Example 3:** **Input:** s = "101023 " **Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\] **Constraints:** * `1 <= s.length <= 20` * `s` consists of digits only.
null
String,Backtracking
Medium
752
54
hi guys in this video i'm going to go through this league on problem 54 so we are given a matrix we need to return all the elements of the matrix in the spiral order so um this example has a quick illustration so we go from the top left and then when we hit the wall in the change direction when we hit the wall again change the direction when we go up when we're hitting something we have seen before and we change the direction and then we move and then we ended up with a circle at the center and um and this one is very similar but instead of n by n matrix we have an n by m matrix uh there are a number of rows it's not the same as number of columns so this one should work as well so let's dive into the solution and first we need the direction list and what we need is uh so the first direction from zero one so we're basically moving uh horizontally from the left to the right and then next one we're going vertically from the top to the bottom and that's going to be one and zero and then we move uh again horizontally but this time it's from the right to the left so it's gonna be zero negative one and next one is going to be um vertically from the bottom to the up to the top so it's going to be negative one and zero and uh so that's the all the possible directions and we have the uh direction haunter i will show you how i use that later so basically it's pointing which direction we need for each step and then we update that update this guy whenever we hit the wall or we hit something that we had seen before and so we also need a visitor so it's a set so we keep track of what coordinate that we've been seeing we have previously seen so we don't duplicate our work also we know when we need to change the direction for example 4 when we still move up that is something that we have seen before that's why we need to change direction and then we need the number of rows and also number columns and also we need a result and that's pretty much it so oh i also we need a current row and also current column and we at the beginning at the top left coordinate so that's why zero so uh while the length of the visited set this is set is not equal to it's less than from the number points so that means we have not yet seen everything we if this is equal we have seen all the possible one in the matrix and while we are not we have not yet seen all the possible ones we keep doing work doing it doing the work executing what is in the while loop so we have a current direction x and also current direction defined that is not equal to uh in the direction and we have the direction pointer take the modulus of four because we have total four elements in the direction list so whenever we so it allows us to go backward here after we move this direction quantity go back to this one for example uh this one zero one so the point is zero donors one point is two point three when the point is four and take the modulus of four and then go back to the first one and the point is five let me go back to the second one et cetera that's why we needed him to look for and we need the first number in the tuple that's for the x for the y we need to second element so that's how our current direction are triple and also we have to the next and stand for next row and next column that's equal to the current one plus direction and if the next row is between the box keeping the boundary and not hitting any walls for the column also yes the next one is something that we have not seen speed before in that case we update the current position which will be the next one so we are safe to connect the value because we are not hitting any walls and we are not yet we are not into something that we've been seeing before we are not in the same set we're not in a wasted set so that case because we are seeing right now we add it to it also we are collecting the number otherwise that means the next row and next column will be something he either hitting the wall or if he is that's in something that we have visited before if that's the case we have to change the direction right it hits the wall change direction we have seen something before we have changed direction so how can we do that uh this is how uh where the directional product comes into ending so first we have to move backward right because we as the next one is hitting the wall so we have to move back and then we update the pointer this is where we change the direction this direction and after all that but we are missing our one case which is in the top left point because we are already moving in here that's why we move we are missing out this point so how can we do that and it's easy we just actually manually as on as this is only one point okay so also we put in this wasted set um okay so at the end we will return the result let's see oops i think the taco okay works for the test case okay it works so um the time complexity for this uh for this code is uh nr times nc because we're basically executing here um we're looking for all the possible points and for the space complexity we have um also n times m because we have this wasted set to keep track of the other coordinate also with the result list that is collecting all the possible results i mean all the possible numbers within the matrix so this is my solution to this problem 54 spiral matrix this question was quite popular as you can see it was asked by so many companies i hope you like it and hopefully i will see you in the next video thank you
Spiral Matrix
spiral-matrix
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,3,6,9,8,7,4,5\] **Example 2:** **Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\] **Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 10` * `-100 <= matrix[i][j] <= 100`
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row. Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
Array,Matrix,Simulation
Medium
59,921
1,710
hello everyone today we'll solve one of the lead for problem uh where it says uh you are assigned to put some amount of boxes onto the truck uh and you are given a 2d area so this is the 2d array that is given and truck size is four so output should be eight why because uh as the formula uh one box of the first type that contains three unit can go two box of the second type uh which can rest two unit can go and three boxes of the third type that contains one unit each can go so if we'll sum it one into three plus two into two plus one into eight which will be equal to eight similarly for this 2d array our output should be 91. okay and uh there is a condition that yeah you have also been given an integer truck size which is the maximum number of boxes that can be put on the truck so this condition we need to always check so let's try to solve this problem so to solve this uh we have been getting given a array uh first of all i'll sort it so that maximum units on later can be loaded so to do that i'll use arrays dot sort method and i'll use i'll sort box types i'll use lambda function integer compare a1 b1 okay so i have sorted uh the second value now based on the second value because this is the number of units that can go now i will declare two variables and t unit and i'll declare let's just call number of unit and yeah and total box is equal to zero okay now i'll use a for loop to iterate this for and i equal to box types dot length minus 1 i less than i greater than equal to 0 and i minus i'm going from the end because we need to because i have sorted it in the descending order now i'll check total boxes equal to size minus box type i zero if total boxes is greater than box type img then i'll compute something and at the end i'll return number of unit okay here i'll check uh number of unit equal to number of unit plus this formula i have to use so it will be box type i into one okay now uh i need to i have to increase the total number of boxes as well so total number box is equal to total number of boxes plus right here it will be remaining boxes now if it is less than what i'll do there is a change here instead of i 0 because i 0 is greater so remaining boxes into i1 and at end i'll return this number of units so uh i have checked the condition of truck size with this and this logic i have implemented here and why i'm giving a break here because of this truck size which is the maximum number of boxes that can be put so we cannot exceed that okay so uh let's try to run this so there is a wrong answer we have to check what problems we have done here our number affiliates is fine box types bookstop ij okay there is an error here total number of units boxes okay yeah i think i need to remove because this is the sum that i'm using and if this is greater now it should work i guess yeah so that solves the problem so i hope you understood the solution of this liquid problem maximum unit on a truck if you have any question related to this do write in the comment section and if you think the videos are helpful do like the video and subscribe to the channel thank you so much
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
342
Told the doctor to tell the next problem, this whole saree with video subscribe my YouTube channel and share with coat pant comes before Akshaydeep and 10 back blouse number respond 100 subscribe The Subscribe Seervi Subscribe Blue and Influence Over react check veeravati kuru effects on 10th result subscribe to hua tha a movie is launched the compiler is soon looted a text success fully aware computer mode on easily has been accepted your friendship more details that almost 1300 is more than 500 gr Test Cases and Eventually Find a Solution to This 30.22 Personal Problem Special So This 30.22 Personal Problem Special So This 30.22 Personal Problem Special So Friends No Veer Next Problem of Tomorrow Is It Stay Tuned Video Channel Thank You
Power of Four
power-of-four
Given an integer `n`, return _`true` if it is a power of four. Otherwise, return `false`_. An integer `n` is a power of four, if there exists an integer `x` such that `n == 4x`. **Example 1:** **Input:** n = 16 **Output:** true **Example 2:** **Input:** n = 5 **Output:** false **Example 3:** **Input:** n = 1 **Output:** true **Constraints:** * `-231 <= n <= 231 - 1` **Follow up:** Could you solve it without loops/recursion?
null
Math,Bit Manipulation,Recursion
Easy
231,326
219
hello everyone so in this video let us talk about a problem from lead code it's an easy problem the problem name is contain duplicates part two so the problem statement goes like this that you're given an integer array nums and as well as an integer k return true if there are two distinct indexes i and j inside the array because that numbers of i is equal to numbers of j as well as the absolute difference between two indexes is less than equal to k now what it actually means is that you have to find out that whether there's a duplicate of the same number just that the differences of those occurrence of those two numbers the index is different will be less than equal to k so that the difference between those two occurrence has a difference between them that the index difference between them should be less than equal to k how you can find out this problem let us take one example so uh let's say this is only one two three one so let's extend is one two three one and then let's say four five six one again let's take an example for this now what you can see here is that i just want that is there a number okay is there a number who has a occurrence of less than equal to let's say two okay which means that the difference between the occurrence of that number like if the number exists let's say at any given i then the next number should be at a distance of 2 like less than equal to 2 if there exists the same number that's the whole problem now how you can check it out is let's say that i just iterate from left to right i see one number one okay then what i can do is that i just have to check that this one also again exists in the range of k like aka distance apart now for that because i have still not iterated to this one what i can do is that i will keep on storing in some map the occurrences of these numbers so which means the last occurrence of one which i have seen is that index so let's say number and uh like index last occurrence of number let's say uh let's take this here only okay let's leave it so what you can see is that the last occurrence of 1 occurs at index then i move to this number the last sequence of number 2 occurs at index 1 and 3 occurs at index 2. now when you come to this point you will ask that what is the last occurrence of one that i have seen that like is one i've already seen and if i go to the map i will already i can check that out easily that one has occurred at index zero now i know that one is occurring here that is at index three and one has already occurred at index zero the difference between three minus zero is equal to three well it means that the difference between these two numbers like the same number occurring is three but i want two that they should be two distance apart and thus i will keep moving forward but now i'll update the last occurrence of one to be three why because see let's say that one again occurs here or let's say here again or anywhere let's say one here again now because i want that the difference between this one and the last one which i've seen should be less than equal to k why should i keep bothering about this one even if i've seen a one that is very far behind and i've seen a new one at this point i should only compare this one and this one now why to compare the distance between this one and this one i hope you get the point so which means that i have to only store the value of the closest one okay that is why i only saw the value of the last occurrence like whenever i see a number and if i see it again i will update the values because now if i again see that value i should not be comparing this with the la very first occurrence of one but the very closest of kinds of ones because then the difference can be less than equal to k i hope you get the point and thus uh that is how i'll update the value of 1 that is now equal to 3 i'll go to this point now 4 has not occurred anywhere inside the map so this is the first occurrence so i just updated i have seen four at index four and five at index five keep on moving like this now six at index that's a six now one again i have seen at this index that is index three and now again that's in the index 7 the difference between them is 7 minus 3 that is 4 which is already very large so which means that now i will update this value of 1 to let's say 7 which means that now i've seen it index 7. now when i again see it index eight i see that again what is the last sequence of one that i've seen at seven so seven minus eight like eight minus seven is equal to one which means that the now the absolute difference is one which is less than equal to k but now this is valid so now i found out one pair and we can just print out the answer even if i want to find out the peer value or what the last seconds you can like use the map here but that's our logic here that how you can check it out and that's the overall let's move on to the code part so we have we can use map you can use a map also you can use an array also to act like a map tools to the last occurrence whatever you want according to your time complexities you want uh and then uh this is n added over the whole length then m dot count this means that i have already like whatever ith index i am on have i've already seen it if i have not seen it then update the value of the current nums of i inside the map and the vap value is the current index which i have seen this if i've already seen this then what i'll do is i will update like i will just check that whether the current index and the last occurrence which i have seen the difference between them the absolute difference is less than equal to k which means that i have found a particular pair i just returned true that i have another pair else if not find out the pair then i'll return false that i have no final pair and at every point of time whenever you see a new number that has occurred update the index that is com completely like update the name so that there's no very far values like uh stored in the map i have the very latest values that's the overall logic for this problem the time complexity here is that i'm doing a for loop and then for loop i'm doing a map check that is i'm using an like unordered map which is like an average of one technology but if you just use only map also then o of n log n if you use a map ordered map it is o of n because i'm just assuming that ordered map takes over one every time quantity and so on so that is the overall logic and code part for this problem thank you for watching this video till the end i will see you next monday coding and bye
Contains Duplicate II
contains-duplicate-ii
Given an integer array `nums` and an integer `k`, return `true` _if there are two **distinct indices**_ `i` _and_ `j` _in the array such that_ `nums[i] == nums[j]` _and_ `abs(i - j) <= k`. **Example 1:** **Input:** nums = \[1,2,3,1\], k = 3 **Output:** true **Example 2:** **Input:** nums = \[1,0,1,1\], k = 1 **Output:** true **Example 3:** **Input:** nums = \[1,2,3,1,2,3\], k = 2 **Output:** false **Constraints:** * `1 <= nums.length <= 105` * `-109 <= nums[i] <= 109` * `0 <= k <= 105`
null
Array,Hash Table,Sliding Window
Easy
217,220
81
Hello hello everyone and welcome back to channel suggestion baikunthpur discus andar important to problem the cutter label kiss problems medium act to problem his approach in routine spotted the ring to this problem is upon by research that china 20 seconds thereby 153 to 9 point research airport children Comment for you two three updated report positive a very comfortable increase explanation I am sure question has been previously in verse in marine product base company cycle clean and dipped Amazon developed concept of the India vs New Zealand test and interview all different vs question two work of you in this uniform And visit today is discussing a different poses on the same question and evidences and we do not want a science question definitely taken by and craft and post your stories 0 comments section block that and feel today's video don't forget to like and subscribe our channel and share This video with your friends also don't forget to like and share interview place liquid liner skates everyone so without wasting any time orders for discussion question that should be commented upon the video and Ritu's try advance is self-evident a try advance is self-evident a try advance is self-evident a question and answers to understand your Devotion And Seeing Such Questions And Will Be Given Away Like These Rights And Duties That Are Related To Direct 12345 Se Pradesh Mein Daal It Also Pinpointed There Might Be Rooted Through Words Rotation Bhi Tak Tips Have Taken A Saint And A Lion Rooted Like This Fennel Bomb 3452 A an alarm set destroy and vitamin and target valley and have to table with television repairing and not support we used 125 12.5% ​​not towards these directions also problems administrative used 125 12.5% ​​not towards these directions also problems administrative used 125 12.5% ​​not towards these directions also problems administrative knowledge and very approach lesson i jaipur that problem is soil and will understand Unko Du Plessis To Understand The Basic Bekash Host Subah Full Movie Want With Solution Record Its Okay Dear Candidate Marked Into Her Surat Second Example Decade Bhi Rs.3 Lakh 4512 Sudhir Widow Pension 1234 Bhi Rs.3 Lakh 4512 Sudhir Widow Pension 1234 Bhi Rs.3 Lakh 4512 Sudhir Widow Pension 1234 500 Festival Disputed Subscribe And Not The Only Thing R Most Like Subscribe In this particular point it is and Sports Club Points 5696 President Decree about 5 Vikram to a solid liquid liner bj and co approved to so this point Electronic Craft In this particular point here are some differences between this question and more channels to live with someone who Question is laddu wicket ashwin lifted here is a part one being rather that this order will support you from getting over 231 repeated and in the midst of going to three lakh candidates selected to have to cash withdrawal is above input like 3452 every little warred for this will Tours After And To 100 Ki Take One Month On This Creation Candy Crush BP Pants Got Up Tomorrow Morning To Understand What Have Tried To Represent Vigraha Of It's Not Digested To A Watch Difficult Something Is Graph Barely Youth In The Expression Pass It's Not Understood As Crafted Will Beat up to understand the question please click on the trees and plants craft lineage of this rumor and still not clear watch this point again and listen decisions cut code for different posts from giving alms vector which was rooted are so let's take in intel 4004 and Anarchy Dooms and Size Minus One So What Are The Zara Tractors and 102 Are Will Be Used To Attract That Swami Right And Will Be Used To Exit From Being Left And Up Having To Address Violence Yassin Ko De Are The Voice Of Ban Albums Equal To Of three final element tarf baluni to continue registration for the is so let's look at what they are doing meditation for stuffed alu how to remove appointed s supreme court pun r and norms and bail someone to equal to thumbs up if plus tomorrow morning office What is Pollution? Send 200 lb input like to discuss the grill 452 entry li ki sufi muddat in ki and istri i will definitely leave at least one this period element and fiction the biggest dat itself and potential to get what is this point simply to and decides How to remove this element and give this element update otherwise important in note - read andher lessnar and not in note - read andher lessnar and not in note - read andher lessnar and not helpless in kotdwar and liquid first in this case is the least one showoff just whatever you tension target date for deposit painless daily 1285 remote all the once A that including swiped artist clear is a slogan next9 code soft toys defined in 10m is equal to e-mail plus and minus years later to so what is this e-mail plus and minus years later to so what is this e-mail plus and minus years later to so what is this is calculating also middle element mother's nine basis of this matter element to titu condition to post Condition Has It's My Name Fennel Am That Is Greater Than Target The Court Can Be Garlic Ginger Paste Day Fool Something Madhesh Country Madhesh Safed That Is Equal To Target The Till Mixture Element Is Paw So He Will Return True Wealth Through Element Is And Target That Is Fonts Are So Effin Target Every Day Through Is Not Will Do Something So Let's Understand What Is The Worst Condition In This Great Possibilities A Solid Rock On Subscriber And Discuss Initially Practice Channel Don't Forget To Subscribe To Element's Live In This Nutrition And in this portion aap osho the sunday post ne software and giving the condition that my number pm that his creative day mein a target are not considered enough to conditions 1514 post call latest consider this position at what is my name live score But have no name of this great chinta aage tak teaser target like and worship that however in but condition is synonyms of this line is above but after there life in this portion and this and share portion is some all of this number and according to fun From another important * and according to fun From another important * and according to fun From another important * Note the condition will always be satisfied Television is equal to what is meant equal to are you and hit and remember pain hydrate nazar index of dresses and norms of name and we which alarms and obscene values ​​on 11th we which alarms and obscene values ​​on 11th we which alarms and obscene values ​​on 11th is so in this condition Rachna discuss this and you but from your data that at this time and this line arghya hello how can decorate target will live swiftly 1008 mail will be left behind by name and they all will be like a good time for this is to poshan verma r Glass previous and after that you for watching this place where to bring back and bank one lesson Sudhanshu ji spot track balance look at the second part of at which the members like hindi offer line white this line survey students language investment this fast target this List No. 2 p.m. Icon Tune is also lying No. 2 p.m. Icon Tune is also lying No. 2 p.m. Icon Tune is also lying on her in the center of the right and you shall say no diary will be lying in the spot and Lord can be lying in this point and in this post that Bigg Boss mention das condition will always be true e- Mail it pin code to is this day to do for e- Mail it pin code to is this day to do for e- Mail it pin code to is this day to do for rent a harem juice peene se that is my target is this line sensed value that and also comes up e-mail so is this day to target that which means dad norms of all that is Also like jain name shop em the right juice also scene is david villa in khuli hai to is condition boss automatis side more condition the time wedding 12410 employee at is the value and this number nine the line mail target and am target will be all In between a name that I and this ahead of my name is sumit target search for this reduced to reduce are song again a prima and bank hai are ayodhya dispute its that and vor this condition is satisfied dena hai to increase mile boy death toll gate Answer lies above and her torch light in these directions possible pass as much target slice to give now to increment measure solid side unicode well for this is more all stock remote this condition and this is located on to this condition for this manner of this great And norms of some specific edition the condition where my job or line understand or phone number bell so is equal to a target and discuss the condition where my dear line for kids in this condition boss all equal to a minor are address what is discussed and Will be incremented at the same time Albums Plus One subscribe The Channel Please subscribe this Video not made to do Subscribe to search discuss the next point Name is not let the target and talk to me a boy name's name is Lucinda got so let's look at this point S well s that research condition is this a number of m so this day the target is a so let's brothers graph etc rate that no again to condition flight number one call can live and we white sesame commissioner a node to gets greater day we 2 p.m. a node to gets greater day we 2 p.m. a node to gets greater day we 2 p.m. Given this condition easily one possible so swiss roll know that however this condition second in this one jewelers months will notice all this time it reverses in the previous one source pass different sources also one source for this and others subscribe skin infections this point when Skin and subscribe to the right nor can discuss the best condition send episode in this part is discussing this condition post so let's see happiness and peace customer is 108 number of employees on her and target is great Indian name of some sort of bigotism coming here And Rkut bhi line and hair and gold disturb me Jha and Neetu increment table and table welcome addition in the previous one is changing na yaar whenever changes viral post rate this delicious is the only second question because one table is possible at this time Condition is that was created neither f-18 can be raised here or again in life like any previous f-18 can be raised here or again in life like any previous f-18 can be raised here or again in life like any previous one that lumps values ​​in the target in this case LED values ​​in the target in this case LED values ​​in the target in this case LED opposite operator album checking is my name clear mail is great benefit this facility only Mahendra Singh and saunf number line has been appointed as this time but will happen if i number pm so sadan target right admin amazon target this employees set norms of all is great then name of saunf m.a. name of saunf m.a. name of saunf m.a. Hai is so rich welcome to celebrate the name of him and my all is in the means of the receiver hai ka rate mtech pointed out so set up to my channel and some consider this source for all the best source for MLA behind pune bomb blast that in This condition certificate office read decrement maze and so westra enrich also previous debit discussed pure spot twist this place on equal opportunity did not find the total number in political space with tried to alter thinking so let's write down the code value that if additional flashlight on off A number of oil on which this article is daily and two numbers of name are research speed post condition when my name chant and Lord Indra then line half number reach tourist fluid humsafar rate and names April is great in the target I just in number on Greater day current target do it means I hate you move ahead Nobel price west try brigade indie lower line and rate is so in this case is making a is equal to one plus one main itna nandishwar roodan ayush wing may and behind all is equal to A Minus One Egg Depend You My File Loot Pause Show Will Return Forms Will Never Ever Have Our Own Troops Withdraw All The Elements From This Elements Of Obscuritism Electronic Cigarette Sued 50 Cent Increase In Officers' Mess Nine Surplus Knowledge Gives Increase In Officers' Mess Nine Surplus Knowledge Gives Increase In Officers' Mess Nine Surplus Knowledge Gives Assignment Open The Beginning Full Video The Software Assignments In This Question Now How To Return With An Elements Present And Not A That Side Which Just Sum Break If Exact Index Duration Element Flash Light A Cute You Find It Index And Report Regular Element Key 120 Assignments You Don't Forget 2.2 Solution Insert Comment Section And Forget 2.2 Solution Insert Comment Section And Forget 2.2 Solution Insert Comment Section And Ask Your Desires Will Benefit Vacancy Open Welcome Anything Like Today Solution Tubelight subscribe The Channel and Share The Video To Friends Android Bell Icon Always Keep An Eye On Updates Thank You For Joining Thank You Keep Coming Talk And Keep Code Thank You
Search in Rotated Sorted Array II
search-in-rotated-sorted-array-ii
There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values). Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`. Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._ You must decrease the overall operation steps as much as possible. **Example 1:** **Input:** nums = \[2,5,6,0,0,1,2\], target = 0 **Output:** true **Example 2:** **Input:** nums = \[2,5,6,0,0,1,2\], target = 3 **Output:** false **Constraints:** * `1 <= nums.length <= 5000` * `-104 <= nums[i] <= 104` * `nums` is guaranteed to be rotated at some pivot. * `-104 <= target <= 104` **Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
null
Array,Binary Search
Medium
33
134
okay so let's continue with our coding exercise so open the and go to exercise so open the and go to exercise so open the and go to the problems tab and if you scroll down the search question number 134 and as an as soon as you hit enter you will find this question that is gas station let's come under the medium category so click on it so let's read the questioner so let me explain this so there are n gas station along a circular route all right so there are n gas station along a circular room where the amount of gas at the io station is gas of I okay you have a car with an unlimited gas tank and it costs cost of five of guests to travel from is station to the next is plus one station you begin the journey with an empty tank at one of the gas station given two integer array gas and cost so we have two arrays given so one is gas and one is cost so if you see the function uh definition SO gas and cost return the starting gas station index so we need to return some integer right if you can travel around the circuit once in a clock protection otherwise written minus one if their existing solution it is guaranteed to be unique so like if you really just stay like a question in a single one or you might do not understand like uh what the question is maybe you need to read two to three more times correct but let's try to split the question in a simple manner all right then like it will be very easy so let's read the again so there are n gas station along this circular route so there is a one circle is like a road which have the circle with a circular root and there are n gas station okay so let's come to the Whiteboard so I created a one circular rule so you could see one circular root okay there are n gas stations so I am taking this example where are one two three four five there are five gas station so there are five gas station along this circular route so I put five station one two three four five there are five gas station along a circular fine where the amount of gas at the ayath station is gas of I so it means the gas at this station like at this station which I am highlighting which I am moving the cursor is gas of I so it means at first station the gas uh what is the like amount of gas so every gas station has some capacity right some has like 1000 liter of gas somewhere two thousand liter of gas so every station has some capacity right they said okay the first station has how much capacity so you can take the like the first index or the zero conduct second station the second index third station the third index fourth session fourth index fifth station fifth index so the first station is like how much liter of gas you can consider the liter like they did not mention whether it's liter or milliliter or what or like ton or what so let's take a simple okay first station is one liter segmentation situation is two liter third station or three liter four session four liter fifth station five later so now so the first line is clear okay now you have a car with an unlimited gas tank which is fine so let's suppose we have a car so we have some car right so this is our car okay you have a car with an unlimited gas tank so they said whatever the gas tank this car has all right so there is some gas tank this car has it is unlimited so you can fill any liter of gas in this is very huge stack right okay so till this point question is clear okay what next and it costs cost of I of gas to travel from ith station to the next I plus one I means that's for this so I plus 1 is the next so I means this I plus 1 is next so if I is this three the I plus 1 is this four if I is 4 then I plus 1 is 5th so basically the next station so this adds so if you have the car and if you have to travel from first gas station to the second gas station so definitely if you are running your car and if you have to travel the fuel is going to be spent but how much fuel is going to be spent they said it is mentioned in the another different array all right so there is a course Target so this is noted like rupees this is you can consider as a leader so it means if you are on the station I so if you are here all right if you are here so this station has how many how much liter of gas this our car doesn't have any gas so if let's suppose our car is here our car doesn't have any gas but this station has one liter of gas and from this station to the next station this station how much liter of gas needed that is three liter of gas right so they have mentioned it cost of your gas to travel from is station to next time plus one to share so you begin the journey with an empty tank at one of the gas station so they have not mention from where you need to begin the journey they said you can begin the journey from any of the station it doesn't matter like they don't care about that all right but the like uh our car has the empty tank all right so our attack has a okay given two integers so now it's understand so what is the stations has how much gas and the coast area is so if we have to move from this index to this index how much if we have to move from first station to the second station how much liter of gas ID to spend right so because this station is very far right so how much liter of gas is to be consumed so it's three liter okay so return the starting gas index so basically because they have mentioned you can start from any index you can begin the journey with at any of the gas station so from where we are going to become begin the journey that we need to find out right so we need to return the starting station index so we need to return the so shall we start from one shall we start from two shall we start from three shall we start from four shall we start from five all right so that you can travel around the circled root once in a clockwise Direction they said you have to choose that station so that if you start from that station you will reach at the same station basically you should complete one whole circular route all right so you need to find that starting point so if you unable to find that static one you need to return minus one okay so I believe the question is clear so the question is clear okay so now let's take this example now let's start because this they said okay we need to find the starting point like I we cannot randomly guess okay one with the starting point two with the static but three is the starting point for the starting book we can't randomly guess that is true so we need to check one by one so this is our array so whether this is our array whether this is a starting point or this is the starting point we don't know so we have to check one by one okay so let's start from the first index where that's the gas station one is so let's suppose our like car as at here so if our car is at here hey this index where I highlighted our car is here so now this gas station has and our car has unlimited tank and uh in the ignition the tank is empty that is zero gas so we place our car here so how much maximum gas we can fill in our car so that is one so let me so when we add station one all right so how much gas we have how much gas we can fill in the tank that is one okay so now we fill our gas okay we filled our worker that is very good so let's start moving one is only one liter right only one liter so now we start moving okay at this point one liter finish at this point one later finish because to reach to the next station we need three liter of gas they have mentioned if you want to move from one station to another station you have to check how much liter of gas so if you move from one to two then we'll need three liter of gas but we have one liter and our car stops in between it means one is not my static point it means one is not my starting point okay so let's start from the another thing another so this is not my starting point okay now let's start from station 2. station two so if we start from the station two our like uh tank is empty so how much gas we can feel maximum two so because we are starting at this station so now our tank has two liter of gas okay so let's start moving our car stops here by our car stops here because to move from one station to the next station we need four liter of gas but we have two liters so our the gas is finished if the gas is finished the car can't move further right so our gas is finished so we can't move further because we need four liter if you see from move to one station to another station we need four liter of gas okay so it means 2 is also not the static point two is also not the starting point okay fine it is perfectly fine let's uh start from three let's start room three because we need to find the starting point but so we know one is not the solution we know two is not the solution let's start from the three okay if we start from the three so let's mean tie here so SO gas station three how much gas you can feel because it has three liter of gas we are going to fill in our tank 3 liter okay now let's start moving and here our gas is going to finish why our gas is going to finish because travel from here to here we need five liter of gas but we have only three liter all right so our car is going to stop here so it means three is also not the starting point three is also known as the static Point okay fine there is no other starting point now let's check the next Point okay so let's suppose our car start from here okay so four okay if we start from the station four because we need to find the starting point if we need to charge from the station for how much gas we can feel poor okay we have four liter gas we have four liter of gas so we can start moving we reach the next station and how much gas we spent only one liter we spent so only one liter we spend and so we reached station five and by the reach boost station five how many guests we spent four minus 1 is equal to three so at the station like our when our car reaches here whenever car reaches here we have three liter of gas still remaining so we are at station five now we can fill more gas so if we feel more gas so three is already there in the tank three is already three there in the time we will feel three plus five is equal to eight so now we have the eight liters so here we have the car has the eight liter of gas all right so let's start moving we will reshare because to move to the next station we need only two liter so we move the next station so we move to the next station so let me we move to the next station and we spend only two liter and remaining is six so when we reach this station we have six liter of gas and at this station we can fill this gas as well six plus one is equal to seven okay so let's fill so six plus one is equal to seven so now we have seven liter of gas here right so we will start moving we will reach two we will release two and as soon as we reach to how many liter of gas we spent seven minus three four correct and we reach four and whenever these two we can fill the another gas as well so six so till this point we have six liter of gas after filling from this now we can start moving and we reach here so we spend only four liter of gas still when we reach here still we have two liter left so two plus three five so we can fill five so now we gas and the five liter is required only and we reach here so we start from here we reached here so we start from four we restarted four so it means we completely to one circular route and our starting point is four so it means we need to like uh return the index so what is the index of the 0 1 2 3 so 3 is the index so if you see 3 is the index all right so three is the index so basically we need to check uh like uh for all stations we need to check for all station now by looking from this diagram it might look very easy all right but you can like ask one question okay I am going to run one loop I am going to run one Loop which is going to check okay because I am going to start from first I am going to check uh this is not valid I will move further this node valid I will move from this node valid I will move further so I am reaching four so this is valid I will move further all right so this is when I will move further but the loop is going to finish how many times I need to run till what point I need to run I'm not going to run while loop right so there is another case so but still now we are going to know how we are going to like solve this question okay so let's read the other example so this is our other example so we have three station in the circular row two three four means the first station has two liter of gas second decision a three loader gas four station or the four liter of gas authorization of the four liter of gas okay and if we want to move to 223 we need three little gas if we want three to four we need a four liter of gas if we want four two shall we start from two so because we need to find the starting point shall we start from two if we start from two our gas is empty our solid let me take that if we start from two where I have the red cursor all right so our tank will be 2 liter of gas two liter of gas car tank has now two little guys okay now I can start moving so moving stopped because it needs three liter to reach so two is not my starting point right okay so 2 is not my starting point delete it so shell will start from three so if we start from three so car tank could have 3 liter of gas alright so if we start from three so let's start moving stop because we need four liter okay so we can't start from three okay which is fine let's start from the four can we start from the four if we start from the four then uh car tank can have the four liter of gas because when we start from the four from the gas station we will tell them fill the all the four liter in my car so now we have the four liter so let's start moving so moving yes we reached but we reached the two we need the circular route we start from here so this is my starting point we start from here so we need to check whether it's a circular route will be completed or not so four liter but by reaching the next station we already spent three liter so only one liter remaining only one liter meaning okay we reach at two so we decide to we can feel that our time so one liter already in the car two liter we are going to Morphine so now three liter okay so now we can move so we can move yes we can restore three so as soon as we three like our car reaches three all the three liter finish so all the three liter finish three minus three is equal to zero so now we can fill the tank zero plus three is equal to three okay so let's start moving move but we are going to stop because to move from three to four we need four liter of gas and we have only three liter so we have not completed the circular root we only reached till this part we start from here we have not covered this area all right we have not got this area so we have not addition to the part so we have to return minus one so that's why in this question they are like returning the minus one output is minus one okay so now like uh it's clear right so how we are going to calculate and the same thing we are going to implement in our like a code as well so let me uh erase this one in just a second okay so let's do this okay so let's try the next example let's take the next example now we have the five station in the circular row so five one two three four okay so the first station is 5 liter of gas segmentation as one liter third station has two liter fourth station and three liter fifth station okay so we need to find the starting one so similarly the same approach okay let's start from here okay if we start from here uh our car has zero liter initially so now our car is five liter so with five liter can we move to the next station yes I can move to the next station so as soon as move I move to the next station as soon as I move here so y minus 4 is equal to 1 because I already spent 4 liter on the way all right so one is one liter left and as soon as reached there I will inform the gas station can fill the gas so by so I will have two liter so now I can travel from five to one but can I travel from one to two no because now I have two literally to travel from one to two I need four liter of gas so I can't start from one okay so it means five is not my starting point five is the starting point if we have to travel till 1 but for the circular root 5 is not the starting point right so five is not the starting point one is also not the starting point because if we start from one only one liter of gas because if we start from five we are not going to restore if we start from one we are not even going to reach 2 if we start from two so two liter of gas so that second so if we start from two so here we have the two liter of gas all right so two liter of gas so we reached here we already spent one liter in the way so we have one liter lap now we will ask the gas station Can you feel it so it's going to fill it so now we have the four liter because three plus one four okay so can we reach next station because we need five liter we can't reach the next station so three is also note my starting point okay so will the four is my starting point let's try so we are here so we have four liter of gas so we reach here so we already spent one liter of gas in the between so we have three liter left so three liter left but at this gas station we can fill five more so three plus five is equal to eight so now here we have the eight liter of gas so can we move to the next station yes I can move to the next station as soon as move to the next station so now I have the eight liter when we start but in the way so this way I spent four liter so now four liter so when I reached here so I can ask the customer service can you feed the guy so they are going to fill so now I have the five liter gas can I move next station yes because we need only four liter so I can move uh to the next station as well so I can move to the next station as well as so but in the between I am already used four liters so only one liter lap so I can feel here uh two more later one plus two is equal to three which is fine can I move from two to three yes because I need to only spendable later but I have three liter so I am spend only one later I have three liter so now two liter left so when I reach it here I will last the gas station Can you feel it so it's going to fill all the guys so two plus three five can I move to the next station yes because I have five little gas at only five liter is required so I move I reach it here so four is my starting point so where is the four zero one two three fourth so I am going to return the index 4. okay so now the question is we can't say because if we are moving to the next station we can't say that is the starting point as soon as like we see in this uh example because from 5 we are going to one but from one we are not going to further so it doesn't mean as soon as we started uh that could be the startup and now we have to check but till how many times I am going to check till like until the circular route is not going to be completed so you are not going to check multiple times in the supply node any kind of while loop node two Loops because so if you notice clearly if you notice here you tell me one thing we have as an example we have how much liter of gas in total one two plus one three plus three six plus four ten plus five fifteen we have 15 liter of gas in total and how much you can say a liter we need to spend uh in the circular Road five 12 plus 1 13 30 plus 215 we have 50 liter of gas in total and we have 50 liter of we need to spend in total doesn't matter we are Google to start so when we have equal or more it means we will find some starting point so we are go and starting point either one either two either three either or either right so any one of the static point so we are going to run only one Loop we are not going to check again and again because we know either one is the starting or either two either three either four either five so we are going to start one two three four five so as soon as we reach there we are not going to because let's go starting point is 4 we received 5 here all right and our Loop is going to finish we are not going to check whether it is going to be reached 4 or not because we know it is going to be reached because the total number of gas is equal to or more than the distance we need to travel if you go to the second question second example how much gas in total we have four plus two six plus three nine okay how much distance we need to travel or distance or how much liter we need to spend three plus three six plus four or ten we have only 9 liters and we have to spend 10 liters so doesn't matter from where you are going to set it's not going to be you will not going to find the starting point all right so what I am saying is first check whether you are going to find the starting point or not if you are going to find the starting point then only start the loop if you are not going to find the starting point then just return minus 1 then just return minus one so let's now write the code so hopefully you understand a little bit all right now let's write the code so first thing is that shall I directly start my finding the finding my starting point no because first I will check whether it is possible to find a static point or not how we are going to know let's calculate the total number of gas and let's calculate how much it's going to be uh spent in on the way right so if sum of gas if some move gas is less than sum of cost all right then we are going to return -1 got it so if sum of gas so gas is -1 got it so if sum of gas so gas is -1 got it so if sum of gas so gas is less and gas is less uh yeah so if gas is less than the then the uh then the you can say distance or you can say how much we need to spend all right so if gas is 5 and the gas is let's suppose 15 liter and we have to spend 20 liter so we are not going to like complete the circular route all right so which is fine now so if this condition did not matter so it means there is one starting point from one to five there is one starting point so if there is only one starting point and it could be either one two three or four or five then we are going to run only one once we are not going to run or Loop twice so for I in range of so here let's calculate the length of gas so basically we are going to run Loop because we need to run a loop okay fine now what we need to find the starting point okay let's uh calculate this in the initial starting point is zero let's take the starting point at zero all right and the in the initial our tank is also zero so let's define in a single line so starting point tank is equal to 0 comma 0 and even you can Define the n as well in the same line length of gas just to like redo the number of lengths otherwise you can Define create line as well okay so now you start from I so now we have to check line by line or station by station we start from first okay as soon as we start from first what is our first purpose I will set fill my tank with what value whatever the existing value tank plus whatever the gas station has gas of station of I that is one okay is going to fill okay now how much distance I need to travel to the next station distance I need to travel is equal to the cost of I that is 3 okay let's find the difference if I travel how much tank I am going to spend how much gas I am going to send to 10 minus distance so um like here we have one liter of gas if I travel so 1 minus 3 is equal to minus two so how much like I'm going to travel so if tank is less than zero it means it is negative if it is negative it means that is not a starting point it means this is not a starting point so starting point could be I plus 1 the starting point could be the next uh like uh the next index uh not the starting point so start plus one or something like that the next value right so it's zero uh and the starting point could be the next value start plus one okay so starting point in the next and if we are stored from the next value so we know one is not the starting point so we feel we fill our tank already right and we already spent so now we know one is not our starting point so we know two is our static point so if we know two is our starting point so we have to start from zero that is basically we are going to start from 2 to check whether 2 is our starting point or node so what we are doing is we are doing step by step so if we start from one okay so Loop is here one we start from one all right so we start from one okay we feel our tank is equal to guess plus I okay fill my tank okay car is going to fill by one liter okay how much distance I'm gonna do travel three okay what is the difference tank minus one minus three is equal to minus two okay so okay am I able to reach so whether tank is less than zero yes tank is less than zero so it means one is not my starting point so starting point could be the next it doesn't mean it is next is the starting window it could be the next so if it is the starting point I need to make the tank is equal to zero again because if I am starting from 2 I will reset my tank because now I will put my initial car here right so tank is equal to zero okay so now it is going to find and after that I am going to return the start point because if 2 is not the starting point then it will check for three if three is not the starting point it will check out four if four will draw the center it will check for five that's it and any one of the starting points should be and we are going to return the static part because if there is no like because why we are checking only once because we already checked whether there is a possibility to find the static point or not all right so if there is a if there is not a possibility when the gas is less and the distance we need to travel is more or this The Gas We need to spend is more then it means there is no starting point otherwise definitely there is a static point and it could be any one of them so we are going to run only one top so let's run it has been accepted so let's try to submit it so something is wrong or something is wrong so I think it should be I plus 1 so let me yeah it should be I Plus 1. so like our solution has been accepted our solution has been set so it is not startup plus one like because otherwise unnecessary uh because when the start is uh like setting some value and the start has had some value and so basically we find as an example uh in this sorry in this example so if we do start is equal to start plus 1 then because here we are moving from five to one but five is not a starting point five is not starting so that's why from wherever we are starting that we need to do I okay I plus 1 is my starting point okay not the startless one otherwise start plus one uh we are unnecessary like a uh calculating more values all right so uh that's the end of the video and our solution has been like accepted you can also try this question thank you
Gas Station
gas-station
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`. You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique** **Example 1:** **Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\] **Output:** 3 **Explanation:** Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index. **Example 2:** **Input:** gas = \[2,3,4\], cost = \[3,4,3\] **Output:** -1 **Explanation:** You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start. **Constraints:** * `n == gas.length == cost.length` * `1 <= n <= 105` * `0 <= gas[i], cost[i] <= 104`
null
Array,Greedy
Medium
1346
907
hello everyone let's try to be a cheat code ninja today even though this is categorized as a medium problem I consider this to be more challenging than that let's look at it we are given an array and for every contiguous sub array we have to find the minimum and then we have to sum the minimum of 8 sub array at the end we have to mod our answer by a constant let's look at the example for this array there can be a total of 10 different sub Aries these are all the 10 sub arrays that are possible let's take this sub array 3 comma 1. the minimum of this would be 1. similarly for the sub array 1 comma 2 the minimum would be 1. and for the sub array 3 1 2 the minimum would again be 1. the sum of all the minimums of the sub arrays would be 17. let's try to come up with an intuitive solution for this let's take this array as our example let's try to figure out the number of sub arrays for which an element will be the minimum if we take a look at the sub arrays with 4 as the minimum the sub array cannot have any element on the left from 2 onwards this is because if that sub array contains 2 then 4 cannot be the minimum and 2 itself will be the minimum similarly on the right side for 4 to be the minimum there cannot be an element from 3 onwards because 3 is lesser than 4 and it will become the minimum you can notice that 2 is the first number on the left which is smaller than 4 and 3 is the first number on the right which is smaller than 4. hence the sub array has to be in this range and it must contain 4. these would be all the sub arrays where 4 is the minimum these are 6 sub arrays in total for each of these six sub arrays four is the minimum and we would have to add it to our result we can also come up with the count of the sub arrays by multiplying the number of elements on the left with the number of elements on the right the number of elements on the left would be index of 4 minus index of the previous molar element and the number of elements on the right would be index of next molar element minus index of 4. and we would have to add to our result the product of the number into the number of elements on the left into the number of elements on the right to find out the next or the previous molar element we can use an increasing monotonic stack I have recently uploaded a video for a hard problem next greater element 4 in which I have explained how to find the next greater element using monotonic stack I will advise you to check that out if you haven't used monotonic stack before with our previous approach there can be three Corner cases that we have to handle in our first example let's look at seven we see that it has a smaller element on the right but it does not have a smaller element on the left ideally we should have these two elements on the left for which 7 is the minimum if we can assume that there is a minus infinity at the start of the array then it can be considered as the previous molar element the difference in their indices will be 2 which is what we want hence by adding a minus infinity at the left we can avoid our Edge conditions and finally We'll add to a result 2 into 7 into 1. in our second example for the element 8 there is a smaller element on the left but there is no smaller element on the right ideally there should be only one element on the right if we apply the same technique and assume that our array has a minus infinity at the right we can consider minus infinity to be the next smaller element the difference in their indices would be one which is what we want hence we can avoid an edge condition by adding minus infinity to the right and finally we would add 1 into 8 into 1 to our result in our third example 4 is the smallest element in the array hence there are no smaller elements on the left and the right ideally there should be three elements on the left and two elements on the right applying or above techniques minus infinity would become the previous and the next smaller element for 4. the difference between their indices would also be 3 and 2 which is what we want and finally we would add 3 into 4 into 2 to our result hence by adding minus infinity on both ends this solves all the three edge cases that we can have let's look at a complete example for first element minus infinity there are no elements in the stack hence we'll directly add its index to the stack for our next element we'll compare it with the top of the stack and check if it is smaller than that our top element is minus infinity and 3 is not smaller than that hence we'll directly append its index to our stack for next element we'll check if it is smaller than the top of the stack or top of the stack is 3 and it is greater than 1 so we have found the next molar element for 3 the number of elements to the left would be its index minus the previous index On The Stack and the number of elements on the right would be the current index minus its index we would add to a result 1 into 3 into 1. and then would pop that index from our stack and now we'll add the current index to our stack moving on for the next element 2 will check if it is smaller than the top of the stack or top of the stack element is 1 and 2 is not smaller than 1. so in this case we'll do nothing and add our current index to our stack similarly our next element 4 is not smaller than the top of the stack we'll add its index to our stack for our last element minus infinity it is smaller than the element at index 4 which is 4. so now the middle element would be 4 and the previous molar element would be index 3. and the next smaller index would be our current index which is 5. we'd add 1 into 4 into 1 to our result and then we'll pop 4 and check with the next top element index 3. 2 which is at index 3 is greater than minus infinity its index is 3 and the previous smaller index is 2. the next smaller index is 5. so we will add 1 into 2 to our result would then pop it from our stack and then compare with the top of the stack which is index 2. 1 is greater than minus infinity so it will become the middle element the previous smaller index would be 0 and the next smaller index would be 5. so we'll add 2 into 1 into 3 to our result would pop 2 from our stack and then compare with index 0 which is minus infinity now the minus infinity on the right won't be smaller than the minus infinity on the left we would add the current index to our stack now we don't have any more elements to process our result would be the sum of this and this is 17 as given in the example the time complexity would be we are adding and removing each element from the stack only once hence it would be o of n or space complexity would be o of n because we are using a stack of size n let's Implement our solution we'll change the variable name to a we'll have to add a minus infinity on both ends of the array let's keep a variable for the length of the array let's initialize an empty stack and our result to be 0. we'll go through each element in our array and we'll check in a loop if a stack is not empty and our current element is smaller than the element at the top of the stack this will make it a monotonic increasing stack if a current element is smaller than the element at the top will pop the top element from the stack this would fetch the index of the middle element our left index would be the next top element of the stack this would represent the previous smaller element and our right index would be our current index this would represent the next smaller element we would add to a result the number of sub arrays in which the middle element is the minimum this would be the middle element into the number of elements on the left into the number of elements on the right when there are no more elements on the stack which are greater than our current element we would add our current index to the stack after processing all the elements we could return our result one last thing is that we have to mode our result with this constant as it is given in this question let's submit our solution as you can see our solution is accepted if you have any doubts or concerns regarding this Solution please mention in the comments if this video is helpful please support this channel by liking this video and subscribing to the channel thanks for watching
Sum of Subarray Minimums
koko-eating-bananas
Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[3,1,2,4\] **Output:** 17 **Explanation:** Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\]. Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1. Sum is 17. **Example 2:** **Input:** arr = \[11,81,94,43,3\] **Output:** 444 **Constraints:** * `1 <= arr.length <= 3 * 104` * `1 <= arr[i] <= 3 * 104`
null
Array,Binary Search
Medium
788,1335,2188
518
hello everyone this is mustafa from zakocho and today we have another lit good problem this is one of the classics of dynamic programming what we have here is we have the problem itself is about you have like amount of coin or amount of money and you need to find how many ways you can make up this amount of money and you have array of coins you can use to make up this amount okay we have an example um if we have like five uh if you have five pounds or five dollars and we have like coins of uh one and two and five there is how many ways we can uh make up this five out of this coins array so actually here we have like four ways to make up this um this amount yeah we can choose only directly five and we have we can use two and one and two and three ones and we can use also five ones how we can uh implement this solution and we or how we can um solve this one it's um actually uh to make it much more easier let's uh let's solve it in two into two phases okay so the first phase let's write a backtracking uh backtracking solution that will solve the problem but it will handle it like in much lower a much smaller constraint so after we develop the backtracking solution we will enhance it and we will add the memorization board it will actually help us to have uh more coins and we can use more coins to or more amount to solve the problem so without further ado let's start with uh building our back tracking uh backtracking solution so first thing let's not take the length of the coins into another variable then yeah length okay and uh we need to write uh recursive functions that we uh this request function we will need to call it and it also will call itself again so this is part of our backtracking solution recursive solution okay and our function will take the reminder and the current position of um uh where we are currently at the coins okay so if we are here this is the position this is the first position second position and so on okay and we need to start or we need to solve from the amount itself so we need to solve from the amount and the index of zero okay so this is the first part so let's write our base cases okay actually uh we have two base cases okay so the first one if we already um take the whole amount and we don't have any amount left so we already take this five and we have like zero so we don't need to um we need we don't need to do any another uh calls we just need to return one as we already took this boss and this boss is already good for us and we already reached our goal by making up this amount of money so we need to return one to indicate this boss is good okay and we can use it also we have another base case if we if our position uh reached the end okay so we reached the end of the coins um because we didn't uh we weren't able to make up this amount of money off out of those coins okay and let's write our two recursive uh recursive calls okay so the first one we need to check okay if the reminder is larger or equal sorry larger or equal the current position of coins okay so uh actually if we have the remainder is larger than this current position of coins that actually means we can uh some subtract from the reminder this amount okay we can substitu subtract from the remainder this amount okay so uh we can call fold again and um we need to call the uh the new reminder put the new reminder will be like coins uh will be the remainder minus the coins of the current position okay and the new position surprisingly would be the same and we need also to solve from the next position okay so we will leave it like this all reminder and musician well a plus one yeah i think i have time here position yeah so what actually this mean uh this means we need to solve from the current coin again because if you see here we can take the coin the same coin in this amount of time so here we take one like five times and we to return it so we need to solve uh from the same coin again so we here we pass the same position again and we also need to solve from try another solution by adding uh the reminder and we need to try with this reminder another coin okay so here we drawing another coin and here we're trying the same coin here we talk this coin so we subtract it from the reminder and he we didn't take it so uh we didn't subtract it from the reminder and we need to return so uh and else as if we didn't find this reminder is larger than the current position uh current position of um of the coin so we need to try uh from the next position okay so we need to solve sorry from reminder minus uh sorry not this yeah modern position plus one so we are throwing another um another solution or another coin okay so this should be our um backtracking solution okay this solution without mobilization so we can consider it as a dynamic programming solution let's just try it and let's see if this solution will work for this test case it should work otherwise we have an issue on our code yeah it works fine now the next step is that we need to write um as a dynamic programming part or the memorization part okay so to do so uh actually we need to create a table or create an array that we need to use it to cache the solution from a specific coin so how to do that we need to define a new array let's call it memo and this memo is actually a new array okay and the length of this array is m plus one and let's fill it up with another arrays to make it like 2d arrays because we need to cache two things the reminder and the position i'm saying reminder all the time it's remaining and the position so this is the remaining and this is the position so yeah uh this should be something like that for equal var i equal zero and um we need to tell them i is less memo length and need to increment the i and we need to say that memo of i equal new array of amounts plus one okay and we need to fill uh remember i fit with minus ones okay why we add it uh like this because we have like sometimes we can have solution like zero and we have social like one so um we will never have a solution like minus one so that would indicate that we didn't have or we didn't use this position before and we can um we can calculate it from here yeah so um let's build um let's include this in the recursive part or as a backtracking board so we need also to add here another if statement another base case so if memo of the current position and the current remaining is not equal -1 so we need to return this -1 so we need to return this -1 so we need to return this okay so we already calculated before we need to return it so this is the first part and we also need to catch the solution here and we need to cache it here okay so this is the solution and at the end we need to return it okay so that should be it we didn't return so it would never return so we forgot this one let's submit it again yeah it works fine and perfectly some minute yeah thank you for your time hopefully this um help you to understand a little bit the solution of dynamic programming and the basics of dynamic programming and as i mentioned in the beginning of the video this is considered as the classics of dynamic programming problems so hopefully you understand it well if you have any questions please let me know
Coin Change II
coin-change-2
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`. You may assume that you have an infinite number of each kind of coin. The answer is **guaranteed** to fit into a signed **32-bit** integer. **Example 1:** **Input:** amount = 5, coins = \[1,2,5\] **Output:** 4 **Explanation:** there are four ways to make up the amount: 5=5 5=2+2+1 5=2+1+1+1 5=1+1+1+1+1 **Example 2:** **Input:** amount = 3, coins = \[2\] **Output:** 0 **Explanation:** the amount of 3 cannot be made up just with coins of 2. **Example 3:** **Input:** amount = 10, coins = \[10\] **Output:** 1 **Constraints:** * `1 <= coins.length <= 300` * `1 <= coins[i] <= 5000` * All the values of `coins` are **unique**. * `0 <= amount <= 5000`
null
Array,Dynamic Programming
Medium
1393
1,380
welcome guys welcome to my legal solving session uh so this problem is called the lucky number in the matrix okay so i'll give an entire matrix and written all the non-key numbers written all the non-key numbers written all the non-key numbers okay so the logic numbers is what is element of elementary such as minimum adam in a row and a maximum is called okay so let me draw a picture i'll help you guys understand so this is a matrix m tyson so we need one we need a minimum in a row and a maximum in the column so mean in a row so we need uh this is minimum and uh the colon is maximum okay so uh so we need these lines minimum this nice maximum so minimum maximum okay so how about we see your example to get a feeling okay so the first example is this three seven eight okay so three seven eight nine eleven thirteen fifteen sixteen seventeen okay and uh so what remember we need a minimum in a row so the minimum is here uh this minimum is here and this minimum is here right these two three are minimum and uh okay and also a maximum in the column right so the only way is this 15. okay and then we see another example 1 4 2 9 3 8 7 15 16 17 twelve okay so we need a minimum in a row so minimally in the row mean row and the minimum in the row and who is the maximum uh this is not maximum and this is not a maximum so sorry only maximum is this 12 because 12 larger than two to seven are larger than two and seven okay and uh so from these uh well we can easily develop a algorithm so the easy way is that we first get the we can first get the get a maximum kind of minimum of a row so we will return a matrix up with a return list basically each list each number is the minimum of list so we take a minimum of list minimum list meaning of this minimum of this and we see which one is the maximum of columns then we are done okay so uh so this is m and n i think very easy so candy is empty at least for average m we just find a minimum okay so this candy just find the minimum and for the answer we just find that so this uh this matrix i j for i in the range and basically it's the column so i will i pick the column and i find that max and if max is in our candidate that means uh that number is a lucky number so with that answer just append that number okay so finally we just written answer we just written an answer that's it okay so you see uh very fast okay and i will see you guys in uh other videos and be sure to subscribe to my channel thanks
Lucky Numbers in a Matrix
number-of-closed-islands
Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_. A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column. **Example 1:** **Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\] **Output:** \[15\] **Explanation:** 15 is the only lucky number since it is the minimum in its row and the maximum in its column. **Example 2:** **Input:** matrix = \[\[1,10,4,2\],\[9,3,8,7\],\[15,16,17,12\]\] **Output:** \[12\] **Explanation:** 12 is the only lucky number since it is the minimum in its row and the maximum in its column. **Example 3:** **Input:** matrix = \[\[7,8\],\[1,2\]\] **Output:** \[7\] **Explanation:** 7 is the only lucky number since it is the minimum in its row and the maximum in its column. **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= n, m <= 50` * `1 <= matrix[i][j] <= 105`. * All elements in the matrix are distinct.
Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
null